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