LLVM  7.0.0svn
MCCodeView.cpp
Go to the documentation of this file.
1 //===- MCCodeView.h - Machine Code CodeView support -------------*- 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 // Holds state from .cv_file and .cv_loc directives for later emission.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/MC/MCCodeView.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCValue.h"
25 
26 using namespace llvm;
27 using namespace llvm::codeview;
28 
30 
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;
36 }
37 
38 /// This is a valid number for use with .cv_loc if we've already seen a .cv_file
39 /// for it.
40 bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const {
41  unsigned Idx = FileNumber - 1;
42  if (Idx < Files.size())
43  return Files[Idx].Assigned;
44  return false;
45 }
46 
47 bool CodeViewContext::addFile(MCStreamer &OS, unsigned FileNumber,
48  StringRef Filename,
49  ArrayRef<uint8_t> ChecksumBytes,
50  uint8_t ChecksumKind) {
51  assert(FileNumber > 0);
52  auto FilenameOffset = addToStringTable(Filename);
53  Filename = FilenameOffset.first;
54  unsigned Idx = FileNumber - 1;
55  if (Idx >= Files.size())
56  Files.resize(Idx + 1);
57 
58  if (Filename.empty())
59  Filename = "<stdin>";
60 
61  if (Files[Idx].Assigned)
62  return false;
63 
64  FilenameOffset = addToStringTable(Filename);
65  Filename = FilenameOffset.first;
66  unsigned Offset = FilenameOffset.second;
67 
68  auto ChecksumOffsetSymbol =
69  OS.getContext().createTempSymbol("checksum_offset", false);
70  Files[Idx].StringTableOffset = Offset;
71  Files[Idx].ChecksumTableOffset = ChecksumOffsetSymbol;
72  Files[Idx].Assigned = true;
73  Files[Idx].Checksum = ChecksumBytes;
74  Files[Idx].ChecksumKind = ChecksumKind;
75 
76  return true;
77 }
78 
80  if (FuncId >= Functions.size())
81  return nullptr;
82  if (Functions[FuncId].isUnallocatedFunctionInfo())
83  return nullptr;
84  return &Functions[FuncId];
85 }
86 
87 bool CodeViewContext::recordFunctionId(unsigned FuncId) {
88  if (FuncId >= Functions.size())
89  Functions.resize(FuncId + 1);
90 
91  // Return false if this function info was already allocated.
92  if (!Functions[FuncId].isUnallocatedFunctionInfo())
93  return false;
94 
95  // Mark this as an allocated normal function, and leave the rest alone.
96  Functions[FuncId].ParentFuncIdPlusOne = MCCVFunctionInfo::FunctionSentinel;
97  return true;
98 }
99 
100 bool CodeViewContext::recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc,
101  unsigned IAFile, unsigned IALine,
102  unsigned IACol) {
103  if (FuncId >= Functions.size())
104  Functions.resize(FuncId + 1);
105 
106  // Return false if this function info was already allocated.
107  if (!Functions[FuncId].isUnallocatedFunctionInfo())
108  return false;
109 
110  MCCVFunctionInfo::LineInfo InlinedAt;
111  InlinedAt.File = IAFile;
112  InlinedAt.Line = IALine;
113  InlinedAt.Col = IACol;
114 
115  // Mark this as an inlined call site and record call site line info.
116  MCCVFunctionInfo *Info = &Functions[FuncId];
117  Info->ParentFuncIdPlusOne = IAFunc + 1;
118  Info->InlinedAt = InlinedAt;
119 
120  // Walk up the call chain adding this function id to the InlinedAtMap of all
121  // transitive callers until we hit a real function.
122  while (Info->isInlinedCallSite()) {
123  InlinedAt = Info->InlinedAt;
124  Info = getCVFunctionInfo(Info->getParentFuncId());
125  Info->InlinedAtMap[FuncId] = InlinedAt;
126  }
127 
128  return true;
129 }
130 
131 MCDataFragment *CodeViewContext::getStringTableFragment() {
132  if (!StrTabFragment) {
133  StrTabFragment = new MCDataFragment();
134  // Start a new string table out with a null byte.
135  StrTabFragment->getContents().push_back('\0');
136  }
137  return StrTabFragment;
138 }
139 
140 std::pair<StringRef, unsigned> CodeViewContext::addToStringTable(StringRef S) {
141  SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents();
142  auto Insertion =
143  StringTable.insert(std::make_pair(S, unsigned(Contents.size())));
144  // Return the string from the table, since it is stable.
145  std::pair<StringRef, unsigned> Ret =
146  std::make_pair(Insertion.first->first(), Insertion.first->second);
147  if (Insertion.second) {
148  // The string map key is always null terminated.
149  Contents.append(Ret.first.begin(), Ret.first.end() + 1);
150  }
151  return Ret;
152 }
153 
154 unsigned CodeViewContext::getStringTableOffset(StringRef S) {
155  // A string table offset of zero is always the empty string.
156  if (S.empty())
157  return 0;
158  auto I = StringTable.find(S);
159  assert(I != StringTable.end());
160  return I->second;
161 }
162 
164  MCContext &Ctx = OS.getContext();
165  MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false),
166  *StringEnd = Ctx.createTempSymbol("strtab_end", false);
167 
169  OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
170  OS.EmitLabel(StringBegin);
171 
172  // Put the string table data fragment here, if we haven't already put it
173  // somewhere else. If somebody wants two string tables in their .s file, one
174  // will just be empty.
175  if (!InsertedStrTabFragment) {
176  OS.insert(getStringTableFragment());
177  InsertedStrTabFragment = true;
178  }
179 
180  OS.EmitValueToAlignment(4, 0);
181 
182  OS.EmitLabel(StringEnd);
183 }
184 
186  // Do nothing if there are no file checksums. Microsoft's linker rejects empty
187  // CodeView substreams.
188  if (Files.empty())
189  return;
190 
191  MCContext &Ctx = OS.getContext();
192  MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false),
193  *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
194 
196  OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
197  OS.EmitLabel(FileBegin);
198 
199  unsigned CurrentOffset = 0;
200 
201  // Emit an array of FileChecksum entries. We index into this table using the
202  // user-provided file number. Each entry may be a variable number of bytes
203  // determined by the checksum kind and size.
204  for (auto File : Files) {
205  OS.EmitAssignment(File.ChecksumTableOffset,
206  MCConstantExpr::create(CurrentOffset, Ctx));
207  CurrentOffset += 4; // String table offset.
208  if (!File.ChecksumKind) {
209  CurrentOffset +=
210  4; // One byte each for checksum size and kind, then align to 4 bytes.
211  } else {
212  CurrentOffset += 2; // One byte each for checksum size and kind.
213  CurrentOffset += File.Checksum.size();
214  CurrentOffset = alignTo(CurrentOffset, 4);
215  }
216 
217  OS.EmitIntValue(File.StringTableOffset, 4);
218 
219  if (!File.ChecksumKind) {
220  // There is no checksum. Therefore zero the next two fields and align
221  // back to 4 bytes.
222  OS.EmitIntValue(0, 4);
223  continue;
224  }
225  OS.EmitIntValue(static_cast<uint8_t>(File.Checksum.size()), 1);
226  OS.EmitIntValue(File.ChecksumKind, 1);
227  OS.EmitBytes(toStringRef(File.Checksum));
228  OS.EmitValueToAlignment(4);
229  }
230 
231  OS.EmitLabel(FileEnd);
232 
233  ChecksumOffsetsAssigned = true;
234 }
235 
236 // Output checksum table offset of the given file number. It is possible that
237 // not all files have been registered yet, and so the offset cannot be
238 // calculated. In this case a symbol representing the offset is emitted, and
239 // the value of this symbol will be fixed up at a later time.
241  unsigned FileNo) {
242  unsigned Idx = FileNo - 1;
243 
244  if (Idx >= Files.size())
245  Files.resize(Idx + 1);
246 
247  if (ChecksumOffsetsAssigned) {
248  OS.EmitSymbolValue(Files[Idx].ChecksumTableOffset, 4);
249  return;
250  }
251 
252  const MCSymbolRefExpr *SRE =
253  MCSymbolRefExpr::create(Files[Idx].ChecksumTableOffset, OS.getContext());
254 
255  OS.EmitValueImpl(SRE, 4);
256 }
257 
259  size_t Offset = MCCVLines.size();
260  auto I = MCCVLineStartStop.insert(
261  {LineEntry.getFunctionId(), {Offset, Offset + 1}});
262  if (!I.second)
263  I.first->second.second = Offset + 1;
264  MCCVLines.push_back(LineEntry);
265 }
266 
267 std::vector<MCCVLineEntry>
269  std::vector<MCCVLineEntry> FilteredLines;
270  auto I = MCCVLineStartStop.find(FuncId);
271  if (I != MCCVLineStartStop.end()) {
272  MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId);
273  for (size_t Idx = I->second.first, End = I->second.second; Idx != End;
274  ++Idx) {
275  unsigned LocationFuncId = MCCVLines[Idx].getFunctionId();
276  if (LocationFuncId == FuncId) {
277  // This was a .cv_loc directly for FuncId, so record it.
278  FilteredLines.push_back(MCCVLines[Idx]);
279  } else {
280  // Check if the current location is inlined in this function. If it is,
281  // synthesize a statement .cv_loc at the original inlined call site.
282  auto I = SiteInfo->InlinedAtMap.find(LocationFuncId);
283  if (I != SiteInfo->InlinedAtMap.end()) {
284  MCCVFunctionInfo::LineInfo &IA = I->second;
285  // Only add the location if it differs from the previous location.
286  // Large inlined calls will have many .cv_loc entries and we only need
287  // one line table entry in the parent function.
288  if (FilteredLines.empty() ||
289  FilteredLines.back().getFileNum() != IA.File ||
290  FilteredLines.back().getLine() != IA.Line ||
291  FilteredLines.back().getColumn() != IA.Col) {
292  FilteredLines.push_back(MCCVLineEntry(
293  MCCVLines[Idx].getLabel(),
294  MCCVLoc(FuncId, IA.File, IA.Line, IA.Col, false, false)));
295  }
296  }
297  }
298  }
299  }
300  return FilteredLines;
301 }
302 
303 std::pair<size_t, size_t> CodeViewContext::getLineExtent(unsigned FuncId) {
304  auto I = MCCVLineStartStop.find(FuncId);
305  // Return an empty extent if there are no cv_locs for this function id.
306  if (I == MCCVLineStartStop.end())
307  return {~0ULL, 0};
308  return I->second;
309 }
310 
312  if (R <= L)
313  return None;
314  if (L >= MCCVLines.size())
315  return None;
316  return makeArrayRef(&MCCVLines[L], R - L);
317 }
318 
320  unsigned FuncId,
321  const MCSymbol *FuncBegin,
322  const MCSymbol *FuncEnd) {
323  MCContext &Ctx = OS.getContext();
324  MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false),
325  *LineEnd = Ctx.createTempSymbol("linetable_end", false);
326 
327  OS.EmitIntValue(unsigned(DebugSubsectionKind::Lines), 4);
328  OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
329  OS.EmitLabel(LineBegin);
330  OS.EmitCOFFSecRel32(FuncBegin, /*Offset=*/0);
331  OS.EmitCOFFSectionIndex(FuncBegin);
332 
333  // Actual line info.
334  std::vector<MCCVLineEntry> Locs = getFunctionLineEntries(FuncId);
335  bool HaveColumns = any_of(Locs, [](const MCCVLineEntry &LineEntry) {
336  return LineEntry.getColumn() != 0;
337  });
338  OS.EmitIntValue(HaveColumns ? int(LF_HaveColumns) : 0, 2);
339  OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4);
340 
341  for (auto I = Locs.begin(), E = Locs.end(); I != E;) {
342  // Emit a file segment for the run of locations that share a file id.
343  unsigned CurFileNum = I->getFileNum();
344  auto FileSegEnd =
345  std::find_if(I, E, [CurFileNum](const MCCVLineEntry &Loc) {
346  return Loc.getFileNum() != CurFileNum;
347  });
348  unsigned EntryCount = FileSegEnd - I;
349  OS.AddComment(
350  "Segment for file '" +
351  Twine(getStringTableFragment()
352  ->getContents()[Files[CurFileNum - 1].StringTableOffset]) +
353  "' begins");
354  OS.EmitCVFileChecksumOffsetDirective(CurFileNum);
355  OS.EmitIntValue(EntryCount, 4);
356  uint32_t SegmentSize = 12;
357  SegmentSize += 8 * EntryCount;
358  if (HaveColumns)
359  SegmentSize += 4 * EntryCount;
360  OS.EmitIntValue(SegmentSize, 4);
361 
362  for (auto J = I; J != FileSegEnd; ++J) {
363  OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
364  unsigned LineData = J->getLine();
365  if (J->isStmt())
366  LineData |= LineInfo::StatementFlag;
367  OS.EmitIntValue(LineData, 4);
368  }
369  if (HaveColumns) {
370  for (auto J = I; J != FileSegEnd; ++J) {
371  OS.EmitIntValue(J->getColumn(), 2);
372  OS.EmitIntValue(0, 2);
373  }
374  }
375  I = FileSegEnd;
376  }
377  OS.EmitLabel(LineEnd);
378 }
379 
381  if (isUInt<7>(Data)) {
382  Buffer.push_back(Data);
383  return true;
384  }
385 
386  if (isUInt<14>(Data)) {
387  Buffer.push_back((Data >> 8) | 0x80);
388  Buffer.push_back(Data & 0xff);
389  return true;
390  }
391 
392  if (isUInt<29>(Data)) {
393  Buffer.push_back((Data >> 24) | 0xC0);
394  Buffer.push_back((Data >> 16) & 0xff);
395  Buffer.push_back((Data >> 8) & 0xff);
396  Buffer.push_back(Data & 0xff);
397  return true;
398  }
399 
400  return false;
401 }
402 
404  SmallVectorImpl<char> &Buffer) {
405  return compressAnnotation(static_cast<uint32_t>(Annotation), Buffer);
406 }
407 
409  if (Data >> 31)
410  return ((-Data) << 1) | 1;
411  return Data << 1;
412 }
413 
415  unsigned PrimaryFunctionId,
416  unsigned SourceFileId,
417  unsigned SourceLineNum,
418  const MCSymbol *FnStartSym,
419  const MCSymbol *FnEndSym) {
420  // Create and insert a fragment into the current section that will be encoded
421  // later.
422  new MCCVInlineLineTableFragment(PrimaryFunctionId, SourceFileId,
423  SourceLineNum, FnStartSym, FnEndSym,
424  OS.getCurrentSectionOnly());
425 }
426 
428  MCObjectStreamer &OS,
429  ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
430  StringRef FixedSizePortion) {
431  // Create and insert a fragment into the current section that will be encoded
432  // later.
433  new MCCVDefRangeFragment(Ranges, FixedSizePortion,
434  OS.getCurrentSectionOnly());
435 }
436 
437 static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin,
438  const MCSymbol *End) {
439  MCContext &Ctx = Layout.getAssembler().getContext();
441  const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
442  *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
443  const MCExpr *AddrDelta =
444  MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
445  int64_t Result;
446  bool Success = AddrDelta->evaluateKnownAbsolute(Result, Layout);
447  assert(Success && "failed to evaluate label difference as absolute");
448  (void)Success;
449  assert(Result >= 0 && "negative label difference requested");
450  assert(Result < UINT_MAX && "label difference greater than 2GB");
451  return unsigned(Result);
452 }
453 
456  size_t LocBegin;
457  size_t LocEnd;
458  std::tie(LocBegin, LocEnd) = getLineExtent(Frag.SiteFuncId);
459 
460  // Include all child inline call sites in our .cv_loc extent.
461  MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(Frag.SiteFuncId);
462  for (auto &KV : SiteInfo->InlinedAtMap) {
463  unsigned ChildId = KV.first;
464  auto Extent = getLineExtent(ChildId);
465  LocBegin = std::min(LocBegin, Extent.first);
466  LocEnd = std::max(LocEnd, Extent.second);
467  }
468 
469  if (LocBegin >= LocEnd)
470  return;
471  ArrayRef<MCCVLineEntry> Locs = getLinesForExtent(LocBegin, LocEnd);
472  if (Locs.empty())
473  return;
474 
475  // Make an artificial start location using the function start and the inlinee
476  // lines start location information. All deltas start relative to this
477  // location.
478  MCCVLineEntry StartLoc(Frag.getFnStartSym(), MCCVLoc(Locs.front()));
479  StartLoc.setFileNum(Frag.StartFileId);
480  StartLoc.setLine(Frag.StartLineNum);
481  bool HaveOpenRange = false;
482 
483  const MCSymbol *LastLabel = Frag.getFnStartSym();
484  MCCVFunctionInfo::LineInfo LastSourceLoc, CurSourceLoc;
485  LastSourceLoc.File = Frag.StartFileId;
486  LastSourceLoc.Line = Frag.StartLineNum;
487 
488  SmallVectorImpl<char> &Buffer = Frag.getContents();
489  Buffer.clear(); // Clear old contents if we went through relaxation.
490  for (const MCCVLineEntry &Loc : Locs) {
491  // Exit early if our line table would produce an oversized InlineSiteSym
492  // record. Account for the ChangeCodeLength annotation emitted after the
493  // loop ends.
494  constexpr uint32_t InlineSiteSize = 12;
495  constexpr uint32_t AnnotationSize = 8;
496  size_t MaxBufferSize = MaxRecordLength - InlineSiteSize - AnnotationSize;
497  if (Buffer.size() >= MaxBufferSize)
498  break;
499 
500  if (Loc.getFunctionId() == Frag.SiteFuncId) {
501  CurSourceLoc.File = Loc.getFileNum();
502  CurSourceLoc.Line = Loc.getLine();
503  } else {
504  auto I = SiteInfo->InlinedAtMap.find(Loc.getFunctionId());
505  if (I != SiteInfo->InlinedAtMap.end()) {
506  // This .cv_loc is from a child inline call site. Use the source
507  // location of the inlined call site instead of the .cv_loc directive
508  // source location.
509  CurSourceLoc = I->second;
510  } else {
511  // We've hit a cv_loc not attributed to this inline call site. Use this
512  // label to end the PC range.
513  if (HaveOpenRange) {
514  unsigned Length = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
516  compressAnnotation(Length, Buffer);
517  LastLabel = Loc.getLabel();
518  }
519  HaveOpenRange = false;
520  continue;
521  }
522  }
523 
524  // Skip this .cv_loc if we have an open range and this isn't a meaningful
525  // source location update. The current table format does not support column
526  // info, so we can skip updates for those.
527  if (HaveOpenRange && CurSourceLoc.File == LastSourceLoc.File &&
528  CurSourceLoc.Line == LastSourceLoc.Line)
529  continue;
530 
531  HaveOpenRange = true;
532 
533  if (CurSourceLoc.File != LastSourceLoc.File) {
534  unsigned FileOffset = static_cast<const MCConstantExpr *>(
535  Files[CurSourceLoc.File - 1]
536  .ChecksumTableOffset->getVariableValue())
537  ->getValue();
539  compressAnnotation(FileOffset, Buffer);
540  }
541 
542  int LineDelta = CurSourceLoc.Line - LastSourceLoc.Line;
543  unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
544  unsigned CodeDelta = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
545  if (CodeDelta == 0 && LineDelta != 0) {
547  compressAnnotation(EncodedLineDelta, Buffer);
548  } else if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
549  // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
550  // encoded line delta uses 3 or fewer set bits and the code offset fits
551  // in one nibble.
552  unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
554  Buffer);
555  compressAnnotation(Operand, Buffer);
556  } else {
557  // Otherwise use the separate line and code deltas.
558  if (LineDelta != 0) {
560  compressAnnotation(EncodedLineDelta, Buffer);
561  }
563  compressAnnotation(CodeDelta, Buffer);
564  }
565 
566  LastLabel = Loc.getLabel();
567  LastSourceLoc = CurSourceLoc;
568  }
569 
570  assert(HaveOpenRange);
571 
572  unsigned EndSymLength =
573  computeLabelDiff(Layout, LastLabel, Frag.getFnEndSym());
574  unsigned LocAfterLength = ~0U;
575  ArrayRef<MCCVLineEntry> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
576  if (!LocAfter.empty()) {
577  // Only try to compute this difference if we're in the same section.
578  const MCCVLineEntry &Loc = LocAfter[0];
579  if (&Loc.getLabel()->getSection() == &LastLabel->getSection())
580  LocAfterLength = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
581  }
582 
584  compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
585 }
586 
588  MCCVDefRangeFragment &Frag) {
589  MCContext &Ctx = Layout.getAssembler().getContext();
590  SmallVectorImpl<char> &Contents = Frag.getContents();
591  Contents.clear();
593  Fixups.clear();
594  raw_svector_ostream OS(Contents);
595 
596  // Compute all the sizes up front.
597  SmallVector<std::pair<unsigned, unsigned>, 4> GapAndRangeSizes;
598  const MCSymbol *LastLabel = nullptr;
599  for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) {
600  unsigned GapSize =
601  LastLabel ? computeLabelDiff(Layout, LastLabel, Range.first) : 0;
602  unsigned RangeSize = computeLabelDiff(Layout, Range.first, Range.second);
603  GapAndRangeSizes.push_back({GapSize, RangeSize});
604  LastLabel = Range.second;
605  }
606 
607  // Write down each range where the variable is defined.
608  for (size_t I = 0, E = Frag.getRanges().size(); I != E;) {
609  // If the range size of multiple consecutive ranges is under the max,
610  // combine the ranges and emit some gaps.
611  const MCSymbol *RangeBegin = Frag.getRanges()[I].first;
612  unsigned RangeSize = GapAndRangeSizes[I].second;
613  size_t J = I + 1;
614  for (; J != E; ++J) {
615  unsigned GapAndRangeSize = GapAndRangeSizes[J].first + GapAndRangeSizes[J].second;
616  if (RangeSize + GapAndRangeSize > MaxDefRange)
617  break;
618  RangeSize += GapAndRangeSize;
619  }
620  unsigned NumGaps = J - I - 1;
621 
623 
624  unsigned Bias = 0;
625  // We must split the range into chunks of MaxDefRange, this is a fundamental
626  // limitation of the file format.
627  do {
628  uint16_t Chunk = std::min((uint32_t)MaxDefRange, RangeSize);
629 
630  const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(RangeBegin, Ctx);
631  const MCBinaryExpr *BE =
632  MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(Bias, Ctx), Ctx);
633  MCValue Res;
634  BE->evaluateAsRelocatable(Res, &Layout, /*Fixup=*/nullptr);
635 
636  // Each record begins with a 2-byte number indicating how large the record
637  // is.
638  StringRef FixedSizePortion = Frag.getFixedSizePortion();
639  // Our record is a fixed sized prefix and a LocalVariableAddrRange that we
640  // are artificially constructing.
641  size_t RecordSize = FixedSizePortion.size() +
642  sizeof(LocalVariableAddrRange) + 4 * NumGaps;
643  // Write out the record size.
644  LEWriter.write<uint16_t>(RecordSize);
645  // Write out the fixed size prefix.
646  OS << FixedSizePortion;
647  // Make space for a fixup that will eventually have a section relative
648  // relocation pointing at the offset where the variable becomes live.
649  Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_4));
650  LEWriter.write<uint32_t>(0); // Fixup for code start.
651  // Make space for a fixup that will record the section index for the code.
652  Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2));
653  LEWriter.write<uint16_t>(0); // Fixup for section index.
654  // Write down the range's extent.
655  LEWriter.write<uint16_t>(Chunk);
656 
657  // Move on to the next range.
658  Bias += Chunk;
659  RangeSize -= Chunk;
660  } while (RangeSize > 0);
661 
662  // Emit the gaps afterwards.
663  assert((NumGaps == 0 || Bias <= MaxDefRange) &&
664  "large ranges should not have gaps");
665  unsigned GapStartOffset = GapAndRangeSizes[I].second;
666  for (++I; I != J; ++I) {
667  unsigned GapSize, RangeSize;
668  assert(I < GapAndRangeSizes.size());
669  std::tie(GapSize, RangeSize) = GapAndRangeSizes[I];
670  LEWriter.write<uint16_t>(GapStartOffset);
671  LEWriter.write<uint16_t>(GapSize);
672  GapStartOffset += GapSize + RangeSize;
673  }
674  }
675 }
676 
677 //
678 // This is called when an instruction is assembled into the specified section
679 // and if there is information from the last .cv_loc directive that has yet to have
680 // a line entry made for it is made.
681 //
683  CodeViewContext &CVC = MCOS->getContext().getCVContext();
684  if (!CVC.getCVLocSeen())
685  return;
686 
687  // Create a symbol at in the current section for use in the line entry.
688  MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
689  // Set the value of the symbol to use for the MCCVLineEntry.
690  MCOS->EmitLabel(LineSym);
691 
692  // Get the current .loc info saved in the context.
693  const MCCVLoc &CVLoc = CVC.getCurrentCVLoc();
694 
695  // Create a (local) line entry with the symbol and the current .loc info.
696  MCCVLineEntry LineEntry(LineSym, CVLoc);
697 
698  // clear CVLocSeen saying the current .loc info is now used.
699  CVC.clearCVLocSeen();
700 
701  // Add the line entry to this section's entries.
702  CVC.addLineEntry(LineEntry);
703 }
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:152
const NoneType None
Definition: None.h:24
void push_back(const T &Elt)
Definition: SmallVector.h:212
void encodeDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &F)
Definition: MCCodeView.cpp:587
void EmitBytes(StringRef Data) override
Emit the bytes in Data into the output.
ArrayRef< MCCVLineEntry > getLinesForExtent(size_t L, size_t R)
Definition: MCCodeView.cpp:311
Instances of this class represent the information from a .cv_loc directive.
Definition: MCCodeView.h:32
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void emitLineTableForFunction(MCObjectStreamer &OS, unsigned FuncId, const MCSymbol *FuncBegin, const MCSymbol *FuncEnd)
Emits a line table substream.
Definition: MCCodeView.cpp:319
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:313
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:145
This represents an "assembler immediate".
Definition: MCValue.h:40
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
SmallString< 8 > & getContents()
Definition: MCFragment.h:623
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
std::pair< StringRef, unsigned > addToStringTable(StringRef S)
Add something to the string table.
Definition: MCCodeView.cpp:140
static void Make(MCObjectStreamer *MCOS)
Definition: MCCodeView.cpp:682
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:489
void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override
This implements the CodeView &#39;.cv_filechecksumoffset&#39; assembler directive.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
StringRef getFixedSizePortion() const
Definition: MCFragment.h:656
DenseMap< unsigned, LineInfo > InlinedAtMap
Map from inlined call site id to the inlined at location to use for that call site.
Definition: MCCodeView.h:138
bool addFile(MCStreamer &OS, unsigned FileNumber, StringRef Filename, ArrayRef< uint8_t > ChecksumBytes, uint8_t ChecksumKind)
Definition: MCCodeView.cpp:47
static bool compressAnnotation(uint32_t Data, SmallVectorImpl< char > &Buffer)
Definition: MCCodeView.cpp:380
void emitInlineLineTableForFunction(MCObjectStreamer &OS, unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, const MCSymbol *FnStartSym, const MCSymbol *FnEndSym)
Definition: MCCodeView.cpp:414
MCContext & getContext() const
Definition: MCAssembler.h:273
MCContext & getContext() const
Definition: MCStreamer.h:246
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:29
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:165
static uint32_t encodeSignedNumber(uint32_t Data)
Definition: MCCodeView.cpp:408
A four-byte section relative fixup.
Definition: MCFixup.h:42
Context object for machine code objects.
Definition: MCContext.h:61
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition: MCStreamer.h:294
void emitDefRange(MCObjectStreamer &OS, ArrayRef< std::pair< const MCSymbol *, const MCSymbol *>> Ranges, StringRef FixedSizePortion)
Definition: MCCodeView.cpp:427
A two-byte section relative fixup.
Definition: MCFixup.h:41
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:604
Streaming object file generation interface.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
bool isInlinedCallSite() const
Returns true if this represents an inlined call site, meaning ParentFuncIdPlusOne is neither zero nor...
Definition: MCCodeView.h:146
unsigned getParentFuncId() const
Definition: MCCodeView.h:151
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:51
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:451
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:183
virtual void EmitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers...
Definition: MCStreamer.cpp:110
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition: MCExpr.cpp:148
const MCCVLoc & getCurrentCVLoc()
Definition: MCCodeView.h:200
void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) override
Emit the absolute difference between two symbols if possible.
void encodeInlineLineTable(MCAsmLayout &Layout, MCCVInlineLineTableFragment &F)
Encodes the binary annotations once we have a layout.
Definition: MCCodeView.cpp:454
Streaming machine code generation interface.
Definition: MCStreamer.h:181
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:441
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:215
void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc()) override
Emit a label for Symbol into the current section.
void write(ArrayRef< value_type > Vals)
Definition: EndianStream.h:30
void insert(MCFragment *F)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:208
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:821
void addLineEntry(const MCCVLineEntry &LineEntry)
Add a line entry.
Definition: MCCodeView.cpp:258
static const unsigned End
void setFileNum(unsigned fileNum)
Set the FileNum of this MCCVLoc.
Definition: MCCodeView.h:68
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:842
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Definition: StringExtras.h:43
Binary assembler expressions.
Definition: MCExpr.h:407
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:82
Fragment representing the .cv_def_range directive.
Definition: MCFragment.h:634
MCCVFunctionInfo * getCVFunctionInfo(unsigned FuncId)
Retreive the function info if this is a valid function id, or nullptr.
Definition: MCCodeView.cpp:79
void setLine(unsigned line)
Set the Line of this MCCVLoc.
Definition: MCCodeView.h:71
void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0) override
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin, const MCSymbol *End)
Definition: MCCodeView.cpp:437
unsigned ParentFuncIdPlusOne
If this represents an inlined call site, then ParentFuncIdPlusOne will be the parent function id plus...
Definition: MCCodeView.h:118
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:862
unsigned getFileNum() const
Get the FileNum of this MCCVLoc.
Definition: MCCodeView.h:54
const MCSymbol * getFnEndSym() const
Definition: MCFragment.h:621
MCSection * getCurrentSectionOnly() const
Definition: MCStreamer.h:328
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:267
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:396
Fragment representing the binary annotations produced by the .cv_inline_linetable directive...
Definition: MCFragment.h:596
const MCSymbol * getFnStartSym() const
Definition: MCFragment.h:620
#define Success
bool recordFunctionId(unsigned FuncId)
Records the function id of a normal function.
Definition: MCCodeView.cpp:87
static void addToStringTable(raw_ostream &Out, StringRef ArcName, const NewArchiveMember &M, bool Thin)
std::pair< size_t, size_t > getLineExtent(unsigned FuncId)
Definition: MCCodeView.cpp:303
bool recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc, unsigned IAFile, unsigned IALine, unsigned IACol)
Records the function id of an inlined call site.
Definition: MCCodeView.cpp:100
void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override
Emit an assignment of Value to Symbol.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isValidFileNumber(unsigned FileNumber) const
This is a valid number for use with .cv_loc if we&#39;ve already seen a .cv_file for it.
Definition: MCCodeView.cpp:40
void emitStringTable(MCObjectStreamer &OS)
Emits the string table substream.
Definition: MCCodeView.cpp:163
void emitFileChecksumOffset(MCObjectStreamer &OS, unsigned FileNo)
Emits the offset into the checksum table of the given file number.
Definition: MCCodeView.cpp:240
void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc()) override
Emit the expression Value into the output as a native integer of the given Size bytes.
Instances of this class represent the line information for the CodeView line table entries...
Definition: MCCodeView.h:88
CodeViewContext & getCVContext()
Definition: MCContext.cpp:563
Fragment for data and encoded instructions.
Definition: MCFragment.h:226
virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset)
Emits a COFF section relative relocation.
Definition: MCStreamer.cpp:799
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const MCSymbol * getLabel() const
Definition: MCCodeView.h:100
ArrayRef< std::pair< const MCSymbol *, const MCSymbol * > > getRanges() const
Definition: MCFragment.h:652
unsigned getColumn() const
Get the Column of this MCCVLoc.
Definition: MCCodeView.h:60
std::vector< MCCVLineEntry > getFunctionLineEntries(unsigned FuncId)
Definition: MCCodeView.cpp:268
Subtraction.
Definition: MCExpr.h:431
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Information describing a function or inlined call site introduced by .cv_func_id or ...
Definition: MCCodeView.h:112
unsigned getFunctionId() const
Definition: MCCodeView.h:51
void emitFileChecksums(MCObjectStreamer &OS)
Emits the file checksum substream.
Definition: MCCodeView.cpp:185
virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol)
Emits a COFF section index.
Definition: MCStreamer.cpp:796
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:159
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
Holds state from .cv_file and .cv_loc directives for later emission.
Definition: MCCodeView.h:158