1 //===-- llvm/lib/CodeGen/AsmPrinter/WinCodeViewLineTables.cpp --*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing line tables info into COFF files.
12 //===----------------------------------------------------------------------===//
14 #include "WinCodeViewLineTables.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCSymbol.h"
17 #include "llvm/Support/COFF.h"
21 StringRef WinCodeViewLineTables::getFullFilepath(const MDNode *S) {
24 assert((D.isCompileUnit() || D.isFile() || D.isSubprogram() ||
25 D.isLexicalBlockFile() || D.isLexicalBlock()) &&
26 "Unexpected scope info");
29 StringRef Dir = Scope.getDirectory(),
30 Filename = Scope.getFilename();
31 char *&Result = DirAndFilenameToFilepathMap[std::make_pair(Dir, Filename)];
35 // Clang emits directory and relative filename info into the IR, but CodeView
36 // operates on full paths. We could change Clang to emit full paths too, but
37 // that would increase the IR size and probably not needed for other users.
38 // For now, just concatenate and canonicalize the path here.
40 if (Filename.find(':') == 1)
43 Filepath = (Dir + Twine("\\") + Filename).str();
45 // Canonicalize the path. We have to do it textually because we may no longer
46 // have access the file in the filesystem.
47 // First, replace all slashes with backslashes.
48 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
50 // Remove all "\.\" with "\".
52 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
53 Filepath.erase(Cursor, 2);
55 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
56 // path should be well-formatted, e.g. start with a drive letter, etc.
58 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
59 // Something's wrong if the path starts with "\..\", abort.
63 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
64 if (PrevSlash == std::string::npos)
65 // Something's wrong, abort.
68 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
69 // The next ".." might be following the one we've just erased.
73 // Remove all duplicate backslashes.
75 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
76 Filepath.erase(Cursor, 1);
78 Result = strdup(Filepath.c_str());
79 return StringRef(Result);
82 void WinCodeViewLineTables::maybeRecordLocation(DebugLoc DL,
83 const MachineFunction *MF) {
84 const MDNode *Scope = DL.getScope(MF->getFunction()->getContext());
87 StringRef Filename = getFullFilepath(Scope);
89 // Skip this instruction if it has the same file:line as the previous one.
91 if (!CurFn->Instrs.empty()) {
92 const InstrInfoTy &LastInstr = InstrInfo[CurFn->Instrs.back()];
93 if (LastInstr.Filename == Filename && LastInstr.LineNumber == DL.getLine())
96 FileNameRegistry.add(Filename);
98 MCSymbol *MCL = Asm->MMI->getContext().CreateTempSymbol();
99 Asm->OutStreamer.EmitLabel(MCL);
100 CurFn->Instrs.push_back(MCL);
101 InstrInfo[MCL] = InstrInfoTy(Filename, DL.getLine());
104 WinCodeViewLineTables::WinCodeViewLineTables(AsmPrinter *AP)
105 : Asm(nullptr), CurFn(nullptr) {
106 MachineModuleInfo *MMI = AP->MMI;
108 // If module doesn't have named metadata anchors or COFF debug section
109 // is not available, skip any debug info related stuff.
110 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
111 !AP->getObjFileLowering().getCOFFDebugSymbolsSection())
114 // Tell MMI that we have debug info.
115 MMI->setDebugInfoAvailability(true);
119 void WinCodeViewLineTables::endModule() {
120 if (FnDebugInfo.empty())
123 assert(Asm != nullptr);
124 Asm->OutStreamer.SwitchSection(
125 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
126 Asm->EmitInt32(COFF::DEBUG_SECTION_MAGIC);
128 // The COFF .debug$S section consists of several subsections, each starting
129 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
130 // of the payload followed by the payload itself. The subsections are 4-byte
133 // Emit per-function debug information. This code is extracted into a
134 // separate function for readability.
135 for (size_t I = 0, E = VisitedFunctions.size(); I != E; ++I)
136 emitDebugInfoForFunction(VisitedFunctions[I]);
138 // This subsection holds a file index to offset in string table table.
139 Asm->OutStreamer.AddComment("File index to string table offset subsection");
140 Asm->EmitInt32(COFF::DEBUG_INDEX_SUBSECTION);
141 size_t NumFilenames = FileNameRegistry.Infos.size();
142 Asm->EmitInt32(8 * NumFilenames);
143 for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {
144 StringRef Filename = FileNameRegistry.Filenames[I];
145 // For each unique filename, just write its offset in the string table.
146 Asm->EmitInt32(FileNameRegistry.Infos[Filename].StartOffset);
147 // The function name offset is not followed by any additional data.
151 // This subsection holds the string table.
152 Asm->OutStreamer.AddComment("String table");
153 Asm->EmitInt32(COFF::DEBUG_STRING_TABLE_SUBSECTION);
154 Asm->EmitInt32(FileNameRegistry.LastOffset);
155 // The payload starts with a null character.
158 for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {
159 // Just emit unique filenames one by one, separated by a null character.
160 Asm->OutStreamer.EmitBytes(FileNameRegistry.Filenames[I]);
164 // No more subsections. Fill with zeros to align the end of the section by 4.
165 Asm->OutStreamer.EmitFill((-FileNameRegistry.LastOffset) % 4, 0);
170 static void EmitLabelDiff(MCStreamer &Streamer,
171 const MCSymbol *From, const MCSymbol *To,
172 unsigned int Size = 4) {
173 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
174 MCContext &Context = Streamer.getContext();
175 const MCExpr *FromRef = MCSymbolRefExpr::Create(From, Variant, Context),
176 *ToRef = MCSymbolRefExpr::Create(To, Variant, Context);
177 const MCExpr *AddrDelta =
178 MCBinaryExpr::Create(MCBinaryExpr::Sub, ToRef, FromRef, Context);
179 Streamer.EmitValue(AddrDelta, Size);
182 void WinCodeViewLineTables::emitDebugInfoForFunction(const Function *GV) {
183 // For each function there is a separate subsection
184 // which holds the PC to file:line table.
185 const MCSymbol *Fn = Asm->getSymbol(GV);
188 const FunctionInfo &FI = FnDebugInfo[GV];
189 if (FI.Instrs.empty())
191 assert(FI.End && "Don't know where the function ends?");
193 const StringRef FuncName = getDISubprogram(GV).getDisplayName();
194 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
195 MCSymbol *SymbolsBegin = Asm->MMI->getContext().CreateTempSymbol(),
196 *SymbolsEnd = Asm->MMI->getContext().CreateTempSymbol();
197 Asm->OutStreamer.AddComment("Symbol subsection for " + Twine(FuncName));
198 Asm->EmitInt32(COFF::DEBUG_SYMBOL_SUBSECTION);
199 EmitLabelDiff(Asm->OutStreamer, SymbolsBegin, SymbolsEnd);
200 Asm->OutStreamer.EmitLabel(SymbolsBegin);
202 MCSymbol *ProcSegmentBegin = Asm->MMI->getContext().CreateTempSymbol(),
203 *ProcSegmentEnd = Asm->MMI->getContext().CreateTempSymbol();
204 EmitLabelDiff(Asm->OutStreamer, ProcSegmentBegin, ProcSegmentEnd, 2);
205 Asm->OutStreamer.EmitLabel(ProcSegmentBegin);
207 Asm->EmitInt16(COFF::DEBUG_SYMBOL_TYPE_PROC_START);
208 // Some bytes of this segment don't seem to be required for basic debugging,
209 // so just fill them with zeroes.
210 Asm->OutStreamer.EmitFill(12, 0);
211 // This is the important bit that tells the debugger where the function
212 // code is located and what's its size:
213 EmitLabelDiff(Asm->OutStreamer, Fn, FI.End);
214 Asm->OutStreamer.EmitFill(12, 0);
215 Asm->OutStreamer.EmitCOFFSecRel32(Fn);
216 Asm->OutStreamer.EmitCOFFSectionIndex(Fn);
218 // Emit the function name as a null-terminated string.
219 Asm->OutStreamer.EmitBytes(FuncName);
221 Asm->OutStreamer.EmitLabel(ProcSegmentEnd);
223 // We're done with this function.
224 Asm->EmitInt16(0x0002);
225 Asm->EmitInt16(COFF::DEBUG_SYMBOL_TYPE_PROC_END);
227 Asm->OutStreamer.EmitLabel(SymbolsEnd);
228 // Every subsection must be aligned to a 4-byte boundary.
229 Asm->OutStreamer.EmitFill((-FuncName.size()) % 4, 0);
231 // PCs/Instructions are grouped into segments sharing the same filename.
232 // Pre-calculate the lengths (in instructions) of these segments and store
233 // them in a map for convenience. Each index in the map is the sequential
234 // number of the respective instruction that starts a new segment.
235 DenseMap<size_t, size_t> FilenameSegmentLengths;
236 size_t LastSegmentEnd = 0;
237 StringRef PrevFilename = InstrInfo[FI.Instrs[0]].Filename;
238 for (size_t J = 1, F = FI.Instrs.size(); J != F; ++J) {
239 if (PrevFilename == InstrInfo[FI.Instrs[J]].Filename)
241 FilenameSegmentLengths[LastSegmentEnd] = J - LastSegmentEnd;
243 PrevFilename = InstrInfo[FI.Instrs[J]].Filename;
245 FilenameSegmentLengths[LastSegmentEnd] = FI.Instrs.size() - LastSegmentEnd;
247 // Emit a line table subsection, requred to do PC-to-file:line lookup.
248 Asm->OutStreamer.AddComment("Line table subsection for " + Twine(FuncName));
249 Asm->EmitInt32(COFF::DEBUG_LINE_TABLE_SUBSECTION);
250 MCSymbol *LineTableBegin = Asm->MMI->getContext().CreateTempSymbol(),
251 *LineTableEnd = Asm->MMI->getContext().CreateTempSymbol();
252 EmitLabelDiff(Asm->OutStreamer, LineTableBegin, LineTableEnd);
253 Asm->OutStreamer.EmitLabel(LineTableBegin);
255 // Identify the function this subsection is for.
256 Asm->OutStreamer.EmitCOFFSecRel32(Fn);
257 Asm->OutStreamer.EmitCOFFSectionIndex(Fn);
258 // Insert padding after a 16-bit section index.
261 // Length of the function's code, in bytes.
262 EmitLabelDiff(Asm->OutStreamer, Fn, FI.End);
264 // PC-to-linenumber lookup table:
265 MCSymbol *FileSegmentEnd = nullptr;
266 for (size_t J = 0, F = FI.Instrs.size(); J != F; ++J) {
267 MCSymbol *Instr = FI.Instrs[J];
268 assert(InstrInfo.count(Instr));
270 if (FilenameSegmentLengths.count(J)) {
271 // We came to a beginning of a new filename segment.
273 Asm->OutStreamer.EmitLabel(FileSegmentEnd);
274 StringRef CurFilename = InstrInfo[FI.Instrs[J]].Filename;
275 assert(FileNameRegistry.Infos.count(CurFilename));
276 size_t IndexInStringTable =
277 FileNameRegistry.Infos[CurFilename].FilenameID;
278 // Each segment starts with the offset of the filename
279 // in the string table.
280 Asm->OutStreamer.AddComment(
281 "Segment for file '" + Twine(CurFilename) + "' begins");
282 MCSymbol *FileSegmentBegin = Asm->MMI->getContext().CreateTempSymbol();
283 Asm->OutStreamer.EmitLabel(FileSegmentBegin);
284 Asm->EmitInt32(8 * IndexInStringTable);
286 // Number of PC records in the lookup table.
287 size_t SegmentLength = FilenameSegmentLengths[J];
288 Asm->EmitInt32(SegmentLength);
290 // Full size of the segment for this filename, including the prev two
292 FileSegmentEnd = Asm->MMI->getContext().CreateTempSymbol();
293 EmitLabelDiff(Asm->OutStreamer, FileSegmentBegin, FileSegmentEnd);
296 // The first PC with the given linenumber and the linenumber itself.
297 EmitLabelDiff(Asm->OutStreamer, Fn, Instr);
298 Asm->EmitInt32(InstrInfo[Instr].LineNumber);
302 Asm->OutStreamer.EmitLabel(FileSegmentEnd);
303 Asm->OutStreamer.EmitLabel(LineTableEnd);
306 void WinCodeViewLineTables::beginFunction(const MachineFunction *MF) {
307 assert(!CurFn && "Can't process two functions at once!");
309 if (!Asm || !Asm->MMI->hasDebugInfo())
312 const Function *GV = MF->getFunction();
313 assert(FnDebugInfo.count(GV) == false);
314 VisitedFunctions.push_back(GV);
315 CurFn = &FnDebugInfo[GV];
317 // Find the end of the function prolog.
318 // FIXME: is there a simpler a way to do this? Can we just search
319 // for the first instruction of the function, not the last of the prolog?
320 DebugLoc PrologEndLoc;
321 bool EmptyPrologue = true;
322 for (const auto &MBB : *MF) {
323 if (!PrologEndLoc.isUnknown())
325 for (const auto &MI : MBB) {
326 if (MI.isDebugValue())
329 // First known non-DBG_VALUE and non-frame setup location marks
330 // the beginning of the function body.
331 // FIXME: do we need the first subcondition?
332 if (!MI.getFlag(MachineInstr::FrameSetup) &&
333 (!MI.getDebugLoc().isUnknown())) {
334 PrologEndLoc = MI.getDebugLoc();
337 EmptyPrologue = false;
340 // Record beginning of function if we have a non-empty prologue.
341 if (!PrologEndLoc.isUnknown() && !EmptyPrologue) {
343 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
344 maybeRecordLocation(FnStartDL, MF);
348 void WinCodeViewLineTables::endFunction(const MachineFunction *MF) {
349 if (!Asm || !CurFn) // We haven't created any debug info for this function.
352 const Function *GV = MF->getFunction();
353 assert(FnDebugInfo.count(GV));
354 assert(CurFn == &FnDebugInfo[GV]);
356 if (CurFn->Instrs.empty()) {
357 FnDebugInfo.erase(GV);
358 VisitedFunctions.pop_back();
360 // Define end label for subprogram.
361 MCSymbol *FunctionEndSym = Asm->OutStreamer.getContext().CreateTempSymbol();
362 Asm->OutStreamer.EmitLabel(FunctionEndSym);
363 CurFn->End = FunctionEndSym;
368 void WinCodeViewLineTables::beginInstruction(const MachineInstr *MI) {
369 // Ignore DBG_VALUE locations and function prologue.
370 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
372 DebugLoc DL = MI->getDebugLoc();
373 if (DL == PrevInstLoc || DL.isUnknown())
375 maybeRecordLocation(DL, Asm->MF);