1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
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 "llvm/ADT/TinyPtrVector.h"
16 #include "llvm/DebugInfo/CodeView/CVTypeDumper.h"
17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
18 #include "llvm/DebugInfo/CodeView/CodeView.h"
19 #include "llvm/DebugInfo/CodeView/Line.h"
20 #include "llvm/DebugInfo/CodeView/ModuleDebugInlineeLinesFragment.h"
21 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
22 #include "llvm/DebugInfo/CodeView/TypeDatabase.h"
23 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
24 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
25 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
26 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/BinaryByteStream.h"
33 #include "llvm/Support/BinaryStreamReader.h"
34 #include "llvm/Support/COFF.h"
35 #include "llvm/Support/ScopedPrinter.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 
40 using namespace llvm;
41 using namespace llvm::codeview;
42 
43 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
44     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
45       TypeTable(Allocator), CurFn(nullptr) {
46   // If module doesn't have named metadata anchors or COFF debug section
47   // is not available, skip any debug info related stuff.
48   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
49       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
50     Asm = nullptr;
51     return;
52   }
53 
54   // Tell MMI that we have debug info.
55   MMI->setDebugInfoAvailability(true);
56 }
57 
58 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
59   std::string &Filepath = FileToFilepathMap[File];
60   if (!Filepath.empty())
61     return Filepath;
62 
63   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
64 
65   // Clang emits directory and relative filename info into the IR, but CodeView
66   // operates on full paths.  We could change Clang to emit full paths too, but
67   // that would increase the IR size and probably not needed for other users.
68   // For now, just concatenate and canonicalize the path here.
69   if (Filename.find(':') == 1)
70     Filepath = Filename;
71   else
72     Filepath = (Dir + "\\" + Filename).str();
73 
74   // Canonicalize the path.  We have to do it textually because we may no longer
75   // have access the file in the filesystem.
76   // First, replace all slashes with backslashes.
77   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
78 
79   // Remove all "\.\" with "\".
80   size_t Cursor = 0;
81   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
82     Filepath.erase(Cursor, 2);
83 
84   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
85   // path should be well-formatted, e.g. start with a drive letter, etc.
86   Cursor = 0;
87   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
88     // Something's wrong if the path starts with "\..\", abort.
89     if (Cursor == 0)
90       break;
91 
92     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
93     if (PrevSlash == std::string::npos)
94       // Something's wrong, abort.
95       break;
96 
97     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
98     // The next ".." might be following the one we've just erased.
99     Cursor = PrevSlash;
100   }
101 
102   // Remove all duplicate backslashes.
103   Cursor = 0;
104   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
105     Filepath.erase(Cursor, 1);
106 
107   return Filepath;
108 }
109 
110 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
111   unsigned NextId = FileIdMap.size() + 1;
112   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
113   if (Insertion.second) {
114     // We have to compute the full filepath and emit a .cv_file directive.
115     StringRef FullPath = getFullFilepath(F);
116     bool Success = OS.EmitCVFileDirective(NextId, FullPath);
117     (void)Success;
118     assert(Success && ".cv_file directive failed");
119   }
120   return Insertion.first->second;
121 }
122 
123 CodeViewDebug::InlineSite &
124 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
125                              const DISubprogram *Inlinee) {
126   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
127   InlineSite *Site = &SiteInsertion.first->second;
128   if (SiteInsertion.second) {
129     unsigned ParentFuncId = CurFn->FuncId;
130     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
131       ParentFuncId =
132           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
133               .SiteFuncId;
134 
135     Site->SiteFuncId = NextFuncId++;
136     OS.EmitCVInlineSiteIdDirective(
137         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
138         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
139     Site->Inlinee = Inlinee;
140     InlinedSubprograms.insert(Inlinee);
141     getFuncIdForSubprogram(Inlinee);
142   }
143   return *Site;
144 }
145 
146 static StringRef getPrettyScopeName(const DIScope *Scope) {
147   StringRef ScopeName = Scope->getName();
148   if (!ScopeName.empty())
149     return ScopeName;
150 
151   switch (Scope->getTag()) {
152   case dwarf::DW_TAG_enumeration_type:
153   case dwarf::DW_TAG_class_type:
154   case dwarf::DW_TAG_structure_type:
155   case dwarf::DW_TAG_union_type:
156     return "<unnamed-tag>";
157   case dwarf::DW_TAG_namespace:
158     return "`anonymous namespace'";
159   }
160 
161   return StringRef();
162 }
163 
164 static const DISubprogram *getQualifiedNameComponents(
165     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
166   const DISubprogram *ClosestSubprogram = nullptr;
167   while (Scope != nullptr) {
168     if (ClosestSubprogram == nullptr)
169       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
170     StringRef ScopeName = getPrettyScopeName(Scope);
171     if (!ScopeName.empty())
172       QualifiedNameComponents.push_back(ScopeName);
173     Scope = Scope->getScope().resolve();
174   }
175   return ClosestSubprogram;
176 }
177 
178 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
179                                     StringRef TypeName) {
180   std::string FullyQualifiedName;
181   for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
182     FullyQualifiedName.append(QualifiedNameComponent);
183     FullyQualifiedName.append("::");
184   }
185   FullyQualifiedName.append(TypeName);
186   return FullyQualifiedName;
187 }
188 
189 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
190   SmallVector<StringRef, 5> QualifiedNameComponents;
191   getQualifiedNameComponents(Scope, QualifiedNameComponents);
192   return getQualifiedName(QualifiedNameComponents, Name);
193 }
194 
195 struct CodeViewDebug::TypeLoweringScope {
196   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
197   ~TypeLoweringScope() {
198     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
199     // inner TypeLoweringScopes don't attempt to emit deferred types.
200     if (CVD.TypeEmissionLevel == 1)
201       CVD.emitDeferredCompleteTypes();
202     --CVD.TypeEmissionLevel;
203   }
204   CodeViewDebug &CVD;
205 };
206 
207 static std::string getFullyQualifiedName(const DIScope *Ty) {
208   const DIScope *Scope = Ty->getScope().resolve();
209   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
210 }
211 
212 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
213   // No scope means global scope and that uses the zero index.
214   if (!Scope || isa<DIFile>(Scope))
215     return TypeIndex();
216 
217   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
218 
219   // Check if we've already translated this scope.
220   auto I = TypeIndices.find({Scope, nullptr});
221   if (I != TypeIndices.end())
222     return I->second;
223 
224   // Build the fully qualified name of the scope.
225   std::string ScopeName = getFullyQualifiedName(Scope);
226   StringIdRecord SID(TypeIndex(), ScopeName);
227   auto TI = TypeTable.writeKnownType(SID);
228   return recordTypeIndexForDINode(Scope, TI);
229 }
230 
231 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
232   assert(SP);
233 
234   // Check if we've already translated this subprogram.
235   auto I = TypeIndices.find({SP, nullptr});
236   if (I != TypeIndices.end())
237     return I->second;
238 
239   // The display name includes function template arguments. Drop them to match
240   // MSVC.
241   StringRef DisplayName = SP->getName().split('<').first;
242 
243   const DIScope *Scope = SP->getScope().resolve();
244   TypeIndex TI;
245   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
246     // If the scope is a DICompositeType, then this must be a method. Member
247     // function types take some special handling, and require access to the
248     // subprogram.
249     TypeIndex ClassType = getTypeIndex(Class);
250     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
251                                DisplayName);
252     TI = TypeTable.writeKnownType(MFuncId);
253   } else {
254     // Otherwise, this must be a free function.
255     TypeIndex ParentScope = getScopeIndex(Scope);
256     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
257     TI = TypeTable.writeKnownType(FuncId);
258   }
259 
260   return recordTypeIndexForDINode(SP, TI);
261 }
262 
263 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
264                                                const DICompositeType *Class) {
265   // Always use the method declaration as the key for the function type. The
266   // method declaration contains the this adjustment.
267   if (SP->getDeclaration())
268     SP = SP->getDeclaration();
269   assert(!SP->getDeclaration() && "should use declaration as key");
270 
271   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
272   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
273   auto I = TypeIndices.find({SP, Class});
274   if (I != TypeIndices.end())
275     return I->second;
276 
277   // Make sure complete type info for the class is emitted *after* the member
278   // function type, as the complete class type is likely to reference this
279   // member function type.
280   TypeLoweringScope S(*this);
281   TypeIndex TI =
282       lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
283   return recordTypeIndexForDINode(SP, TI, Class);
284 }
285 
286 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
287                                                   TypeIndex TI,
288                                                   const DIType *ClassTy) {
289   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
290   (void)InsertResult;
291   assert(InsertResult.second && "DINode was already assigned a type index");
292   return TI;
293 }
294 
295 unsigned CodeViewDebug::getPointerSizeInBytes() {
296   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
297 }
298 
299 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
300                                         const DILocation *InlinedAt) {
301   if (InlinedAt) {
302     // This variable was inlined. Associate it with the InlineSite.
303     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
304     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
305     Site.InlinedLocals.emplace_back(Var);
306   } else {
307     // This variable goes in the main ProcSym.
308     CurFn->Locals.emplace_back(Var);
309   }
310 }
311 
312 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
313                                const DILocation *Loc) {
314   auto B = Locs.begin(), E = Locs.end();
315   if (std::find(B, E, Loc) == E)
316     Locs.push_back(Loc);
317 }
318 
319 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
320                                         const MachineFunction *MF) {
321   // Skip this instruction if it has the same location as the previous one.
322   if (DL == CurFn->LastLoc)
323     return;
324 
325   const DIScope *Scope = DL.get()->getScope();
326   if (!Scope)
327     return;
328 
329   // Skip this line if it is longer than the maximum we can record.
330   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
331   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
332       LI.isNeverStepInto())
333     return;
334 
335   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
336   if (CI.getStartColumn() != DL.getCol())
337     return;
338 
339   if (!CurFn->HaveLineInfo)
340     CurFn->HaveLineInfo = true;
341   unsigned FileId = 0;
342   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
343     FileId = CurFn->LastFileId;
344   else
345     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
346   CurFn->LastLoc = DL;
347 
348   unsigned FuncId = CurFn->FuncId;
349   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
350     const DILocation *Loc = DL.get();
351 
352     // If this location was actually inlined from somewhere else, give it the ID
353     // of the inline call site.
354     FuncId =
355         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
356 
357     // Ensure we have links in the tree of inline call sites.
358     bool FirstLoc = true;
359     while ((SiteLoc = Loc->getInlinedAt())) {
360       InlineSite &Site =
361           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
362       if (!FirstLoc)
363         addLocIfNotPresent(Site.ChildSites, Loc);
364       FirstLoc = false;
365       Loc = SiteLoc;
366     }
367     addLocIfNotPresent(CurFn->ChildSites, Loc);
368   }
369 
370   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
371                         /*PrologueEnd=*/false, /*IsStmt=*/false,
372                         DL->getFilename(), SMLoc());
373 }
374 
375 void CodeViewDebug::emitCodeViewMagicVersion() {
376   OS.EmitValueToAlignment(4);
377   OS.AddComment("Debug section magic");
378   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
379 }
380 
381 void CodeViewDebug::endModule() {
382   if (!Asm || !MMI->hasDebugInfo())
383     return;
384 
385   assert(Asm != nullptr);
386 
387   // The COFF .debug$S section consists of several subsections, each starting
388   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
389   // of the payload followed by the payload itself.  The subsections are 4-byte
390   // aligned.
391 
392   // Use the generic .debug$S section, and make a subsection for all the inlined
393   // subprograms.
394   switchToDebugSectionForSymbol(nullptr);
395 
396   MCSymbol *CompilerInfo = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
397   emitCompilerInformation();
398   endCVSubsection(CompilerInfo);
399 
400   emitInlineeLinesSubsection();
401 
402   // Emit per-function debug information.
403   for (auto &P : FnDebugInfo)
404     if (!P.first->isDeclarationForLinker())
405       emitDebugInfoForFunction(P.first, P.second);
406 
407   // Emit global variable debug information.
408   setCurrentSubprogram(nullptr);
409   emitDebugInfoForGlobals();
410 
411   // Emit retained types.
412   emitDebugInfoForRetainedTypes();
413 
414   // Switch back to the generic .debug$S section after potentially processing
415   // comdat symbol sections.
416   switchToDebugSectionForSymbol(nullptr);
417 
418   // Emit UDT records for any types used by global variables.
419   if (!GlobalUDTs.empty()) {
420     MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
421     emitDebugInfoForUDTs(GlobalUDTs);
422     endCVSubsection(SymbolsEnd);
423   }
424 
425   // This subsection holds a file index to offset in string table table.
426   OS.AddComment("File index to string table offset subsection");
427   OS.EmitCVFileChecksumsDirective();
428 
429   // This subsection holds the string table.
430   OS.AddComment("String table");
431   OS.EmitCVStringTableDirective();
432 
433   // Emit type information last, so that any types we translate while emitting
434   // function info are included.
435   emitTypeInformation();
436 
437   clear();
438 }
439 
440 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
441   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
442   // after a fixed length portion of the record. The fixed length portion should
443   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
444   // overall record size is less than the maximum allowed.
445   unsigned MaxFixedRecordLength = 0xF00;
446   SmallString<32> NullTerminatedString(
447       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
448   NullTerminatedString.push_back('\0');
449   OS.EmitBytes(NullTerminatedString);
450 }
451 
452 void CodeViewDebug::emitTypeInformation() {
453   // Do nothing if we have no debug info or if no non-trivial types were emitted
454   // to TypeTable during codegen.
455   NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
456   if (!CU_Nodes)
457     return;
458   if (TypeTable.empty())
459     return;
460 
461   // Start the .debug$T section with 0x4.
462   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
463   emitCodeViewMagicVersion();
464 
465   SmallString<8> CommentPrefix;
466   if (OS.isVerboseAsm()) {
467     CommentPrefix += '\t';
468     CommentPrefix += Asm->MAI->getCommentString();
469     CommentPrefix += ' ';
470   }
471 
472   TypeDatabase TypeDB;
473   CVTypeDumper CVTD(TypeDB);
474   TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> Record) {
475     if (OS.isVerboseAsm()) {
476       // Emit a block comment describing the type record for readability.
477       SmallString<512> CommentBlock;
478       raw_svector_ostream CommentOS(CommentBlock);
479       ScopedPrinter SP(CommentOS);
480       SP.setPrefix(CommentPrefix);
481       TypeDumpVisitor TDV(TypeDB, &SP, false);
482       Error E = CVTD.dump(Record, TDV);
483       if (E) {
484         logAllUnhandledErrors(std::move(E), errs(), "error: ");
485         llvm_unreachable("produced malformed type record");
486       }
487       // emitRawComment will insert its own tab and comment string before
488       // the first line, so strip off our first one. It also prints its own
489       // newline.
490       OS.emitRawComment(
491           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
492     } else {
493 #ifndef NDEBUG
494       // Assert that the type data is valid even if we aren't dumping
495       // comments. The MSVC linker doesn't do much type record validation,
496       // so the first link of an invalid type record can succeed while
497       // subsequent links will fail with LNK1285.
498       BinaryByteStream Stream(Record, llvm::support::little);
499       CVTypeArray Types;
500       BinaryStreamReader Reader(Stream);
501       Error E = Reader.readArray(Types, Reader.getLength());
502       if (!E) {
503         TypeVisitorCallbacks C;
504         E = CVTypeVisitor(C).visitTypeStream(Types);
505       }
506       if (E) {
507         logAllUnhandledErrors(std::move(E), errs(), "error: ");
508         llvm_unreachable("produced malformed type record");
509       }
510 #endif
511     }
512     StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size());
513     OS.EmitBinaryData(S);
514   });
515 }
516 
517 namespace {
518 
519 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
520   switch (DWLang) {
521   case dwarf::DW_LANG_C:
522   case dwarf::DW_LANG_C89:
523   case dwarf::DW_LANG_C99:
524   case dwarf::DW_LANG_C11:
525   case dwarf::DW_LANG_ObjC:
526     return SourceLanguage::C;
527   case dwarf::DW_LANG_C_plus_plus:
528   case dwarf::DW_LANG_C_plus_plus_03:
529   case dwarf::DW_LANG_C_plus_plus_11:
530   case dwarf::DW_LANG_C_plus_plus_14:
531     return SourceLanguage::Cpp;
532   case dwarf::DW_LANG_Fortran77:
533   case dwarf::DW_LANG_Fortran90:
534   case dwarf::DW_LANG_Fortran03:
535   case dwarf::DW_LANG_Fortran08:
536     return SourceLanguage::Fortran;
537   case dwarf::DW_LANG_Pascal83:
538     return SourceLanguage::Pascal;
539   case dwarf::DW_LANG_Cobol74:
540   case dwarf::DW_LANG_Cobol85:
541     return SourceLanguage::Cobol;
542   case dwarf::DW_LANG_Java:
543     return SourceLanguage::Java;
544   default:
545     // There's no CodeView representation for this language, and CV doesn't
546     // have an "unknown" option for the language field, so we'll use MASM,
547     // as it's very low level.
548     return SourceLanguage::Masm;
549   }
550 }
551 
552 struct Version {
553   int Part[4];
554 };
555 
556 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
557 // the version number.
558 static Version parseVersion(StringRef Name) {
559   Version V = {{0}};
560   int N = 0;
561   for (const char C : Name) {
562     if (isdigit(C)) {
563       V.Part[N] *= 10;
564       V.Part[N] += C - '0';
565     } else if (C == '.') {
566       ++N;
567       if (N >= 4)
568         return V;
569     } else if (N > 0)
570       return V;
571   }
572   return V;
573 }
574 
575 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
576   switch (Type) {
577     case Triple::ArchType::x86:
578       return CPUType::Pentium3;
579     case Triple::ArchType::x86_64:
580       return CPUType::X64;
581     case Triple::ArchType::thumb:
582       return CPUType::Thumb;
583     default:
584       report_fatal_error("target architecture doesn't map to a CodeView "
585                          "CPUType");
586   }
587 }
588 
589 }  // anonymous namespace
590 
591 void CodeViewDebug::emitCompilerInformation() {
592   MCContext &Context = MMI->getContext();
593   MCSymbol *CompilerBegin = Context.createTempSymbol(),
594            *CompilerEnd = Context.createTempSymbol();
595   OS.AddComment("Record length");
596   OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
597   OS.EmitLabel(CompilerBegin);
598   OS.AddComment("Record kind: S_COMPILE3");
599   OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
600   uint32_t Flags = 0;
601 
602   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
603   const MDNode *Node = *CUs->operands().begin();
604   const auto *CU = cast<DICompileUnit>(Node);
605 
606   // The low byte of the flags indicates the source language.
607   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
608   // TODO:  Figure out which other flags need to be set.
609 
610   OS.AddComment("Flags and language");
611   OS.EmitIntValue(Flags, 4);
612 
613   OS.AddComment("CPUType");
614   CPUType CPU =
615       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
616   OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
617 
618   StringRef CompilerVersion = CU->getProducer();
619   Version FrontVer = parseVersion(CompilerVersion);
620   OS.AddComment("Frontend version");
621   for (int N = 0; N < 4; ++N)
622     OS.EmitIntValue(FrontVer.Part[N], 2);
623 
624   // Some Microsoft tools, like Binscope, expect a backend version number of at
625   // least 8.something, so we'll coerce the LLVM version into a form that
626   // guarantees it'll be big enough without really lying about the version.
627   int Major = 1000 * LLVM_VERSION_MAJOR +
628               10 * LLVM_VERSION_MINOR +
629               LLVM_VERSION_PATCH;
630   // Clamp it for builds that use unusually large version numbers.
631   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
632   Version BackVer = {{ Major, 0, 0, 0 }};
633   OS.AddComment("Backend version");
634   for (int N = 0; N < 4; ++N)
635     OS.EmitIntValue(BackVer.Part[N], 2);
636 
637   OS.AddComment("Null-terminated compiler version string");
638   emitNullTerminatedSymbolName(OS, CompilerVersion);
639 
640   OS.EmitLabel(CompilerEnd);
641 }
642 
643 void CodeViewDebug::emitInlineeLinesSubsection() {
644   if (InlinedSubprograms.empty())
645     return;
646 
647   OS.AddComment("Inlinee lines subsection");
648   MCSymbol *InlineEnd =
649       beginCVSubsection(ModuleDebugFragmentKind::InlineeLines);
650 
651   // We don't provide any extra file info.
652   // FIXME: Find out if debuggers use this info.
653   OS.AddComment("Inlinee lines signature");
654   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
655 
656   for (const DISubprogram *SP : InlinedSubprograms) {
657     assert(TypeIndices.count({SP, nullptr}));
658     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
659 
660     OS.AddBlankLine();
661     unsigned FileId = maybeRecordFile(SP->getFile());
662     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
663                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
664     OS.AddBlankLine();
665     // The filechecksum table uses 8 byte entries for now, and file ids start at
666     // 1.
667     unsigned FileOffset = (FileId - 1) * 8;
668     OS.AddComment("Type index of inlined function");
669     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
670     OS.AddComment("Offset into filechecksum table");
671     OS.EmitIntValue(FileOffset, 4);
672     OS.AddComment("Starting line number");
673     OS.EmitIntValue(SP->getLine(), 4);
674   }
675 
676   endCVSubsection(InlineEnd);
677 }
678 
679 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
680                                         const DILocation *InlinedAt,
681                                         const InlineSite &Site) {
682   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
683            *InlineEnd = MMI->getContext().createTempSymbol();
684 
685   assert(TypeIndices.count({Site.Inlinee, nullptr}));
686   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
687 
688   // SymbolRecord
689   OS.AddComment("Record length");
690   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
691   OS.EmitLabel(InlineBegin);
692   OS.AddComment("Record kind: S_INLINESITE");
693   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
694 
695   OS.AddComment("PtrParent");
696   OS.EmitIntValue(0, 4);
697   OS.AddComment("PtrEnd");
698   OS.EmitIntValue(0, 4);
699   OS.AddComment("Inlinee type index");
700   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
701 
702   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
703   unsigned StartLineNum = Site.Inlinee->getLine();
704 
705   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
706                                     FI.Begin, FI.End);
707 
708   OS.EmitLabel(InlineEnd);
709 
710   emitLocalVariableList(Site.InlinedLocals);
711 
712   // Recurse on child inlined call sites before closing the scope.
713   for (const DILocation *ChildSite : Site.ChildSites) {
714     auto I = FI.InlineSites.find(ChildSite);
715     assert(I != FI.InlineSites.end() &&
716            "child site not in function inline site map");
717     emitInlinedCallSite(FI, ChildSite, I->second);
718   }
719 
720   // Close the scope.
721   OS.AddComment("Record length");
722   OS.EmitIntValue(2, 2);                                  // RecordLength
723   OS.AddComment("Record kind: S_INLINESITE_END");
724   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
725 }
726 
727 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
728   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
729   // comdat key. A section may be comdat because of -ffunction-sections or
730   // because it is comdat in the IR.
731   MCSectionCOFF *GVSec =
732       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
733   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
734 
735   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
736       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
737   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
738 
739   OS.SwitchSection(DebugSec);
740 
741   // Emit the magic version number if this is the first time we've switched to
742   // this section.
743   if (ComdatDebugSections.insert(DebugSec).second)
744     emitCodeViewMagicVersion();
745 }
746 
747 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
748                                              FunctionInfo &FI) {
749   // For each function there is a separate subsection
750   // which holds the PC to file:line table.
751   const MCSymbol *Fn = Asm->getSymbol(GV);
752   assert(Fn);
753 
754   // Switch to the to a comdat section, if appropriate.
755   switchToDebugSectionForSymbol(Fn);
756 
757   std::string FuncName;
758   auto *SP = GV->getSubprogram();
759   assert(SP);
760   setCurrentSubprogram(SP);
761 
762   // If we have a display name, build the fully qualified name by walking the
763   // chain of scopes.
764   if (!SP->getName().empty())
765     FuncName =
766         getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
767 
768   // If our DISubprogram name is empty, use the mangled name.
769   if (FuncName.empty())
770     FuncName = GlobalValue::getRealLinkageName(GV->getName());
771 
772   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
773   OS.AddComment("Symbol subsection for " + Twine(FuncName));
774   MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
775   {
776     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
777              *ProcRecordEnd = MMI->getContext().createTempSymbol();
778     OS.AddComment("Record length");
779     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
780     OS.EmitLabel(ProcRecordBegin);
781 
782     if (GV->hasLocalLinkage()) {
783       OS.AddComment("Record kind: S_LPROC32_ID");
784       OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
785     } else {
786       OS.AddComment("Record kind: S_GPROC32_ID");
787       OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
788     }
789 
790     // These fields are filled in by tools like CVPACK which run after the fact.
791     OS.AddComment("PtrParent");
792     OS.EmitIntValue(0, 4);
793     OS.AddComment("PtrEnd");
794     OS.EmitIntValue(0, 4);
795     OS.AddComment("PtrNext");
796     OS.EmitIntValue(0, 4);
797     // This is the important bit that tells the debugger where the function
798     // code is located and what's its size:
799     OS.AddComment("Code size");
800     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
801     OS.AddComment("Offset after prologue");
802     OS.EmitIntValue(0, 4);
803     OS.AddComment("Offset before epilogue");
804     OS.EmitIntValue(0, 4);
805     OS.AddComment("Function type index");
806     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
807     OS.AddComment("Function section relative address");
808     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
809     OS.AddComment("Function section index");
810     OS.EmitCOFFSectionIndex(Fn);
811     OS.AddComment("Flags");
812     OS.EmitIntValue(0, 1);
813     // Emit the function display name as a null-terminated string.
814     OS.AddComment("Function name");
815     // Truncate the name so we won't overflow the record length field.
816     emitNullTerminatedSymbolName(OS, FuncName);
817     OS.EmitLabel(ProcRecordEnd);
818 
819     emitLocalVariableList(FI.Locals);
820 
821     // Emit inlined call site information. Only emit functions inlined directly
822     // into the parent function. We'll emit the other sites recursively as part
823     // of their parent inline site.
824     for (const DILocation *InlinedAt : FI.ChildSites) {
825       auto I = FI.InlineSites.find(InlinedAt);
826       assert(I != FI.InlineSites.end() &&
827              "child site not in function inline site map");
828       emitInlinedCallSite(FI, InlinedAt, I->second);
829     }
830 
831     if (SP != nullptr)
832       emitDebugInfoForUDTs(LocalUDTs);
833 
834     // We're done with this function.
835     OS.AddComment("Record length");
836     OS.EmitIntValue(0x0002, 2);
837     OS.AddComment("Record kind: S_PROC_ID_END");
838     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
839   }
840   endCVSubsection(SymbolsEnd);
841 
842   // We have an assembler directive that takes care of the whole line table.
843   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
844 }
845 
846 CodeViewDebug::LocalVarDefRange
847 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
848   LocalVarDefRange DR;
849   DR.InMemory = -1;
850   DR.DataOffset = Offset;
851   assert(DR.DataOffset == Offset && "truncation");
852   DR.IsSubfield = 0;
853   DR.StructOffset = 0;
854   DR.CVRegister = CVRegister;
855   return DR;
856 }
857 
858 CodeViewDebug::LocalVarDefRange
859 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
860                                      int Offset, bool IsSubfield,
861                                      uint16_t StructOffset) {
862   LocalVarDefRange DR;
863   DR.InMemory = InMemory;
864   DR.DataOffset = Offset;
865   DR.IsSubfield = IsSubfield;
866   DR.StructOffset = StructOffset;
867   DR.CVRegister = CVRegister;
868   return DR;
869 }
870 
871 void CodeViewDebug::collectVariableInfoFromMFTable(
872     DenseSet<InlinedVariable> &Processed) {
873   const MachineFunction &MF = *Asm->MF;
874   const TargetSubtargetInfo &TSI = MF.getSubtarget();
875   const TargetFrameLowering *TFI = TSI.getFrameLowering();
876   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
877 
878   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
879     if (!VI.Var)
880       continue;
881     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
882            "Expected inlined-at fields to agree");
883 
884     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
885     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
886 
887     // If variable scope is not found then skip this variable.
888     if (!Scope)
889       continue;
890 
891     // Get the frame register used and the offset.
892     unsigned FrameReg = 0;
893     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
894     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
895 
896     // Calculate the label ranges.
897     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
898     for (const InsnRange &Range : Scope->getRanges()) {
899       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
900       const MCSymbol *End = getLabelAfterInsn(Range.second);
901       End = End ? End : Asm->getFunctionEnd();
902       DefRange.Ranges.emplace_back(Begin, End);
903     }
904 
905     LocalVariable Var;
906     Var.DIVar = VI.Var;
907     Var.DefRanges.emplace_back(std::move(DefRange));
908     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
909   }
910 }
911 
912 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
913   DenseSet<InlinedVariable> Processed;
914   // Grab the variable info that was squirreled away in the MMI side-table.
915   collectVariableInfoFromMFTable(Processed);
916 
917   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
918 
919   for (const auto &I : DbgValues) {
920     InlinedVariable IV = I.first;
921     if (Processed.count(IV))
922       continue;
923     const DILocalVariable *DIVar = IV.first;
924     const DILocation *InlinedAt = IV.second;
925 
926     // Instruction ranges, specifying where IV is accessible.
927     const auto &Ranges = I.second;
928 
929     LexicalScope *Scope = nullptr;
930     if (InlinedAt)
931       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
932     else
933       Scope = LScopes.findLexicalScope(DIVar->getScope());
934     // If variable scope is not found then skip this variable.
935     if (!Scope)
936       continue;
937 
938     LocalVariable Var;
939     Var.DIVar = DIVar;
940 
941     // Calculate the definition ranges.
942     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
943       const InsnRange &Range = *I;
944       const MachineInstr *DVInst = Range.first;
945       assert(DVInst->isDebugValue() && "Invalid History entry");
946       const DIExpression *DIExpr = DVInst->getDebugExpression();
947       bool IsSubfield = false;
948       unsigned StructOffset = 0;
949 
950       // Handle fragments.
951       auto Fragment = DIExpr->getFragmentInfo();
952       if (Fragment) {
953         IsSubfield = true;
954         StructOffset = Fragment->OffsetInBits / 8;
955       } else if (DIExpr->getNumElements() > 0) {
956         continue; // Ignore unrecognized exprs.
957       }
958 
959       // Bail if operand 0 is not a valid register. This means the variable is a
960       // simple constant, or is described by a complex expression.
961       // FIXME: Find a way to represent constant variables, since they are
962       // relatively common.
963       unsigned Reg =
964           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
965       if (Reg == 0)
966         continue;
967 
968       // Handle the two cases we can handle: indirect in memory and in register.
969       unsigned CVReg = TRI->getCodeViewRegNum(Reg);
970       bool InMemory = DVInst->getOperand(1).isImm();
971       int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
972       {
973         LocalVarDefRange DR;
974         DR.CVRegister = CVReg;
975         DR.InMemory = InMemory;
976         DR.DataOffset = Offset;
977         DR.IsSubfield = IsSubfield;
978         DR.StructOffset = StructOffset;
979 
980         if (Var.DefRanges.empty() ||
981             Var.DefRanges.back().isDifferentLocation(DR)) {
982           Var.DefRanges.emplace_back(std::move(DR));
983         }
984       }
985 
986       // Compute the label range.
987       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
988       const MCSymbol *End = getLabelAfterInsn(Range.second);
989       if (!End) {
990         // This range is valid until the next overlapping bitpiece. In the
991         // common case, ranges will not be bitpieces, so they will overlap.
992         auto J = std::next(I);
993         while (J != E &&
994                !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
995           ++J;
996         if (J != E)
997           End = getLabelBeforeInsn(J->first);
998         else
999           End = Asm->getFunctionEnd();
1000       }
1001 
1002       // If the last range end is our begin, just extend the last range.
1003       // Otherwise make a new range.
1004       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1005           Var.DefRanges.back().Ranges;
1006       if (!Ranges.empty() && Ranges.back().second == Begin)
1007         Ranges.back().second = End;
1008       else
1009         Ranges.emplace_back(Begin, End);
1010 
1011       // FIXME: Do more range combining.
1012     }
1013 
1014     recordLocalVariable(std::move(Var), InlinedAt);
1015   }
1016 }
1017 
1018 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1019   const Function *GV = MF->getFunction();
1020   assert(FnDebugInfo.count(GV) == false);
1021   CurFn = &FnDebugInfo[GV];
1022   CurFn->FuncId = NextFuncId++;
1023   CurFn->Begin = Asm->getFunctionBegin();
1024 
1025   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1026 
1027   // Find the end of the function prolog.  First known non-DBG_VALUE and
1028   // non-frame setup location marks the beginning of the function body.
1029   // FIXME: is there a simpler a way to do this? Can we just search
1030   // for the first instruction of the function, not the last of the prolog?
1031   DebugLoc PrologEndLoc;
1032   bool EmptyPrologue = true;
1033   for (const auto &MBB : *MF) {
1034     for (const auto &MI : MBB) {
1035       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1036           MI.getDebugLoc()) {
1037         PrologEndLoc = MI.getDebugLoc();
1038         break;
1039       } else if (!MI.isDebugValue()) {
1040         EmptyPrologue = false;
1041       }
1042     }
1043   }
1044 
1045   // Record beginning of function if we have a non-empty prologue.
1046   if (PrologEndLoc && !EmptyPrologue) {
1047     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1048     maybeRecordLocation(FnStartDL, MF);
1049   }
1050 }
1051 
1052 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
1053   // Don't record empty UDTs.
1054   if (Ty->getName().empty())
1055     return;
1056 
1057   SmallVector<StringRef, 5> QualifiedNameComponents;
1058   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1059       Ty->getScope().resolve(), QualifiedNameComponents);
1060 
1061   std::string FullyQualifiedName =
1062       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1063 
1064   if (ClosestSubprogram == nullptr)
1065     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1066   else if (ClosestSubprogram == CurrentSubprogram)
1067     LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1068 
1069   // TODO: What if the ClosestSubprogram is neither null or the current
1070   // subprogram?  Currently, the UDT just gets dropped on the floor.
1071   //
1072   // The current behavior is not desirable.  To get maximal fidelity, we would
1073   // need to perform all type translation before beginning emission of .debug$S
1074   // and then make LocalUDTs a member of FunctionInfo
1075 }
1076 
1077 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1078   // Generic dispatch for lowering an unknown type.
1079   switch (Ty->getTag()) {
1080   case dwarf::DW_TAG_array_type:
1081     return lowerTypeArray(cast<DICompositeType>(Ty));
1082   case dwarf::DW_TAG_typedef:
1083     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1084   case dwarf::DW_TAG_base_type:
1085     return lowerTypeBasic(cast<DIBasicType>(Ty));
1086   case dwarf::DW_TAG_pointer_type:
1087     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1088       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1089     LLVM_FALLTHROUGH;
1090   case dwarf::DW_TAG_reference_type:
1091   case dwarf::DW_TAG_rvalue_reference_type:
1092     return lowerTypePointer(cast<DIDerivedType>(Ty));
1093   case dwarf::DW_TAG_ptr_to_member_type:
1094     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1095   case dwarf::DW_TAG_const_type:
1096   case dwarf::DW_TAG_volatile_type:
1097   // TODO: add support for DW_TAG_atomic_type here
1098     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1099   case dwarf::DW_TAG_subroutine_type:
1100     if (ClassTy) {
1101       // The member function type of a member function pointer has no
1102       // ThisAdjustment.
1103       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1104                                      /*ThisAdjustment=*/0);
1105     }
1106     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1107   case dwarf::DW_TAG_enumeration_type:
1108     return lowerTypeEnum(cast<DICompositeType>(Ty));
1109   case dwarf::DW_TAG_class_type:
1110   case dwarf::DW_TAG_structure_type:
1111     return lowerTypeClass(cast<DICompositeType>(Ty));
1112   case dwarf::DW_TAG_union_type:
1113     return lowerTypeUnion(cast<DICompositeType>(Ty));
1114   default:
1115     // Use the null type index.
1116     return TypeIndex();
1117   }
1118 }
1119 
1120 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1121   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1122   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
1123   StringRef TypeName = Ty->getName();
1124 
1125   addToUDTs(Ty, UnderlyingTypeIndex);
1126 
1127   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1128       TypeName == "HRESULT")
1129     return TypeIndex(SimpleTypeKind::HResult);
1130   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1131       TypeName == "wchar_t")
1132     return TypeIndex(SimpleTypeKind::WideCharacter);
1133 
1134   return UnderlyingTypeIndex;
1135 }
1136 
1137 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1138   DITypeRef ElementTypeRef = Ty->getBaseType();
1139   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1140   // IndexType is size_t, which depends on the bitness of the target.
1141   TypeIndex IndexType = Asm->TM.getPointerSize() == 8
1142                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1143                             : TypeIndex(SimpleTypeKind::UInt32Long);
1144 
1145   uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1146 
1147   // Add subranges to array type.
1148   DINodeArray Elements = Ty->getElements();
1149   for (int i = Elements.size() - 1; i >= 0; --i) {
1150     const DINode *Element = Elements[i];
1151     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1152 
1153     const DISubrange *Subrange = cast<DISubrange>(Element);
1154     assert(Subrange->getLowerBound() == 0 &&
1155            "codeview doesn't support subranges with lower bounds");
1156     int64_t Count = Subrange->getCount();
1157 
1158     // Variable Length Array (VLA) has Count equal to '-1'.
1159     // Replace with Count '1', assume it is the minimum VLA length.
1160     // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1161     if (Count == -1)
1162       Count = 1;
1163 
1164     // Update the element size and element type index for subsequent subranges.
1165     ElementSize *= Count;
1166 
1167     // If this is the outermost array, use the size from the array. It will be
1168     // more accurate if we had a VLA or an incomplete element type size.
1169     uint64_t ArraySize =
1170         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1171 
1172     StringRef Name = (i == 0) ? Ty->getName() : "";
1173     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1174     ElementTypeIndex = TypeTable.writeKnownType(AR);
1175   }
1176 
1177   return ElementTypeIndex;
1178 }
1179 
1180 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1181   TypeIndex Index;
1182   dwarf::TypeKind Kind;
1183   uint32_t ByteSize;
1184 
1185   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1186   ByteSize = Ty->getSizeInBits() / 8;
1187 
1188   SimpleTypeKind STK = SimpleTypeKind::None;
1189   switch (Kind) {
1190   case dwarf::DW_ATE_address:
1191     // FIXME: Translate
1192     break;
1193   case dwarf::DW_ATE_boolean:
1194     switch (ByteSize) {
1195     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1196     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1197     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1198     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1199     case 16: STK = SimpleTypeKind::Boolean128; break;
1200     }
1201     break;
1202   case dwarf::DW_ATE_complex_float:
1203     switch (ByteSize) {
1204     case 2:  STK = SimpleTypeKind::Complex16;  break;
1205     case 4:  STK = SimpleTypeKind::Complex32;  break;
1206     case 8:  STK = SimpleTypeKind::Complex64;  break;
1207     case 10: STK = SimpleTypeKind::Complex80;  break;
1208     case 16: STK = SimpleTypeKind::Complex128; break;
1209     }
1210     break;
1211   case dwarf::DW_ATE_float:
1212     switch (ByteSize) {
1213     case 2:  STK = SimpleTypeKind::Float16;  break;
1214     case 4:  STK = SimpleTypeKind::Float32;  break;
1215     case 6:  STK = SimpleTypeKind::Float48;  break;
1216     case 8:  STK = SimpleTypeKind::Float64;  break;
1217     case 10: STK = SimpleTypeKind::Float80;  break;
1218     case 16: STK = SimpleTypeKind::Float128; break;
1219     }
1220     break;
1221   case dwarf::DW_ATE_signed:
1222     switch (ByteSize) {
1223     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1224     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1225     case 4:  STK = SimpleTypeKind::Int32;           break;
1226     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1227     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1228     }
1229     break;
1230   case dwarf::DW_ATE_unsigned:
1231     switch (ByteSize) {
1232     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1233     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1234     case 4:  STK = SimpleTypeKind::UInt32;            break;
1235     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1236     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1237     }
1238     break;
1239   case dwarf::DW_ATE_UTF:
1240     switch (ByteSize) {
1241     case 2: STK = SimpleTypeKind::Character16; break;
1242     case 4: STK = SimpleTypeKind::Character32; break;
1243     }
1244     break;
1245   case dwarf::DW_ATE_signed_char:
1246     if (ByteSize == 1)
1247       STK = SimpleTypeKind::SignedCharacter;
1248     break;
1249   case dwarf::DW_ATE_unsigned_char:
1250     if (ByteSize == 1)
1251       STK = SimpleTypeKind::UnsignedCharacter;
1252     break;
1253   default:
1254     break;
1255   }
1256 
1257   // Apply some fixups based on the source-level type name.
1258   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1259     STK = SimpleTypeKind::Int32Long;
1260   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1261     STK = SimpleTypeKind::UInt32Long;
1262   if (STK == SimpleTypeKind::UInt16Short &&
1263       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1264     STK = SimpleTypeKind::WideCharacter;
1265   if ((STK == SimpleTypeKind::SignedCharacter ||
1266        STK == SimpleTypeKind::UnsignedCharacter) &&
1267       Ty->getName() == "char")
1268     STK = SimpleTypeKind::NarrowCharacter;
1269 
1270   return TypeIndex(STK);
1271 }
1272 
1273 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1274   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1275 
1276   // Pointers to simple types can use SimpleTypeMode, rather than having a
1277   // dedicated pointer type record.
1278   if (PointeeTI.isSimple() &&
1279       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1280       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1281     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1282                               ? SimpleTypeMode::NearPointer64
1283                               : SimpleTypeMode::NearPointer32;
1284     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1285   }
1286 
1287   PointerKind PK =
1288       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1289   PointerMode PM = PointerMode::Pointer;
1290   switch (Ty->getTag()) {
1291   default: llvm_unreachable("not a pointer tag type");
1292   case dwarf::DW_TAG_pointer_type:
1293     PM = PointerMode::Pointer;
1294     break;
1295   case dwarf::DW_TAG_reference_type:
1296     PM = PointerMode::LValueReference;
1297     break;
1298   case dwarf::DW_TAG_rvalue_reference_type:
1299     PM = PointerMode::RValueReference;
1300     break;
1301   }
1302   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1303   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1304   // do.
1305   PointerOptions PO = PointerOptions::None;
1306   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1307   return TypeTable.writeKnownType(PR);
1308 }
1309 
1310 static PointerToMemberRepresentation
1311 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1312   // SizeInBytes being zero generally implies that the member pointer type was
1313   // incomplete, which can happen if it is part of a function prototype. In this
1314   // case, use the unknown model instead of the general model.
1315   if (IsPMF) {
1316     switch (Flags & DINode::FlagPtrToMemberRep) {
1317     case 0:
1318       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1319                               : PointerToMemberRepresentation::GeneralFunction;
1320     case DINode::FlagSingleInheritance:
1321       return PointerToMemberRepresentation::SingleInheritanceFunction;
1322     case DINode::FlagMultipleInheritance:
1323       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1324     case DINode::FlagVirtualInheritance:
1325       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1326     }
1327   } else {
1328     switch (Flags & DINode::FlagPtrToMemberRep) {
1329     case 0:
1330       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1331                               : PointerToMemberRepresentation::GeneralData;
1332     case DINode::FlagSingleInheritance:
1333       return PointerToMemberRepresentation::SingleInheritanceData;
1334     case DINode::FlagMultipleInheritance:
1335       return PointerToMemberRepresentation::MultipleInheritanceData;
1336     case DINode::FlagVirtualInheritance:
1337       return PointerToMemberRepresentation::VirtualInheritanceData;
1338     }
1339   }
1340   llvm_unreachable("invalid ptr to member representation");
1341 }
1342 
1343 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1344   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1345   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1346   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1347   PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1348                                                  : PointerKind::Near32;
1349   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1350   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1351                          : PointerMode::PointerToDataMember;
1352   PointerOptions PO = PointerOptions::None; // FIXME
1353   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1354   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1355   MemberPointerInfo MPI(
1356       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1357   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1358   return TypeTable.writeKnownType(PR);
1359 }
1360 
1361 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1362 /// have a translation, use the NearC convention.
1363 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1364   switch (DwarfCC) {
1365   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1366   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1367   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1368   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1369   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1370   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1371   }
1372   return CallingConvention::NearC;
1373 }
1374 
1375 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1376   ModifierOptions Mods = ModifierOptions::None;
1377   bool IsModifier = true;
1378   const DIType *BaseTy = Ty;
1379   while (IsModifier && BaseTy) {
1380     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1381     switch (BaseTy->getTag()) {
1382     case dwarf::DW_TAG_const_type:
1383       Mods |= ModifierOptions::Const;
1384       break;
1385     case dwarf::DW_TAG_volatile_type:
1386       Mods |= ModifierOptions::Volatile;
1387       break;
1388     default:
1389       IsModifier = false;
1390       break;
1391     }
1392     if (IsModifier)
1393       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1394   }
1395   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1396   ModifierRecord MR(ModifiedTI, Mods);
1397   return TypeTable.writeKnownType(MR);
1398 }
1399 
1400 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1401   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1402   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1403     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1404 
1405   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1406   ArrayRef<TypeIndex> ArgTypeIndices = None;
1407   if (!ReturnAndArgTypeIndices.empty()) {
1408     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1409     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1410     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1411   }
1412 
1413   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1414   TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1415 
1416   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1417 
1418   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1419                             ArgTypeIndices.size(), ArgListIndex);
1420   return TypeTable.writeKnownType(Procedure);
1421 }
1422 
1423 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1424                                                  const DIType *ClassTy,
1425                                                  int ThisAdjustment) {
1426   // Lower the containing class type.
1427   TypeIndex ClassType = getTypeIndex(ClassTy);
1428 
1429   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1430   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1431     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1432 
1433   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1434   ArrayRef<TypeIndex> ArgTypeIndices = None;
1435   if (!ReturnAndArgTypeIndices.empty()) {
1436     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1437     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1438     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1439   }
1440   TypeIndex ThisTypeIndex = TypeIndex::Void();
1441   if (!ArgTypeIndices.empty()) {
1442     ThisTypeIndex = ArgTypeIndices.front();
1443     ArgTypeIndices = ArgTypeIndices.drop_front();
1444   }
1445 
1446   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1447   TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
1448 
1449   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1450 
1451   // TODO: Need to use the correct values for:
1452   //       FunctionOptions
1453   //       ThisPointerAdjustment.
1454   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1455                            FunctionOptions::None, ArgTypeIndices.size(),
1456                            ArgListIndex, ThisAdjustment);
1457   TypeIndex TI = TypeTable.writeKnownType(MFR);
1458 
1459   return TI;
1460 }
1461 
1462 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1463   unsigned VSlotCount =
1464       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1465   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1466 
1467   VFTableShapeRecord VFTSR(Slots);
1468   return TypeTable.writeKnownType(VFTSR);
1469 }
1470 
1471 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1472   switch (Flags & DINode::FlagAccessibility) {
1473   case DINode::FlagPrivate:   return MemberAccess::Private;
1474   case DINode::FlagPublic:    return MemberAccess::Public;
1475   case DINode::FlagProtected: return MemberAccess::Protected;
1476   case 0:
1477     // If there was no explicit access control, provide the default for the tag.
1478     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1479                                                  : MemberAccess::Public;
1480   }
1481   llvm_unreachable("access flags are exclusive");
1482 }
1483 
1484 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1485   if (SP->isArtificial())
1486     return MethodOptions::CompilerGenerated;
1487 
1488   // FIXME: Handle other MethodOptions.
1489 
1490   return MethodOptions::None;
1491 }
1492 
1493 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1494                                            bool Introduced) {
1495   switch (SP->getVirtuality()) {
1496   case dwarf::DW_VIRTUALITY_none:
1497     break;
1498   case dwarf::DW_VIRTUALITY_virtual:
1499     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1500   case dwarf::DW_VIRTUALITY_pure_virtual:
1501     return Introduced ? MethodKind::PureIntroducingVirtual
1502                       : MethodKind::PureVirtual;
1503   default:
1504     llvm_unreachable("unhandled virtuality case");
1505   }
1506 
1507   // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1508 
1509   return MethodKind::Vanilla;
1510 }
1511 
1512 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1513   switch (Ty->getTag()) {
1514   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1515   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1516   }
1517   llvm_unreachable("unexpected tag");
1518 }
1519 
1520 /// Return ClassOptions that should be present on both the forward declaration
1521 /// and the defintion of a tag type.
1522 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1523   ClassOptions CO = ClassOptions::None;
1524 
1525   // MSVC always sets this flag, even for local types. Clang doesn't always
1526   // appear to give every type a linkage name, which may be problematic for us.
1527   // FIXME: Investigate the consequences of not following them here.
1528   if (!Ty->getIdentifier().empty())
1529     CO |= ClassOptions::HasUniqueName;
1530 
1531   // Put the Nested flag on a type if it appears immediately inside a tag type.
1532   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1533   // here. That flag is only set on definitions, and not forward declarations.
1534   const DIScope *ImmediateScope = Ty->getScope().resolve();
1535   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1536     CO |= ClassOptions::Nested;
1537 
1538   // Put the Scoped flag on function-local types.
1539   for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1540        Scope = Scope->getScope().resolve()) {
1541     if (isa<DISubprogram>(Scope)) {
1542       CO |= ClassOptions::Scoped;
1543       break;
1544     }
1545   }
1546 
1547   return CO;
1548 }
1549 
1550 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1551   ClassOptions CO = getCommonClassOptions(Ty);
1552   TypeIndex FTI;
1553   unsigned EnumeratorCount = 0;
1554 
1555   if (Ty->isForwardDecl()) {
1556     CO |= ClassOptions::ForwardReference;
1557   } else {
1558     FieldListRecordBuilder FLRB(TypeTable);
1559 
1560     FLRB.begin();
1561     for (const DINode *Element : Ty->getElements()) {
1562       // We assume that the frontend provides all members in source declaration
1563       // order, which is what MSVC does.
1564       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1565         EnumeratorRecord ER(MemberAccess::Public,
1566                             APSInt::getUnsigned(Enumerator->getValue()),
1567                             Enumerator->getName());
1568         FLRB.writeMemberType(ER);
1569         EnumeratorCount++;
1570       }
1571     }
1572     FTI = FLRB.end();
1573   }
1574 
1575   std::string FullName = getFullyQualifiedName(Ty);
1576 
1577   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1578                 getTypeIndex(Ty->getBaseType()));
1579   return TypeTable.writeKnownType(ER);
1580 }
1581 
1582 //===----------------------------------------------------------------------===//
1583 // ClassInfo
1584 //===----------------------------------------------------------------------===//
1585 
1586 struct llvm::ClassInfo {
1587   struct MemberInfo {
1588     const DIDerivedType *MemberTypeNode;
1589     uint64_t BaseOffset;
1590   };
1591   // [MemberInfo]
1592   typedef std::vector<MemberInfo> MemberList;
1593 
1594   typedef TinyPtrVector<const DISubprogram *> MethodsList;
1595   // MethodName -> MethodsList
1596   typedef MapVector<MDString *, MethodsList> MethodsMap;
1597 
1598   /// Base classes.
1599   std::vector<const DIDerivedType *> Inheritance;
1600 
1601   /// Direct members.
1602   MemberList Members;
1603   // Direct overloaded methods gathered by name.
1604   MethodsMap Methods;
1605 
1606   TypeIndex VShapeTI;
1607 
1608   std::vector<const DICompositeType *> NestedClasses;
1609 };
1610 
1611 void CodeViewDebug::clear() {
1612   assert(CurFn == nullptr);
1613   FileIdMap.clear();
1614   FnDebugInfo.clear();
1615   FileToFilepathMap.clear();
1616   LocalUDTs.clear();
1617   GlobalUDTs.clear();
1618   TypeIndices.clear();
1619   CompleteTypeIndices.clear();
1620 }
1621 
1622 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1623                                       const DIDerivedType *DDTy) {
1624   if (!DDTy->getName().empty()) {
1625     Info.Members.push_back({DDTy, 0});
1626     return;
1627   }
1628   // An unnamed member must represent a nested struct or union. Add all the
1629   // indirect fields to the current record.
1630   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1631   uint64_t Offset = DDTy->getOffsetInBits();
1632   const DIType *Ty = DDTy->getBaseType().resolve();
1633   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1634   ClassInfo NestedInfo = collectClassInfo(DCTy);
1635   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1636     Info.Members.push_back(
1637         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1638 }
1639 
1640 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1641   ClassInfo Info;
1642   // Add elements to structure type.
1643   DINodeArray Elements = Ty->getElements();
1644   for (auto *Element : Elements) {
1645     // We assume that the frontend provides all members in source declaration
1646     // order, which is what MSVC does.
1647     if (!Element)
1648       continue;
1649     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1650       Info.Methods[SP->getRawName()].push_back(SP);
1651     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1652       if (DDTy->getTag() == dwarf::DW_TAG_member) {
1653         collectMemberInfo(Info, DDTy);
1654       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1655         Info.Inheritance.push_back(DDTy);
1656       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1657                  DDTy->getName() == "__vtbl_ptr_type") {
1658         Info.VShapeTI = getTypeIndex(DDTy);
1659       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1660         // Ignore friend members. It appears that MSVC emitted info about
1661         // friends in the past, but modern versions do not.
1662       }
1663     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1664       Info.NestedClasses.push_back(Composite);
1665     }
1666     // Skip other unrecognized kinds of elements.
1667   }
1668   return Info;
1669 }
1670 
1671 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1672   // First, construct the forward decl.  Don't look into Ty to compute the
1673   // forward decl options, since it might not be available in all TUs.
1674   TypeRecordKind Kind = getRecordKind(Ty);
1675   ClassOptions CO =
1676       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1677   std::string FullName = getFullyQualifiedName(Ty);
1678   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1679                  FullName, Ty->getIdentifier());
1680   TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
1681   if (!Ty->isForwardDecl())
1682     DeferredCompleteTypes.push_back(Ty);
1683   return FwdDeclTI;
1684 }
1685 
1686 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1687   // Construct the field list and complete type record.
1688   TypeRecordKind Kind = getRecordKind(Ty);
1689   ClassOptions CO = getCommonClassOptions(Ty);
1690   TypeIndex FieldTI;
1691   TypeIndex VShapeTI;
1692   unsigned FieldCount;
1693   bool ContainsNestedClass;
1694   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1695       lowerRecordFieldList(Ty);
1696 
1697   if (ContainsNestedClass)
1698     CO |= ClassOptions::ContainsNestedClass;
1699 
1700   std::string FullName = getFullyQualifiedName(Ty);
1701 
1702   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1703 
1704   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1705                  SizeInBytes, FullName, Ty->getIdentifier());
1706   TypeIndex ClassTI = TypeTable.writeKnownType(CR);
1707 
1708   StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1709   TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1710   UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1711   TypeTable.writeKnownType(USLR);
1712 
1713   addToUDTs(Ty, ClassTI);
1714 
1715   return ClassTI;
1716 }
1717 
1718 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1719   ClassOptions CO =
1720       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1721   std::string FullName = getFullyQualifiedName(Ty);
1722   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1723   TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
1724   if (!Ty->isForwardDecl())
1725     DeferredCompleteTypes.push_back(Ty);
1726   return FwdDeclTI;
1727 }
1728 
1729 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1730   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1731   TypeIndex FieldTI;
1732   unsigned FieldCount;
1733   bool ContainsNestedClass;
1734   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1735       lowerRecordFieldList(Ty);
1736 
1737   if (ContainsNestedClass)
1738     CO |= ClassOptions::ContainsNestedClass;
1739 
1740   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1741   std::string FullName = getFullyQualifiedName(Ty);
1742 
1743   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1744                  Ty->getIdentifier());
1745   TypeIndex UnionTI = TypeTable.writeKnownType(UR);
1746 
1747   StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1748   TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1749   UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1750   TypeTable.writeKnownType(USLR);
1751 
1752   addToUDTs(Ty, UnionTI);
1753 
1754   return UnionTI;
1755 }
1756 
1757 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1758 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1759   // Manually count members. MSVC appears to count everything that generates a
1760   // field list record. Each individual overload in a method overload group
1761   // contributes to this count, even though the overload group is a single field
1762   // list record.
1763   unsigned MemberCount = 0;
1764   ClassInfo Info = collectClassInfo(Ty);
1765   FieldListRecordBuilder FLBR(TypeTable);
1766   FLBR.begin();
1767 
1768   // Create base classes.
1769   for (const DIDerivedType *I : Info.Inheritance) {
1770     if (I->getFlags() & DINode::FlagVirtual) {
1771       // Virtual base.
1772       // FIXME: Emit VBPtrOffset when the frontend provides it.
1773       unsigned VBPtrOffset = 0;
1774       // FIXME: Despite the accessor name, the offset is really in bytes.
1775       unsigned VBTableIndex = I->getOffsetInBits() / 4;
1776       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1777                             ? TypeRecordKind::IndirectVirtualBaseClass
1778                             : TypeRecordKind::VirtualBaseClass;
1779       VirtualBaseClassRecord VBCR(
1780           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
1781           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1782           VBTableIndex);
1783 
1784       FLBR.writeMemberType(VBCR);
1785     } else {
1786       assert(I->getOffsetInBits() % 8 == 0 &&
1787              "bases must be on byte boundaries");
1788       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1789                           getTypeIndex(I->getBaseType()),
1790                           I->getOffsetInBits() / 8);
1791       FLBR.writeMemberType(BCR);
1792     }
1793   }
1794 
1795   // Create members.
1796   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1797     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1798     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1799     StringRef MemberName = Member->getName();
1800     MemberAccess Access =
1801         translateAccessFlags(Ty->getTag(), Member->getFlags());
1802 
1803     if (Member->isStaticMember()) {
1804       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1805       FLBR.writeMemberType(SDMR);
1806       MemberCount++;
1807       continue;
1808     }
1809 
1810     // Virtual function pointer member.
1811     if ((Member->getFlags() & DINode::FlagArtificial) &&
1812         Member->getName().startswith("_vptr$")) {
1813       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1814       FLBR.writeMemberType(VFPR);
1815       MemberCount++;
1816       continue;
1817     }
1818 
1819     // Data member.
1820     uint64_t MemberOffsetInBits =
1821         Member->getOffsetInBits() + MemberInfo.BaseOffset;
1822     if (Member->isBitField()) {
1823       uint64_t StartBitOffset = MemberOffsetInBits;
1824       if (const auto *CI =
1825               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
1826         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
1827       }
1828       StartBitOffset -= MemberOffsetInBits;
1829       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1830                          StartBitOffset);
1831       MemberBaseType = TypeTable.writeKnownType(BFR);
1832     }
1833     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1834     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1835                          MemberName);
1836     FLBR.writeMemberType(DMR);
1837     MemberCount++;
1838   }
1839 
1840   // Create methods
1841   for (auto &MethodItr : Info.Methods) {
1842     StringRef Name = MethodItr.first->getString();
1843 
1844     std::vector<OneMethodRecord> Methods;
1845     for (const DISubprogram *SP : MethodItr.second) {
1846       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1847       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1848 
1849       unsigned VFTableOffset = -1;
1850       if (Introduced)
1851         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1852 
1853       Methods.push_back(OneMethodRecord(
1854           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1855           translateMethodKindFlags(SP, Introduced),
1856           translateMethodOptionFlags(SP), VFTableOffset, Name));
1857       MemberCount++;
1858     }
1859     assert(Methods.size() > 0 && "Empty methods map entry");
1860     if (Methods.size() == 1)
1861       FLBR.writeMemberType(Methods[0]);
1862     else {
1863       MethodOverloadListRecord MOLR(Methods);
1864       TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1865       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1866       FLBR.writeMemberType(OMR);
1867     }
1868   }
1869 
1870   // Create nested classes.
1871   for (const DICompositeType *Nested : Info.NestedClasses) {
1872     NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
1873     FLBR.writeMemberType(R);
1874     MemberCount++;
1875   }
1876 
1877   TypeIndex FieldTI = FLBR.end();
1878   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
1879                          !Info.NestedClasses.empty());
1880 }
1881 
1882 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1883   if (!VBPType.getIndex()) {
1884     // Make a 'const int *' type.
1885     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1886     TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
1887 
1888     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1889                                                   : PointerKind::Near32;
1890     PointerMode PM = PointerMode::Pointer;
1891     PointerOptions PO = PointerOptions::None;
1892     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1893 
1894     VBPType = TypeTable.writeKnownType(PR);
1895   }
1896 
1897   return VBPType;
1898 }
1899 
1900 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1901   const DIType *Ty = TypeRef.resolve();
1902   const DIType *ClassTy = ClassTyRef.resolve();
1903 
1904   // The null DIType is the void type. Don't try to hash it.
1905   if (!Ty)
1906     return TypeIndex::Void();
1907 
1908   // Check if we've already translated this type. Don't try to do a
1909   // get-or-create style insertion that caches the hash lookup across the
1910   // lowerType call. It will update the TypeIndices map.
1911   auto I = TypeIndices.find({Ty, ClassTy});
1912   if (I != TypeIndices.end())
1913     return I->second;
1914 
1915   TypeLoweringScope S(*this);
1916   TypeIndex TI = lowerType(Ty, ClassTy);
1917   return recordTypeIndexForDINode(Ty, TI, ClassTy);
1918 }
1919 
1920 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1921   const DIType *Ty = TypeRef.resolve();
1922 
1923   // The null DIType is the void type. Don't try to hash it.
1924   if (!Ty)
1925     return TypeIndex::Void();
1926 
1927   // If this is a non-record type, the complete type index is the same as the
1928   // normal type index. Just call getTypeIndex.
1929   switch (Ty->getTag()) {
1930   case dwarf::DW_TAG_class_type:
1931   case dwarf::DW_TAG_structure_type:
1932   case dwarf::DW_TAG_union_type:
1933     break;
1934   default:
1935     return getTypeIndex(Ty);
1936   }
1937 
1938   // Check if we've already translated the complete record type.  Lowering a
1939   // complete type should never trigger lowering another complete type, so we
1940   // can reuse the hash table lookup result.
1941   const auto *CTy = cast<DICompositeType>(Ty);
1942   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1943   if (!InsertResult.second)
1944     return InsertResult.first->second;
1945 
1946   TypeLoweringScope S(*this);
1947 
1948   // Make sure the forward declaration is emitted first. It's unclear if this
1949   // is necessary, but MSVC does it, and we should follow suit until we can show
1950   // otherwise.
1951   TypeIndex FwdDeclTI = getTypeIndex(CTy);
1952 
1953   // Just use the forward decl if we don't have complete type info. This might
1954   // happen if the frontend is using modules and expects the complete definition
1955   // to be emitted elsewhere.
1956   if (CTy->isForwardDecl())
1957     return FwdDeclTI;
1958 
1959   TypeIndex TI;
1960   switch (CTy->getTag()) {
1961   case dwarf::DW_TAG_class_type:
1962   case dwarf::DW_TAG_structure_type:
1963     TI = lowerCompleteTypeClass(CTy);
1964     break;
1965   case dwarf::DW_TAG_union_type:
1966     TI = lowerCompleteTypeUnion(CTy);
1967     break;
1968   default:
1969     llvm_unreachable("not a record");
1970   }
1971 
1972   InsertResult.first->second = TI;
1973   return TI;
1974 }
1975 
1976 /// Emit all the deferred complete record types. Try to do this in FIFO order,
1977 /// and do this until fixpoint, as each complete record type typically
1978 /// references
1979 /// many other record types.
1980 void CodeViewDebug::emitDeferredCompleteTypes() {
1981   SmallVector<const DICompositeType *, 4> TypesToEmit;
1982   while (!DeferredCompleteTypes.empty()) {
1983     std::swap(DeferredCompleteTypes, TypesToEmit);
1984     for (const DICompositeType *RecordTy : TypesToEmit)
1985       getCompleteTypeIndex(RecordTy);
1986     TypesToEmit.clear();
1987   }
1988 }
1989 
1990 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1991   // Get the sorted list of parameters and emit them first.
1992   SmallVector<const LocalVariable *, 6> Params;
1993   for (const LocalVariable &L : Locals)
1994     if (L.DIVar->isParameter())
1995       Params.push_back(&L);
1996   std::sort(Params.begin(), Params.end(),
1997             [](const LocalVariable *L, const LocalVariable *R) {
1998               return L->DIVar->getArg() < R->DIVar->getArg();
1999             });
2000   for (const LocalVariable *L : Params)
2001     emitLocalVariable(*L);
2002 
2003   // Next emit all non-parameters in the order that we found them.
2004   for (const LocalVariable &L : Locals)
2005     if (!L.DIVar->isParameter())
2006       emitLocalVariable(L);
2007 }
2008 
2009 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2010   // LocalSym record, see SymbolRecord.h for more info.
2011   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2012            *LocalEnd = MMI->getContext().createTempSymbol();
2013   OS.AddComment("Record length");
2014   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2015   OS.EmitLabel(LocalBegin);
2016 
2017   OS.AddComment("Record kind: S_LOCAL");
2018   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
2019 
2020   LocalSymFlags Flags = LocalSymFlags::None;
2021   if (Var.DIVar->isParameter())
2022     Flags |= LocalSymFlags::IsParameter;
2023   if (Var.DefRanges.empty())
2024     Flags |= LocalSymFlags::IsOptimizedOut;
2025 
2026   OS.AddComment("TypeIndex");
2027   TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2028   OS.EmitIntValue(TI.getIndex(), 4);
2029   OS.AddComment("Flags");
2030   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2031   // Truncate the name so we won't overflow the record length field.
2032   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2033   OS.EmitLabel(LocalEnd);
2034 
2035   // Calculate the on disk prefix of the appropriate def range record. The
2036   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2037   // should be big enough to hold all forms without memory allocation.
2038   SmallString<20> BytePrefix;
2039   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2040     BytePrefix.clear();
2041     if (DefRange.InMemory) {
2042       uint16_t RegRelFlags = 0;
2043       if (DefRange.IsSubfield) {
2044         RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2045                       (DefRange.StructOffset
2046                        << DefRangeRegisterRelSym::OffsetInParentShift);
2047       }
2048       DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2049       Sym.Hdr.Register = DefRange.CVRegister;
2050       Sym.Hdr.Flags = RegRelFlags;
2051       Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
2052       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2053       BytePrefix +=
2054           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
2055       BytePrefix +=
2056           StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
2057     } else {
2058       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2059       if (DefRange.IsSubfield) {
2060         // Unclear what matters here.
2061         DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2062         Sym.Hdr.Register = DefRange.CVRegister;
2063         Sym.Hdr.MayHaveNoName = 0;
2064         Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2065 
2066         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2067         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2068                                 sizeof(SymKind));
2069         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2070                                 sizeof(Sym.Hdr));
2071       } else {
2072         // Unclear what matters here.
2073         DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2074         Sym.Hdr.Register = DefRange.CVRegister;
2075         Sym.Hdr.MayHaveNoName = 0;
2076         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2077         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2078                                 sizeof(SymKind));
2079         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2080                                 sizeof(Sym.Hdr));
2081       }
2082     }
2083     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2084   }
2085 }
2086 
2087 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2088   const Function *GV = MF->getFunction();
2089   assert(FnDebugInfo.count(GV));
2090   assert(CurFn == &FnDebugInfo[GV]);
2091 
2092   collectVariableInfo(GV->getSubprogram());
2093 
2094   // Don't emit anything if we don't have any line tables.
2095   if (!CurFn->HaveLineInfo) {
2096     FnDebugInfo.erase(GV);
2097     CurFn = nullptr;
2098     return;
2099   }
2100 
2101   CurFn->End = Asm->getFunctionEnd();
2102 
2103   CurFn = nullptr;
2104 }
2105 
2106 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2107   DebugHandlerBase::beginInstruction(MI);
2108 
2109   // Ignore DBG_VALUE locations and function prologue.
2110   if (!Asm || !CurFn || MI->isDebugValue() ||
2111       MI->getFlag(MachineInstr::FrameSetup))
2112     return;
2113   DebugLoc DL = MI->getDebugLoc();
2114   if (DL == PrevInstLoc || !DL)
2115     return;
2116   maybeRecordLocation(DL, Asm->MF);
2117 }
2118 
2119 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleDebugFragmentKind Kind) {
2120   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2121            *EndLabel = MMI->getContext().createTempSymbol();
2122   OS.EmitIntValue(unsigned(Kind), 4);
2123   OS.AddComment("Subsection size");
2124   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2125   OS.EmitLabel(BeginLabel);
2126   return EndLabel;
2127 }
2128 
2129 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2130   OS.EmitLabel(EndLabel);
2131   // Every subsection must be aligned to a 4-byte boundary.
2132   OS.EmitValueToAlignment(4);
2133 }
2134 
2135 void CodeViewDebug::emitDebugInfoForUDTs(
2136     ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2137   for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2138     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2139              *UDTRecordEnd = MMI->getContext().createTempSymbol();
2140     OS.AddComment("Record length");
2141     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2142     OS.EmitLabel(UDTRecordBegin);
2143 
2144     OS.AddComment("Record kind: S_UDT");
2145     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2146 
2147     OS.AddComment("Type");
2148     OS.EmitIntValue(UDT.second.getIndex(), 4);
2149 
2150     emitNullTerminatedSymbolName(OS, UDT.first);
2151     OS.EmitLabel(UDTRecordEnd);
2152   }
2153 }
2154 
2155 void CodeViewDebug::emitDebugInfoForGlobals() {
2156   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2157       GlobalMap;
2158   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2159     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2160     GV.getDebugInfo(GVEs);
2161     for (const auto *GVE : GVEs)
2162       GlobalMap[GVE] = &GV;
2163   }
2164 
2165   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2166   for (const MDNode *Node : CUs->operands()) {
2167     const auto *CU = cast<DICompileUnit>(Node);
2168 
2169     // First, emit all globals that are not in a comdat in a single symbol
2170     // substream. MSVC doesn't like it if the substream is empty, so only open
2171     // it if we have at least one global to emit.
2172     switchToDebugSectionForSymbol(nullptr);
2173     MCSymbol *EndLabel = nullptr;
2174     for (const auto *GVE : CU->getGlobalVariables()) {
2175       if (const auto *GV = GlobalMap.lookup(GVE))
2176         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
2177           if (!EndLabel) {
2178             OS.AddComment("Symbol subsection for globals");
2179             EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
2180           }
2181           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2182           emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
2183         }
2184     }
2185     if (EndLabel)
2186       endCVSubsection(EndLabel);
2187 
2188     // Second, emit each global that is in a comdat into its own .debug$S
2189     // section along with its own symbol substream.
2190     for (const auto *GVE : CU->getGlobalVariables()) {
2191       if (const auto *GV = GlobalMap.lookup(GVE)) {
2192         if (GV->hasComdat()) {
2193           MCSymbol *GVSym = Asm->getSymbol(GV);
2194           OS.AddComment("Symbol subsection for " +
2195                         Twine(GlobalValue::getRealLinkageName(GV->getName())));
2196           switchToDebugSectionForSymbol(GVSym);
2197           EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
2198           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2199           emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
2200           endCVSubsection(EndLabel);
2201         }
2202       }
2203     }
2204   }
2205 }
2206 
2207 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2208   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2209   for (const MDNode *Node : CUs->operands()) {
2210     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2211       if (DIType *RT = dyn_cast<DIType>(Ty)) {
2212         getTypeIndex(RT);
2213         // FIXME: Add to global/local DTU list.
2214       }
2215     }
2216   }
2217 }
2218 
2219 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2220                                            const GlobalVariable *GV,
2221                                            MCSymbol *GVSym) {
2222   // DataSym record, see SymbolRecord.h for more info.
2223   // FIXME: Thread local data, etc
2224   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2225            *DataEnd = MMI->getContext().createTempSymbol();
2226   OS.AddComment("Record length");
2227   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2228   OS.EmitLabel(DataBegin);
2229   if (DIGV->isLocalToUnit()) {
2230     if (GV->isThreadLocal()) {
2231       OS.AddComment("Record kind: S_LTHREAD32");
2232       OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2233     } else {
2234       OS.AddComment("Record kind: S_LDATA32");
2235       OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2236     }
2237   } else {
2238     if (GV->isThreadLocal()) {
2239       OS.AddComment("Record kind: S_GTHREAD32");
2240       OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2241     } else {
2242       OS.AddComment("Record kind: S_GDATA32");
2243       OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2244     }
2245   }
2246   OS.AddComment("Type");
2247   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2248   OS.AddComment("DataOffset");
2249   OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
2250   OS.AddComment("Segment");
2251   OS.EmitCOFFSectionIndex(GVSym);
2252   OS.AddComment("Name");
2253   emitNullTerminatedSymbolName(OS, DIGV->getName());
2254   OS.EmitLabel(DataEnd);
2255 }
2256