1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeViewDebug.h"
15 #include "llvm/DebugInfo/CodeView/CodeView.h"
16 #include "llvm/DebugInfo/CodeView/Line.h"
17 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
18 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
19 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/COFF.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetFrameLowering.h"
26 
27 using namespace llvm;
28 using namespace llvm::codeview;
29 
30 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
31     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
32   // If module doesn't have named metadata anchors or COFF debug section
33   // is not available, skip any debug info related stuff.
34   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
35       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
36     Asm = nullptr;
37     return;
38   }
39 
40   // Tell MMI that we have debug info.
41   MMI->setDebugInfoAvailability(true);
42 }
43 
44 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
45   std::string &Filepath = FileToFilepathMap[File];
46   if (!Filepath.empty())
47     return Filepath;
48 
49   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
50 
51   // Clang emits directory and relative filename info into the IR, but CodeView
52   // operates on full paths.  We could change Clang to emit full paths too, but
53   // that would increase the IR size and probably not needed for other users.
54   // For now, just concatenate and canonicalize the path here.
55   if (Filename.find(':') == 1)
56     Filepath = Filename;
57   else
58     Filepath = (Dir + "\\" + Filename).str();
59 
60   // Canonicalize the path.  We have to do it textually because we may no longer
61   // have access the file in the filesystem.
62   // First, replace all slashes with backslashes.
63   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
64 
65   // Remove all "\.\" with "\".
66   size_t Cursor = 0;
67   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
68     Filepath.erase(Cursor, 2);
69 
70   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
71   // path should be well-formatted, e.g. start with a drive letter, etc.
72   Cursor = 0;
73   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
74     // Something's wrong if the path starts with "\..\", abort.
75     if (Cursor == 0)
76       break;
77 
78     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
79     if (PrevSlash == std::string::npos)
80       // Something's wrong, abort.
81       break;
82 
83     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
84     // The next ".." might be following the one we've just erased.
85     Cursor = PrevSlash;
86   }
87 
88   // Remove all duplicate backslashes.
89   Cursor = 0;
90   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
91     Filepath.erase(Cursor, 1);
92 
93   return Filepath;
94 }
95 
96 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
97   unsigned NextId = FileIdMap.size() + 1;
98   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
99   if (Insertion.second) {
100     // We have to compute the full filepath and emit a .cv_file directive.
101     StringRef FullPath = getFullFilepath(F);
102     NextId = OS.EmitCVFileDirective(NextId, FullPath);
103     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
104   }
105   return Insertion.first->second;
106 }
107 
108 CodeViewDebug::InlineSite &
109 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
110                              const DISubprogram *Inlinee) {
111   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
112   InlineSite *Site = &SiteInsertion.first->second;
113   if (SiteInsertion.second) {
114     Site->SiteFuncId = NextFuncId++;
115     Site->Inlinee = Inlinee;
116     InlinedSubprograms.insert(Inlinee);
117     recordFuncIdForSubprogram(Inlinee);
118   }
119   return *Site;
120 }
121 
122 TypeIndex CodeViewDebug::getGenericFunctionTypeIndex() {
123   if (VoidFnTyIdx.getIndex() != 0)
124     return VoidFnTyIdx;
125 
126   ArrayRef<TypeIndex> NoArgs;
127   ArgListRecord ArgListRec(TypeRecordKind::ArgList, NoArgs);
128   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
129 
130   ProcedureRecord Procedure(TypeIndex::Void(), CallingConvention::NearC,
131                             FunctionOptions::None, 0, ArgListIndex);
132   VoidFnTyIdx = TypeTable.writeProcedure(Procedure);
133   return VoidFnTyIdx;
134 }
135 
136 void CodeViewDebug::recordFuncIdForSubprogram(const DISubprogram *SP) {
137   TypeIndex ParentScope = TypeIndex(0);
138   StringRef DisplayName = SP->getDisplayName();
139   FuncIdRecord FuncId(ParentScope, getGenericFunctionTypeIndex(), DisplayName);
140   TypeIndex TI = TypeTable.writeFuncId(FuncId);
141   TypeIndices[SP] = TI;
142 }
143 
144 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
145                                         const DILocation *InlinedAt) {
146   if (InlinedAt) {
147     // This variable was inlined. Associate it with the InlineSite.
148     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
149     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
150     Site.InlinedLocals.emplace_back(Var);
151   } else {
152     // This variable goes in the main ProcSym.
153     CurFn->Locals.emplace_back(Var);
154   }
155 }
156 
157 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
158                                const DILocation *Loc) {
159   auto B = Locs.begin(), E = Locs.end();
160   if (std::find(B, E, Loc) == E)
161     Locs.push_back(Loc);
162 }
163 
164 void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
165                                         const MachineFunction *MF) {
166   // Skip this instruction if it has the same location as the previous one.
167   if (DL == CurFn->LastLoc)
168     return;
169 
170   const DIScope *Scope = DL.get()->getScope();
171   if (!Scope)
172     return;
173 
174   // Skip this line if it is longer than the maximum we can record.
175   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
176   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
177       LI.isNeverStepInto())
178     return;
179 
180   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
181   if (CI.getStartColumn() != DL.getCol())
182     return;
183 
184   if (!CurFn->HaveLineInfo)
185     CurFn->HaveLineInfo = true;
186   unsigned FileId = 0;
187   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
188     FileId = CurFn->LastFileId;
189   else
190     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
191   CurFn->LastLoc = DL;
192 
193   unsigned FuncId = CurFn->FuncId;
194   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
195     const DILocation *Loc = DL.get();
196 
197     // If this location was actually inlined from somewhere else, give it the ID
198     // of the inline call site.
199     FuncId =
200         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
201 
202     // Ensure we have links in the tree of inline call sites.
203     bool FirstLoc = true;
204     while ((SiteLoc = Loc->getInlinedAt())) {
205       InlineSite &Site =
206           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
207       if (!FirstLoc)
208         addLocIfNotPresent(Site.ChildSites, Loc);
209       FirstLoc = false;
210       Loc = SiteLoc;
211     }
212     addLocIfNotPresent(CurFn->ChildSites, Loc);
213   }
214 
215   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
216                         /*PrologueEnd=*/false,
217                         /*IsStmt=*/false, DL->getFilename());
218 }
219 
220 void CodeViewDebug::endModule() {
221   if (FnDebugInfo.empty())
222     return;
223 
224   emitTypeInformation();
225 
226   // FIXME: For functions that are comdat, we should emit separate .debug$S
227   // sections that are comdat associative with the main function instead of
228   // having one big .debug$S section.
229   assert(Asm != nullptr);
230   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
231   OS.AddComment("Debug section magic");
232   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
233 
234   // The COFF .debug$S section consists of several subsections, each starting
235   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
236   // of the payload followed by the payload itself.  The subsections are 4-byte
237   // aligned.
238 
239   // Make a subsection for all the inlined subprograms.
240   emitInlineeFuncIdsAndLines();
241 
242   // Emit per-function debug information.
243   for (auto &P : FnDebugInfo)
244     emitDebugInfoForFunction(P.first, P.second);
245 
246   // This subsection holds a file index to offset in string table table.
247   OS.AddComment("File index to string table offset subsection");
248   OS.EmitCVFileChecksumsDirective();
249 
250   // This subsection holds the string table.
251   OS.AddComment("String table");
252   OS.EmitCVStringTableDirective();
253 
254   clear();
255 }
256 
257 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
258   // Microsoft's linker seems to have trouble with symbol names longer than
259   // 0xffd8 bytes.
260   S = S.substr(0, 0xffd8);
261   SmallString<32> NullTerminatedString(S);
262   NullTerminatedString.push_back('\0');
263   OS.EmitBytes(NullTerminatedString);
264 }
265 
266 void CodeViewDebug::emitTypeInformation() {
267   // Do nothing if we have no debug info or if no non-trivial types were emitted
268   // to TypeTable during codegen.
269   NamedMDNode *CU_Nodes =
270       MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
271   if (!CU_Nodes)
272     return;
273   if (TypeTable.empty())
274     return;
275 
276   // Start the .debug$T section with 0x4.
277   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
278   OS.AddComment("Debug section magic");
279   OS.EmitValueToAlignment(4);
280   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
281 
282   TypeTable.ForEachRecord(
283       [&](TypeIndex Index, const MemoryTypeTableBuilder::Record *R) {
284         // Each record should be 4 byte aligned. We achieve that by emitting
285         // LF_PAD padding bytes. The on-disk record size includes the padding
286         // bytes so that consumers don't have to skip past them.
287         uint64_t RecordSize = R->size() + 2;
288         uint64_t AlignedSize = alignTo(RecordSize, 4);
289         uint64_t AlignedRecordSize = AlignedSize - 2;
290         assert(AlignedRecordSize < (1 << 16) && "type record size overflow");
291         OS.AddComment("Type record length");
292         OS.EmitIntValue(AlignedRecordSize, 2);
293         OS.AddComment("Type record data");
294         OS.EmitBytes(StringRef(R->data(), R->size()));
295         // Pad the record with LF_PAD bytes.
296         for (unsigned I = AlignedSize - RecordSize; I > 0; --I)
297           OS.EmitIntValue(LF_PAD0 + I, 1);
298       });
299 }
300 
301 void CodeViewDebug::emitInlineeFuncIdsAndLines() {
302   if (InlinedSubprograms.empty())
303     return;
304 
305   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
306            *InlineEnd = MMI->getContext().createTempSymbol();
307 
308   OS.AddComment("Inlinee lines subsection");
309   OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
310   OS.AddComment("Subsection size");
311   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
312   OS.EmitLabel(InlineBegin);
313 
314   // We don't provide any extra file info.
315   // FIXME: Find out if debuggers use this info.
316   OS.AddComment("Inlinee lines signature");
317   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
318 
319   for (const DISubprogram *SP : InlinedSubprograms) {
320     assert(TypeIndices.count(SP));
321     TypeIndex InlineeIdx = TypeIndices[SP];
322 
323     OS.AddBlankLine();
324     unsigned FileId = maybeRecordFile(SP->getFile());
325     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
326                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
327     OS.AddBlankLine();
328     // The filechecksum table uses 8 byte entries for now, and file ids start at
329     // 1.
330     unsigned FileOffset = (FileId - 1) * 8;
331     OS.AddComment("Type index of inlined function");
332     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
333     OS.AddComment("Offset into filechecksum table");
334     OS.EmitIntValue(FileOffset, 4);
335     OS.AddComment("Starting line number");
336     OS.EmitIntValue(SP->getLine(), 4);
337   }
338 
339   OS.EmitLabel(InlineEnd);
340 }
341 
342 void CodeViewDebug::collectInlineSiteChildren(
343     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
344     const InlineSite &Site) {
345   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
346     auto I = FI.InlineSites.find(ChildSiteLoc);
347     const InlineSite &ChildSite = I->second;
348     Children.push_back(ChildSite.SiteFuncId);
349     collectInlineSiteChildren(Children, FI, ChildSite);
350   }
351 }
352 
353 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
354                                         const DILocation *InlinedAt,
355                                         const InlineSite &Site) {
356   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
357            *InlineEnd = MMI->getContext().createTempSymbol();
358 
359   assert(TypeIndices.count(Site.Inlinee));
360   TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
361 
362   // SymbolRecord
363   OS.AddComment("Record length");
364   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
365   OS.EmitLabel(InlineBegin);
366   OS.AddComment("Record kind: S_INLINESITE");
367   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
368 
369   OS.AddComment("PtrParent");
370   OS.EmitIntValue(0, 4);
371   OS.AddComment("PtrEnd");
372   OS.EmitIntValue(0, 4);
373   OS.AddComment("Inlinee type index");
374   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
375 
376   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
377   unsigned StartLineNum = Site.Inlinee->getLine();
378   SmallVector<unsigned, 3> SecondaryFuncIds;
379   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
380 
381   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
382                                     FI.Begin, FI.End, SecondaryFuncIds);
383 
384   OS.EmitLabel(InlineEnd);
385 
386   for (const LocalVariable &Var : Site.InlinedLocals)
387     emitLocalVariable(Var);
388 
389   // Recurse on child inlined call sites before closing the scope.
390   for (const DILocation *ChildSite : Site.ChildSites) {
391     auto I = FI.InlineSites.find(ChildSite);
392     assert(I != FI.InlineSites.end() &&
393            "child site not in function inline site map");
394     emitInlinedCallSite(FI, ChildSite, I->second);
395   }
396 
397   // Close the scope.
398   OS.AddComment("Record length");
399   OS.EmitIntValue(2, 2);                                  // RecordLength
400   OS.AddComment("Record kind: S_INLINESITE_END");
401   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
402 }
403 
404 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
405                                              FunctionInfo &FI) {
406   // For each function there is a separate subsection
407   // which holds the PC to file:line table.
408   const MCSymbol *Fn = Asm->getSymbol(GV);
409   assert(Fn);
410 
411   StringRef FuncName;
412   if (auto *SP = GV->getSubprogram())
413     FuncName = SP->getDisplayName();
414 
415   // If our DISubprogram name is empty, use the mangled name.
416   if (FuncName.empty())
417     FuncName = GlobalValue::getRealLinkageName(GV->getName());
418 
419   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
420   MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
421            *SymbolsEnd = MMI->getContext().createTempSymbol();
422   OS.AddComment("Symbol subsection for " + Twine(FuncName));
423   OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
424   OS.AddComment("Subsection size");
425   OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
426   OS.EmitLabel(SymbolsBegin);
427   {
428     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
429              *ProcRecordEnd = MMI->getContext().createTempSymbol();
430     OS.AddComment("Record length");
431     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
432     OS.EmitLabel(ProcRecordBegin);
433 
434     OS.AddComment("Record kind: S_GPROC32_ID");
435     OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
436 
437     // These fields are filled in by tools like CVPACK which run after the fact.
438     OS.AddComment("PtrParent");
439     OS.EmitIntValue(0, 4);
440     OS.AddComment("PtrEnd");
441     OS.EmitIntValue(0, 4);
442     OS.AddComment("PtrNext");
443     OS.EmitIntValue(0, 4);
444     // This is the important bit that tells the debugger where the function
445     // code is located and what's its size:
446     OS.AddComment("Code size");
447     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
448     OS.AddComment("Offset after prologue");
449     OS.EmitIntValue(0, 4);
450     OS.AddComment("Offset before epilogue");
451     OS.EmitIntValue(0, 4);
452     OS.AddComment("Function type index");
453     OS.EmitIntValue(0, 4);
454     OS.AddComment("Function section relative address");
455     OS.EmitCOFFSecRel32(Fn);
456     OS.AddComment("Function section index");
457     OS.EmitCOFFSectionIndex(Fn);
458     OS.AddComment("Flags");
459     OS.EmitIntValue(0, 1);
460     // Emit the function display name as a null-terminated string.
461     OS.AddComment("Function name");
462     // Truncate the name so we won't overflow the record length field.
463     emitNullTerminatedSymbolName(OS, FuncName);
464     OS.EmitLabel(ProcRecordEnd);
465 
466     for (const LocalVariable &Var : FI.Locals)
467       emitLocalVariable(Var);
468 
469     // Emit inlined call site information. Only emit functions inlined directly
470     // into the parent function. We'll emit the other sites recursively as part
471     // of their parent inline site.
472     for (const DILocation *InlinedAt : FI.ChildSites) {
473       auto I = FI.InlineSites.find(InlinedAt);
474       assert(I != FI.InlineSites.end() &&
475              "child site not in function inline site map");
476       emitInlinedCallSite(FI, InlinedAt, I->second);
477     }
478 
479     // We're done with this function.
480     OS.AddComment("Record length");
481     OS.EmitIntValue(0x0002, 2);
482     OS.AddComment("Record kind: S_PROC_ID_END");
483     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
484   }
485   OS.EmitLabel(SymbolsEnd);
486   // Every subsection must be aligned to a 4-byte boundary.
487   OS.EmitValueToAlignment(4);
488 
489   // We have an assembler directive that takes care of the whole line table.
490   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
491 }
492 
493 CodeViewDebug::LocalVarDefRange
494 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
495   LocalVarDefRange DR;
496   DR.InMemory = -1;
497   DR.DataOffset = Offset;
498   assert(DR.DataOffset == Offset && "truncation");
499   DR.StructOffset = 0;
500   DR.CVRegister = CVRegister;
501   return DR;
502 }
503 
504 CodeViewDebug::LocalVarDefRange
505 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
506   LocalVarDefRange DR;
507   DR.InMemory = 0;
508   DR.DataOffset = 0;
509   DR.StructOffset = 0;
510   DR.CVRegister = CVRegister;
511   return DR;
512 }
513 
514 void CodeViewDebug::collectVariableInfoFromMMITable(
515     DenseSet<InlinedVariable> &Processed) {
516   const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
517   const TargetFrameLowering *TFI = TSI.getFrameLowering();
518   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
519 
520   for (const MachineModuleInfo::VariableDbgInfo &VI :
521        MMI->getVariableDbgInfo()) {
522     if (!VI.Var)
523       continue;
524     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
525            "Expected inlined-at fields to agree");
526 
527     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
528     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
529 
530     // If variable scope is not found then skip this variable.
531     if (!Scope)
532       continue;
533 
534     // Get the frame register used and the offset.
535     unsigned FrameReg = 0;
536     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
537     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
538 
539     // Calculate the label ranges.
540     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
541     for (const InsnRange &Range : Scope->getRanges()) {
542       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
543       const MCSymbol *End = getLabelAfterInsn(Range.second);
544       End = End ? End : Asm->getFunctionEnd();
545       DefRange.Ranges.emplace_back(Begin, End);
546     }
547 
548     LocalVariable Var;
549     Var.DIVar = VI.Var;
550     Var.DefRanges.emplace_back(std::move(DefRange));
551     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
552   }
553 }
554 
555 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
556   DenseSet<InlinedVariable> Processed;
557   // Grab the variable info that was squirreled away in the MMI side-table.
558   collectVariableInfoFromMMITable(Processed);
559 
560   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
561 
562   for (const auto &I : DbgValues) {
563     InlinedVariable IV = I.first;
564     if (Processed.count(IV))
565       continue;
566     const DILocalVariable *DIVar = IV.first;
567     const DILocation *InlinedAt = IV.second;
568 
569     // Instruction ranges, specifying where IV is accessible.
570     const auto &Ranges = I.second;
571 
572     LexicalScope *Scope = nullptr;
573     if (InlinedAt)
574       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
575     else
576       Scope = LScopes.findLexicalScope(DIVar->getScope());
577     // If variable scope is not found then skip this variable.
578     if (!Scope)
579       continue;
580 
581     LocalVariable Var;
582     Var.DIVar = DIVar;
583 
584     // Calculate the definition ranges.
585     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
586       const InsnRange &Range = *I;
587       const MachineInstr *DVInst = Range.first;
588       assert(DVInst->isDebugValue() && "Invalid History entry");
589       const DIExpression *DIExpr = DVInst->getDebugExpression();
590 
591       // Bail if there is a complex DWARF expression for now.
592       if (DIExpr && DIExpr->getNumElements() > 0)
593         continue;
594 
595       // Bail if operand 0 is not a valid register. This means the variable is a
596       // simple constant, or is described by a complex expression.
597       // FIXME: Find a way to represent constant variables, since they are
598       // relatively common.
599       unsigned Reg =
600           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
601       if (Reg == 0)
602         continue;
603 
604       // Handle the two cases we can handle: indirect in memory and in register.
605       bool IsIndirect = DVInst->getOperand(1).isImm();
606       unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
607       {
608         LocalVarDefRange DefRange;
609         if (IsIndirect) {
610           int64_t Offset = DVInst->getOperand(1).getImm();
611           DefRange = createDefRangeMem(CVReg, Offset);
612         } else {
613           DefRange = createDefRangeReg(CVReg);
614         }
615         if (Var.DefRanges.empty() ||
616             Var.DefRanges.back().isDifferentLocation(DefRange)) {
617           Var.DefRanges.emplace_back(std::move(DefRange));
618         }
619       }
620 
621       // Compute the label range.
622       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
623       const MCSymbol *End = getLabelAfterInsn(Range.second);
624       if (!End) {
625         if (std::next(I) != E)
626           End = getLabelBeforeInsn(std::next(I)->first);
627         else
628           End = Asm->getFunctionEnd();
629       }
630 
631       // If the last range end is our begin, just extend the last range.
632       // Otherwise make a new range.
633       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
634           Var.DefRanges.back().Ranges;
635       if (!Ranges.empty() && Ranges.back().second == Begin)
636         Ranges.back().second = End;
637       else
638         Ranges.emplace_back(Begin, End);
639 
640       // FIXME: Do more range combining.
641     }
642 
643     recordLocalVariable(std::move(Var), InlinedAt);
644   }
645 }
646 
647 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
648   assert(!CurFn && "Can't process two functions at once!");
649 
650   if (!Asm || !MMI->hasDebugInfo())
651     return;
652 
653   DebugHandlerBase::beginFunction(MF);
654 
655   const Function *GV = MF->getFunction();
656   assert(FnDebugInfo.count(GV) == false);
657   CurFn = &FnDebugInfo[GV];
658   CurFn->FuncId = NextFuncId++;
659   CurFn->Begin = Asm->getFunctionBegin();
660 
661   // Find the end of the function prolog.  First known non-DBG_VALUE and
662   // non-frame setup location marks the beginning of the function body.
663   // FIXME: is there a simpler a way to do this? Can we just search
664   // for the first instruction of the function, not the last of the prolog?
665   DebugLoc PrologEndLoc;
666   bool EmptyPrologue = true;
667   for (const auto &MBB : *MF) {
668     for (const auto &MI : MBB) {
669       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
670           MI.getDebugLoc()) {
671         PrologEndLoc = MI.getDebugLoc();
672         break;
673       } else if (!MI.isDebugValue()) {
674         EmptyPrologue = false;
675       }
676     }
677   }
678 
679   // Record beginning of function if we have a non-empty prologue.
680   if (PrologEndLoc && !EmptyPrologue) {
681     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
682     maybeRecordLocation(FnStartDL, MF);
683   }
684 }
685 
686 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
687   // LocalSym record, see SymbolRecord.h for more info.
688   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
689            *LocalEnd = MMI->getContext().createTempSymbol();
690   OS.AddComment("Record length");
691   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
692   OS.EmitLabel(LocalBegin);
693 
694   OS.AddComment("Record kind: S_LOCAL");
695   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
696 
697   LocalSymFlags Flags = LocalSymFlags::None;
698   if (Var.DIVar->isParameter())
699     Flags |= LocalSymFlags::IsParameter;
700   if (Var.DefRanges.empty())
701     Flags |= LocalSymFlags::IsOptimizedOut;
702 
703   OS.AddComment("TypeIndex");
704   OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4);
705   OS.AddComment("Flags");
706   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
707   // Truncate the name so we won't overflow the record length field.
708   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
709   OS.EmitLabel(LocalEnd);
710 
711   // Calculate the on disk prefix of the appropriate def range record. The
712   // records and on disk formats are described in SymbolRecords.h. BytePrefix
713   // should be big enough to hold all forms without memory allocation.
714   SmallString<20> BytePrefix;
715   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
716     BytePrefix.clear();
717     // FIXME: Handle bitpieces.
718     if (DefRange.StructOffset != 0)
719       continue;
720 
721     if (DefRange.InMemory) {
722       DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
723                                  0, 0, ArrayRef<LocalVariableAddrGap>());
724       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
725       BytePrefix +=
726           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
727       BytePrefix +=
728           StringRef(reinterpret_cast<const char *>(&Sym.Header),
729                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
730     } else {
731       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
732       // Unclear what matters here.
733       DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
734                               ArrayRef<LocalVariableAddrGap>());
735       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
736       BytePrefix +=
737           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
738       BytePrefix +=
739           StringRef(reinterpret_cast<const char *>(&Sym.Header),
740                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
741     }
742     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
743   }
744 }
745 
746 void CodeViewDebug::endFunction(const MachineFunction *MF) {
747   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
748     return;
749 
750   const Function *GV = MF->getFunction();
751   assert(FnDebugInfo.count(GV));
752   assert(CurFn == &FnDebugInfo[GV]);
753 
754   collectVariableInfo(GV->getSubprogram());
755 
756   DebugHandlerBase::endFunction(MF);
757 
758   // Don't emit anything if we don't have any line tables.
759   if (!CurFn->HaveLineInfo) {
760     FnDebugInfo.erase(GV);
761     CurFn = nullptr;
762     return;
763   }
764 
765   CurFn->End = Asm->getFunctionEnd();
766 
767   CurFn = nullptr;
768 }
769 
770 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
771   DebugHandlerBase::beginInstruction(MI);
772 
773   // Ignore DBG_VALUE locations and function prologue.
774   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
775     return;
776   DebugLoc DL = MI->getDebugLoc();
777   if (DL == PrevInstLoc || !DL)
778     return;
779   maybeRecordLocation(DL, Asm->MF);
780 }
781