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