1 //===- MCCodeView.h - Machine Code CodeView support -------------*- 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 // Holds state from .cv_file and .cv_loc directives for later emission.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCCodeView.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/DebugInfo/CodeView/CodeView.h"
18 #include "llvm/DebugInfo/CodeView/Line.h"
19 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCObjectStreamer.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Support/EndianStream.h"
27 using namespace llvm::codeview;
29 CodeViewContext::CodeViewContext() {}
31 CodeViewContext::~CodeViewContext() {
32 // If someone inserted strings into the string table but never actually
33 // emitted them somewhere, clean up the fragment.
34 if (!InsertedStrTabFragment)
35 delete StrTabFragment;
38 /// This is a valid number for use with .cv_loc if we've already seen a .cv_file
40 bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const {
41 unsigned Idx = FileNumber - 1;
42 if (Idx < Filenames.size())
43 return !Filenames[Idx].empty();
47 bool CodeViewContext::addFile(unsigned FileNumber, StringRef Filename) {
48 assert(FileNumber > 0);
49 Filename = addToStringTable(Filename);
50 unsigned Idx = FileNumber - 1;
51 if (Idx >= Filenames.size())
52 Filenames.resize(Idx + 1);
57 if (!Filenames[Idx].empty())
60 // FIXME: We should store the string table offset of the filename, rather than
61 // the filename itself for efficiency.
62 Filename = addToStringTable(Filename);
64 Filenames[Idx] = Filename;
68 MCDataFragment *CodeViewContext::getStringTableFragment() {
69 if (!StrTabFragment) {
70 StrTabFragment = new MCDataFragment();
71 // Start a new string table out with a null byte.
72 StrTabFragment->getContents().push_back('\0');
74 return StrTabFragment;
77 StringRef CodeViewContext::addToStringTable(StringRef S) {
78 SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents();
80 StringTable.insert(std::make_pair(S, unsigned(Contents.size())));
81 // Return the string from the table, since it is stable.
82 S = Insertion.first->first();
83 if (Insertion.second) {
84 // The string map key is always null terminated.
85 Contents.append(S.begin(), S.end() + 1);
90 unsigned CodeViewContext::getStringTableOffset(StringRef S) {
91 // A string table offset of zero is always the empty string.
94 auto I = StringTable.find(S);
95 assert(I != StringTable.end());
99 void CodeViewContext::emitStringTable(MCObjectStreamer &OS) {
100 MCContext &Ctx = OS.getContext();
101 MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false),
102 *StringEnd = Ctx.createTempSymbol("strtab_end", false);
104 OS.EmitIntValue(unsigned(ModuleSubstreamKind::StringTable), 4);
105 OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
106 OS.EmitLabel(StringBegin);
108 // Put the string table data fragment here, if we haven't already put it
109 // somewhere else. If somebody wants two string tables in their .s file, one
110 // will just be empty.
111 if (!InsertedStrTabFragment) {
112 OS.insert(getStringTableFragment());
113 InsertedStrTabFragment = true;
116 OS.EmitValueToAlignment(4, 0);
118 OS.EmitLabel(StringEnd);
121 void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) {
122 // Do nothing if there are no file checksums. Microsoft's linker rejects empty
123 // CodeView substreams.
124 if (Filenames.empty())
127 MCContext &Ctx = OS.getContext();
128 MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false),
129 *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
131 OS.EmitIntValue(unsigned(ModuleSubstreamKind::FileChecksums), 4);
132 OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
133 OS.EmitLabel(FileBegin);
135 // Emit an array of FileChecksum entries. We index into this table using the
136 // user-provided file number. Each entry is currently 8 bytes, as we don't
138 for (StringRef Filename : Filenames) {
139 OS.EmitIntValue(getStringTableOffset(Filename), 4);
140 // Zero the next two fields and align back to 4 bytes. This indicates that
141 // no checksum is present.
142 OS.EmitIntValue(0, 4);
145 OS.EmitLabel(FileEnd);
148 void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS,
150 const MCSymbol *FuncBegin,
151 const MCSymbol *FuncEnd) {
152 MCContext &Ctx = OS.getContext();
153 MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false),
154 *LineEnd = Ctx.createTempSymbol("linetable_end", false);
156 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Lines), 4);
157 OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
158 OS.EmitLabel(LineBegin);
159 OS.EmitCOFFSecRel32(FuncBegin);
160 OS.EmitCOFFSectionIndex(FuncBegin);
163 std::vector<MCCVLineEntry> Locs = getFunctionLineEntries(FuncId);
164 bool HaveColumns = any_of(Locs, [](const MCCVLineEntry &LineEntry) {
165 return LineEntry.getColumn() != 0;
167 OS.EmitIntValue(HaveColumns ? int(LineFlags::HaveColumns) : 0, 2);
168 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4);
170 for (auto I = Locs.begin(), E = Locs.end(); I != E;) {
171 // Emit a file segment for the run of locations that share a file id.
172 unsigned CurFileNum = I->getFileNum();
174 std::find_if(I, E, [CurFileNum](const MCCVLineEntry &Loc) {
175 return Loc.getFileNum() != CurFileNum;
177 unsigned EntryCount = FileSegEnd - I;
178 OS.AddComment("Segment for file '" + Twine(Filenames[CurFileNum - 1]) +
180 OS.EmitIntValue(8 * (CurFileNum - 1), 4);
181 OS.EmitIntValue(EntryCount, 4);
182 uint32_t SegmentSize = 12;
183 SegmentSize += 8 * EntryCount;
185 SegmentSize += 4 * EntryCount;
186 OS.EmitIntValue(SegmentSize, 4);
188 for (auto J = I; J != FileSegEnd; ++J) {
189 OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
190 unsigned LineData = J->getLine();
192 LineData |= LineInfo::StatementFlag;
193 OS.EmitIntValue(LineData, 4);
196 for (auto J = I; J != FileSegEnd; ++J) {
197 OS.EmitIntValue(J->getColumn(), 2);
198 OS.EmitIntValue(0, 2);
203 OS.EmitLabel(LineEnd);
206 static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) {
207 if (isUInt<7>(Data)) {
208 Buffer.push_back(Data);
212 if (isUInt<14>(Data)) {
213 Buffer.push_back((Data >> 8) | 0x80);
214 Buffer.push_back(Data & 0xff);
218 if (isUInt<29>(Data)) {
219 Buffer.push_back((Data >> 24) | 0xC0);
220 Buffer.push_back((Data >> 16) & 0xff);
221 Buffer.push_back((Data >> 8) & 0xff);
222 Buffer.push_back(Data & 0xff);
229 static bool compressAnnotation(BinaryAnnotationsOpCode Annotation,
230 SmallVectorImpl<char> &Buffer) {
231 return compressAnnotation(static_cast<uint32_t>(Annotation), Buffer);
234 static uint32_t encodeSignedNumber(uint32_t Data) {
236 return ((-Data) << 1) | 1;
240 void CodeViewContext::emitInlineLineTableForFunction(
241 MCObjectStreamer &OS, unsigned PrimaryFunctionId, unsigned SourceFileId,
242 unsigned SourceLineNum, const MCSymbol *FnStartSym,
243 const MCSymbol *FnEndSym, ArrayRef<unsigned> SecondaryFunctionIds) {
244 // Create and insert a fragment into the current section that will be encoded
246 new MCCVInlineLineTableFragment(
247 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym,
248 SecondaryFunctionIds, OS.getCurrentSectionOnly());
251 void CodeViewContext::emitDefRange(
252 MCObjectStreamer &OS,
253 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
254 StringRef FixedSizePortion) {
255 // Create and insert a fragment into the current section that will be encoded
257 new MCCVDefRangeFragment(Ranges, FixedSizePortion,
258 OS.getCurrentSectionOnly());
261 static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin,
262 const MCSymbol *End) {
263 MCContext &Ctx = Layout.getAssembler().getContext();
264 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
265 const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
266 *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
267 const MCExpr *AddrDelta =
268 MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
270 bool Success = AddrDelta->evaluateKnownAbsolute(Result, Layout);
271 assert(Success && "failed to evaluate label difference as absolute");
273 assert(Result >= 0 && "negative label difference requested");
274 assert(Result < UINT_MAX && "label difference greater than 2GB");
275 return unsigned(Result);
278 void CodeViewContext::encodeInlineLineTable(MCAsmLayout &Layout,
279 MCCVInlineLineTableFragment &Frag) {
282 std::tie(LocBegin, LocEnd) = getLineExtent(Frag.SiteFuncId);
283 for (unsigned SecondaryId : Frag.SecondaryFuncs) {
284 auto Extent = getLineExtent(SecondaryId);
285 LocBegin = std::min(LocBegin, Extent.first);
286 LocEnd = std::max(LocEnd, Extent.second);
288 if (LocBegin >= LocEnd)
290 ArrayRef<MCCVLineEntry> Locs = getLinesForExtent(LocBegin, LocEnd);
294 SmallSet<unsigned, 8> InlinedFuncIds;
295 InlinedFuncIds.insert(Frag.SiteFuncId);
296 InlinedFuncIds.insert(Frag.SecondaryFuncs.begin(), Frag.SecondaryFuncs.end());
298 // Make an artificial start location using the function start and the inlinee
299 // lines start location information. All deltas start relative to this
301 MCCVLineEntry StartLoc(Frag.getFnStartSym(), MCCVLoc(Locs.front()));
302 StartLoc.setFileNum(Frag.StartFileId);
303 StartLoc.setLine(Frag.StartLineNum);
304 const MCCVLineEntry *LastLoc = &StartLoc;
305 bool HaveOpenRange = false;
307 SmallVectorImpl<char> &Buffer = Frag.getContents();
308 Buffer.clear(); // Clear old contents if we went through relaxation.
309 for (const MCCVLineEntry &Loc : Locs) {
310 if (!InlinedFuncIds.count(Loc.getFunctionId())) {
311 // We've hit a cv_loc not attributed to this inline call site. Use this
312 // label to end the PC range.
315 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
316 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
317 compressAnnotation(Length, Buffer);
319 HaveOpenRange = false;
323 // If we've already opened the function and we're at an indirectly inlined
324 // location, continue until the next directly inlined location.
325 bool DirectlyInlined = Loc.getFunctionId() == Frag.SiteFuncId;
326 if (!DirectlyInlined && HaveOpenRange)
328 HaveOpenRange = true;
330 if (Loc.getFileNum() != LastLoc->getFileNum()) {
331 // File ids are 1 based, and each file checksum table entry is 8 bytes
332 // long. See emitFileChecksums above.
333 unsigned FileOffset = 8 * (Loc.getFileNum() - 1);
334 compressAnnotation(BinaryAnnotationsOpCode::ChangeFile, Buffer);
335 compressAnnotation(FileOffset, Buffer);
338 int LineDelta = Loc.getLine() - LastLoc->getLine();
342 unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
344 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
345 if (CodeDelta == 0) {
346 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
347 compressAnnotation(EncodedLineDelta, Buffer);
348 } else if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
349 // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
350 // encoded line delta uses 3 or fewer set bits and the code offset fits
352 unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
353 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset,
355 compressAnnotation(Operand, Buffer);
357 // Otherwise use the separate line and code deltas.
358 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
359 compressAnnotation(EncodedLineDelta, Buffer);
360 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer);
361 compressAnnotation(CodeDelta, Buffer);
367 assert(HaveOpenRange);
369 unsigned EndSymLength =
370 computeLabelDiff(Layout, LastLoc->getLabel(), Frag.getFnEndSym());
371 unsigned LocAfterLength = ~0U;
372 ArrayRef<MCCVLineEntry> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
373 if (!LocAfter.empty()) {
374 // Only try to compute this difference if we're in the same section.
375 const MCCVLineEntry &Loc = LocAfter[0];
376 if (&Loc.getLabel()->getSection(false) ==
377 &LastLoc->getLabel()->getSection(false)) {
379 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
383 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
384 compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
387 void CodeViewContext::encodeDefRange(MCAsmLayout &Layout,
388 MCCVDefRangeFragment &Frag) {
389 MCContext &Ctx = Layout.getAssembler().getContext();
390 SmallVectorImpl<char> &Contents = Frag.getContents();
392 SmallVectorImpl<MCFixup> &Fixups = Frag.getFixups();
394 raw_svector_ostream OS(Contents);
396 // Write down each range where the variable is defined.
397 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) {
398 unsigned RangeSize = computeLabelDiff(Layout, Range.first, Range.second);
400 // We must split the range into chunks of MaxDefRange, this is a fundamental
401 // limitation of the file format.
403 uint16_t Chunk = std::min((uint32_t)MaxDefRange, RangeSize);
405 const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Range.first, Ctx);
406 const MCBinaryExpr *BE =
407 MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(Bias, Ctx), Ctx);
409 BE->evaluateAsRelocatable(Res, &Layout, /*Fixup=*/nullptr);
411 // Each record begins with a 2-byte number indicating how large the record
413 StringRef FixedSizePortion = Frag.getFixedSizePortion();
414 // Our record is a fixed sized prefix and a LocalVariableAddrRange that we
415 // are artificially constructing.
417 FixedSizePortion.size() + sizeof(LocalVariableAddrRange);
418 // Write out the recrod size.
419 support::endian::Writer<support::little>(OS).write<uint16_t>(RecordSize);
420 // Write out the fixed size prefix.
421 OS << FixedSizePortion;
422 // Make space for a fixup that will eventually have a section relative
423 // relocation pointing at the offset where the variable becomes live.
424 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_4));
425 Contents.resize(Contents.size() + 4); // Fixup for code start.
426 // Make space for a fixup that will record the section index for the code.
427 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2));
428 Contents.resize(Contents.size() + 2); // Fixup for section index.
429 // Write down the range's extent.
430 support::endian::Writer<support::little>(OS).write<uint16_t>(Chunk);
432 // Move on to the next range.
435 } while (RangeSize > 0);
440 // This is called when an instruction is assembled into the specified section
441 // and if there is information from the last .cv_loc directive that has yet to have
442 // a line entry made for it is made.
444 void MCCVLineEntry::Make(MCObjectStreamer *MCOS) {
445 if (!MCOS->getContext().getCVLocSeen())
448 // Create a symbol at in the current section for use in the line entry.
449 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
450 // Set the value of the symbol to use for the MCCVLineEntry.
451 MCOS->EmitLabel(LineSym);
453 // Get the current .loc info saved in the context.
454 const MCCVLoc &CVLoc = MCOS->getContext().getCurrentCVLoc();
456 // Create a (local) line entry with the symbol and the current .loc info.
457 MCCVLineEntry LineEntry(LineSym, CVLoc);
459 // clear CVLocSeen saying the current .loc info is now used.
460 MCOS->getContext().clearCVLocSeen();
462 // Add the line entry to this section's entries.
463 MCOS->getContext().getCVContext().addLineEntry(LineEntry);