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