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 *Asm)
105 : Asm(Asm), CurFn(0) {
106 // Tell MMI that we have debug info.
107 Asm->MMI->setDebugInfoAvailability(true);
110 static void EmitLabelDiff(MCStreamer &Streamer,
111 const MCSymbol *From, const MCSymbol *To) {
112 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
113 MCContext &Context = Streamer.getContext();
114 const MCExpr *FromRef = MCSymbolRefExpr::Create(From, Variant, Context),
115 *ToRef = MCSymbolRefExpr::Create(To, Variant, Context);
116 const MCExpr *AddrDelta =
117 MCBinaryExpr::Create(MCBinaryExpr::Sub, ToRef, FromRef, Context);
118 Streamer.EmitValue(AddrDelta, 4);
121 void WinCodeViewLineTables::emitDebugInfoForFunction(const Function *GV) {
122 // For each function there is a separate subsection
123 // which holds the PC to file:line table.
124 const MCSymbol *Fn = Asm->getSymbol(GV);
125 const FunctionInfo &FI = FnDebugInfo[GV];
127 assert(FI.Instrs.size() > 0);
129 // PCs/Instructions are grouped into segments sharing the same filename.
130 // Pre-calculate the lengths (in instructions) of these segments and store
131 // them in a map for convenience. Each index in the map is the sequential
132 // number of the respective instruction that starts a new segment.
133 DenseMap<size_t, size_t> FilenameSegmentLengths;
134 size_t LastSegmentEnd = 0;
135 StringRef PrevFilename = InstrInfo[FI.Instrs[0]].Filename;
136 for (size_t J = 1, F = FI.Instrs.size(); J != F; ++J) {
137 if (PrevFilename == InstrInfo[FI.Instrs[J]].Filename)
139 FilenameSegmentLengths[LastSegmentEnd] = J - LastSegmentEnd;
141 PrevFilename = InstrInfo[FI.Instrs[J]].Filename;
143 FilenameSegmentLengths[LastSegmentEnd] = FI.Instrs.size() - LastSegmentEnd;
145 // Emit the control code of the subsection followed by the payload size.
146 Asm->OutStreamer.AddComment(
147 "Linetable subsection for " + Twine(Fn->getName()));
148 Asm->EmitInt32(COFF::DEBUG_LINE_TABLE_SUBSECTION);
149 MCSymbol *SubsectionBegin = Asm->MMI->getContext().CreateTempSymbol(),
150 *SubsectionEnd = Asm->MMI->getContext().CreateTempSymbol();
151 EmitLabelDiff(Asm->OutStreamer, SubsectionBegin, SubsectionEnd);
152 Asm->OutStreamer.EmitLabel(SubsectionBegin);
154 // Identify the function this subsection is for.
155 Asm->OutStreamer.EmitCOFFSecRel32(Fn);
156 Asm->OutStreamer.EmitCOFFSectionIndex(Fn);
158 // Length of the function's code, in bytes.
159 EmitLabelDiff(Asm->OutStreamer, Fn, FI.End);
161 // PC-to-linenumber lookup table:
162 MCSymbol *FileSegmentEnd = 0;
163 for (size_t J = 0, F = FI.Instrs.size(); J != F; ++J) {
164 MCSymbol *Instr = FI.Instrs[J];
165 assert(InstrInfo.count(Instr));
167 if (FilenameSegmentLengths.count(J)) {
168 // We came to a beginning of a new filename segment.
170 Asm->OutStreamer.EmitLabel(FileSegmentEnd);
171 StringRef CurFilename = InstrInfo[FI.Instrs[J]].Filename;
172 assert(FileNameRegistry.Infos.count(CurFilename));
173 size_t IndexInStringTable =
174 FileNameRegistry.Infos[CurFilename].FilenameID;
175 // Each segment starts with the offset of the filename
176 // in the string table.
177 Asm->OutStreamer.AddComment(
178 "Segment for file '" + Twine(CurFilename) + "' begins");
179 MCSymbol *FileSegmentBegin = Asm->MMI->getContext().CreateTempSymbol();
180 Asm->OutStreamer.EmitLabel(FileSegmentBegin);
181 Asm->EmitInt32(8 * IndexInStringTable);
183 // Number of PC records in the lookup table.
184 size_t SegmentLength = FilenameSegmentLengths[J];
185 Asm->EmitInt32(SegmentLength);
187 // Full size of the segment for this filename, including the prev two
189 FileSegmentEnd = Asm->MMI->getContext().CreateTempSymbol();
190 EmitLabelDiff(Asm->OutStreamer, FileSegmentBegin, FileSegmentEnd);
193 // The first PC with the given linenumber and the linenumber itself.
194 EmitLabelDiff(Asm->OutStreamer, Fn, Instr);
195 Asm->EmitInt32(InstrInfo[Instr].LineNumber);
199 Asm->OutStreamer.EmitLabel(FileSegmentEnd);
200 Asm->OutStreamer.EmitLabel(SubsectionEnd);
203 void WinCodeViewLineTables::endModule() {
204 if (FnDebugInfo.empty())
207 Asm->OutStreamer.SwitchSection(
208 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
209 Asm->EmitInt32(COFF::DEBUG_SECTION_MAGIC);
211 // The COFF .debug$S section consists of several subsections, each starting
212 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
213 // of the payload followed by the payload itself. The subsections are 4-byte
216 for (size_t I = 0, E = VisitedFunctions.size(); I != E; ++I)
217 emitDebugInfoForFunction(VisitedFunctions[I]);
219 // This subsection holds a file index to offset in string table table.
220 Asm->OutStreamer.AddComment("File index to string table offset subsection");
221 Asm->EmitInt32(COFF::DEBUG_INDEX_SUBSECTION);
222 size_t NumFilenames = FileNameRegistry.Infos.size();
223 Asm->EmitInt32(8 * NumFilenames);
224 for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {
225 StringRef Filename = FileNameRegistry.Filenames[I];
226 // For each unique filename, just write it's offset in the string table.
227 Asm->EmitInt32(FileNameRegistry.Infos[Filename].StartOffset);
228 // The function name offset is not followed by any additional data.
232 // This subsection holds the string table.
233 Asm->OutStreamer.AddComment("String table");
234 Asm->EmitInt32(COFF::DEBUG_STRING_TABLE_SUBSECTION);
235 Asm->EmitInt32(FileNameRegistry.LastOffset);
236 // The payload starts with a null character.
239 for (size_t I = 0, E = FileNameRegistry.Filenames.size(); I != E; ++I) {
240 // Just emit unique filenames one by one, separated by a null character.
241 Asm->OutStreamer.EmitBytes(FileNameRegistry.Filenames[I]);
245 // No more subsections. Fill with zeros to align the end of the section by 4.
246 Asm->OutStreamer.EmitFill((-FileNameRegistry.LastOffset) % 4, 0);
251 void WinCodeViewLineTables::beginFunction(const MachineFunction *MF) {
252 assert(!CurFn && "Can't process two functions at once!");
254 if (!Asm->MMI->hasDebugInfo())
257 // Grab the lexical scopes for the function, if we don't have any of those
258 // then we're not going to be able to do anything.
259 LScopes.initialize(*MF);
263 const Function *GV = MF->getFunction();
264 assert(FnDebugInfo.count(GV) == false);
265 VisitedFunctions.push_back(GV);
266 CurFn = &FnDebugInfo[GV];
268 // Find the end of the function prolog.
269 // FIXME: is there a simpler a way to do this? Can we just search
270 // for the first instruction of the function, not the last of the prolog?
271 DebugLoc PrologEndLoc;
272 bool EmptyPrologue = true;
273 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
274 I != E && PrologEndLoc.isUnknown(); ++I) {
275 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
277 const MachineInstr *MI = II;
278 if (MI->isDebugValue())
281 // First known non-DBG_VALUE and non-frame setup location marks
282 // the beginning of the function body.
283 // FIXME: do we need the first subcondition?
284 if (!MI->getFlag(MachineInstr::FrameSetup) &&
285 (!MI->getDebugLoc().isUnknown())) {
286 PrologEndLoc = MI->getDebugLoc();
289 EmptyPrologue = false;
292 // Record beginning of function if we have a non-empty prologue.
293 if (!PrologEndLoc.isUnknown() && !EmptyPrologue) {
295 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
296 maybeRecordLocation(FnStartDL, MF);
300 void WinCodeViewLineTables::endFunction(const MachineFunction *) {
301 if (!CurFn) // We haven't created any debug info for this function.
304 if (CurFn->Instrs.empty())
305 llvm_unreachable("Can this ever happen?");
307 // Define end label for subprogram.
308 MCSymbol *FunctionEndSym = Asm->OutStreamer.getContext().CreateTempSymbol();
309 Asm->OutStreamer.EmitLabel(FunctionEndSym);
310 CurFn->End = FunctionEndSym;
314 void WinCodeViewLineTables::beginInstruction(const MachineInstr *MI) {
315 // Ignore DBG_VALUE locations and function prologue.
316 if (MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
318 DebugLoc DL = MI->getDebugLoc();
319 if (DL == PrevInstLoc || DL.isUnknown())
321 maybeRecordLocation(DL, Asm->MF);