xref: /llvm-project/llvm/lib/MC/MCCodeView.cpp (revision 3fa5b52714b3dadbc5fddfc4ae1e7c423a652962)
1 //===- MCCodeView.h - Machine Code CodeView support -------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Holds state from .cv_file and .cv_loc directives for later emission.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/MC/MCCodeView.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/DebugInfo/CodeView/CodeView.h"
17 #include "llvm/DebugInfo/CodeView/Line.h"
18 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCObjectStreamer.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/EndianStream.h"
24 
25 using namespace llvm;
26 using namespace llvm::codeview;
27 
28 CodeViewContext::~CodeViewContext() {
29   // If someone inserted strings into the string table but never actually
30   // emitted them somewhere, clean up the fragment.
31   if (!InsertedStrTabFragment && StrTabFragment)
32     StrTabFragment->destroy();
33 }
34 
35 /// This is a valid number for use with .cv_loc if we've already seen a .cv_file
36 /// for it.
37 bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const {
38   unsigned Idx = FileNumber - 1;
39   if (Idx < Files.size())
40     return Files[Idx].Assigned;
41   return false;
42 }
43 
44 bool CodeViewContext::addFile(MCStreamer &OS, unsigned FileNumber,
45                               StringRef Filename,
46                               ArrayRef<uint8_t> ChecksumBytes,
47                               uint8_t ChecksumKind) {
48   assert(FileNumber > 0);
49   auto FilenameOffset = addToStringTable(Filename);
50   Filename = FilenameOffset.first;
51   unsigned Idx = FileNumber - 1;
52   if (Idx >= Files.size())
53     Files.resize(Idx + 1);
54 
55   if (Filename.empty())
56     Filename = "<stdin>";
57 
58   if (Files[Idx].Assigned)
59     return false;
60 
61   FilenameOffset = addToStringTable(Filename);
62   Filename = FilenameOffset.first;
63   unsigned Offset = FilenameOffset.second;
64 
65   auto ChecksumOffsetSymbol =
66       OS.getContext().createTempSymbol("checksum_offset", false);
67   Files[Idx].StringTableOffset = Offset;
68   Files[Idx].ChecksumTableOffset = ChecksumOffsetSymbol;
69   Files[Idx].Assigned = true;
70   Files[Idx].Checksum = ChecksumBytes;
71   Files[Idx].ChecksumKind = ChecksumKind;
72 
73   return true;
74 }
75 
76 MCCVFunctionInfo *CodeViewContext::getCVFunctionInfo(unsigned FuncId) {
77   if (FuncId >= Functions.size())
78     return nullptr;
79   if (Functions[FuncId].isUnallocatedFunctionInfo())
80     return nullptr;
81   return &Functions[FuncId];
82 }
83 
84 bool CodeViewContext::recordFunctionId(unsigned FuncId) {
85   if (FuncId >= Functions.size())
86     Functions.resize(FuncId + 1);
87 
88   // Return false if this function info was already allocated.
89   if (!Functions[FuncId].isUnallocatedFunctionInfo())
90     return false;
91 
92   // Mark this as an allocated normal function, and leave the rest alone.
93   Functions[FuncId].ParentFuncIdPlusOne = MCCVFunctionInfo::FunctionSentinel;
94   return true;
95 }
96 
97 bool CodeViewContext::recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc,
98                                               unsigned IAFile, unsigned IALine,
99                                               unsigned IACol) {
100   if (FuncId >= Functions.size())
101     Functions.resize(FuncId + 1);
102 
103   // Return false if this function info was already allocated.
104   if (!Functions[FuncId].isUnallocatedFunctionInfo())
105     return false;
106 
107   MCCVFunctionInfo::LineInfo InlinedAt;
108   InlinedAt.File = IAFile;
109   InlinedAt.Line = IALine;
110   InlinedAt.Col = IACol;
111 
112   // Mark this as an inlined call site and record call site line info.
113   MCCVFunctionInfo *Info = &Functions[FuncId];
114   Info->ParentFuncIdPlusOne = IAFunc + 1;
115   Info->InlinedAt = InlinedAt;
116 
117   // Walk up the call chain adding this function id to the InlinedAtMap of all
118   // transitive callers until we hit a real function.
119   while (Info->isInlinedCallSite()) {
120     InlinedAt = Info->InlinedAt;
121     Info = getCVFunctionInfo(Info->getParentFuncId());
122     Info->InlinedAtMap[FuncId] = InlinedAt;
123   }
124 
125   return true;
126 }
127 
128 void CodeViewContext::recordCVLoc(MCContext &Ctx, const MCSymbol *Label,
129                                   unsigned FunctionId, unsigned FileNo,
130                                   unsigned Line, unsigned Column,
131                                   bool PrologueEnd, bool IsStmt) {
132   addLineEntry(MCCVLoc{
133       Label, FunctionId, FileNo, Line, Column, PrologueEnd, IsStmt});
134 }
135 
136 MCDataFragment *CodeViewContext::getStringTableFragment() {
137   if (!StrTabFragment) {
138     StrTabFragment = MCCtx->allocFragment<MCDataFragment>();
139     // Start a new string table out with a null byte.
140     StrTabFragment->appendContents(1, '\0');
141   }
142   return StrTabFragment;
143 }
144 
145 std::pair<StringRef, unsigned> CodeViewContext::addToStringTable(StringRef S) {
146   SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents();
147   auto Insertion =
148       StringTable.insert(std::make_pair(S, unsigned(Contents.size())));
149   // Return the string from the table, since it is stable.
150   std::pair<StringRef, unsigned> Ret =
151       std::make_pair(Insertion.first->first(), Insertion.first->second);
152   if (Insertion.second) {
153     // The string map key is always null terminated.
154     StrTabFragment->appendContents(
155         ArrayRef(Ret.first.begin(), Ret.first.end() + 1));
156   }
157   return Ret;
158 }
159 
160 unsigned CodeViewContext::getStringTableOffset(StringRef S) {
161   // A string table offset of zero is always the empty string.
162   if (S.empty())
163     return 0;
164   auto I = StringTable.find(S);
165   assert(I != StringTable.end());
166   return I->second;
167 }
168 
169 void CodeViewContext::emitStringTable(MCObjectStreamer &OS) {
170   MCContext &Ctx = OS.getContext();
171   MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false),
172            *StringEnd = Ctx.createTempSymbol("strtab_end", false);
173 
174   OS.emitInt32(uint32_t(DebugSubsectionKind::StringTable));
175   OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
176   OS.emitLabel(StringBegin);
177 
178   // Put the string table data fragment here, if we haven't already put it
179   // somewhere else. If somebody wants two string tables in their .s file, one
180   // will just be empty.
181   if (!InsertedStrTabFragment) {
182     OS.insert(getStringTableFragment());
183     InsertedStrTabFragment = true;
184   }
185 
186   OS.emitValueToAlignment(Align(4), 0);
187 
188   OS.emitLabel(StringEnd);
189 }
190 
191 void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) {
192   // Do nothing if there are no file checksums. Microsoft's linker rejects empty
193   // CodeView substreams.
194   if (Files.empty())
195     return;
196 
197   MCContext &Ctx = OS.getContext();
198   MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false),
199            *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
200 
201   OS.emitInt32(uint32_t(DebugSubsectionKind::FileChecksums));
202   OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
203   OS.emitLabel(FileBegin);
204 
205   unsigned CurrentOffset = 0;
206 
207   // Emit an array of FileChecksum entries. We index into this table using the
208   // user-provided file number.  Each entry may be a variable number of bytes
209   // determined by the checksum kind and size.
210   for (auto File : Files) {
211     OS.emitAssignment(File.ChecksumTableOffset,
212                       MCConstantExpr::create(CurrentOffset, Ctx));
213     CurrentOffset += 4; // String table offset.
214     if (!File.ChecksumKind) {
215       CurrentOffset +=
216           4; // One byte each for checksum size and kind, then align to 4 bytes.
217     } else {
218       CurrentOffset += 2; // One byte each for checksum size and kind.
219       CurrentOffset += File.Checksum.size();
220       CurrentOffset = alignTo(CurrentOffset, 4);
221     }
222 
223     OS.emitInt32(File.StringTableOffset);
224 
225     if (!File.ChecksumKind) {
226       // There is no checksum.  Therefore zero the next two fields and align
227       // back to 4 bytes.
228       OS.emitInt32(0);
229       continue;
230     }
231     OS.emitInt8(static_cast<uint8_t>(File.Checksum.size()));
232     OS.emitInt8(File.ChecksumKind);
233     OS.emitBytes(toStringRef(File.Checksum));
234     OS.emitValueToAlignment(Align(4));
235   }
236 
237   OS.emitLabel(FileEnd);
238 
239   ChecksumOffsetsAssigned = true;
240 }
241 
242 // Output checksum table offset of the given file number.  It is possible that
243 // not all files have been registered yet, and so the offset cannot be
244 // calculated.  In this case a symbol representing the offset is emitted, and
245 // the value of this symbol will be fixed up at a later time.
246 void CodeViewContext::emitFileChecksumOffset(MCObjectStreamer &OS,
247                                              unsigned FileNo) {
248   unsigned Idx = FileNo - 1;
249 
250   if (Idx >= Files.size())
251     Files.resize(Idx + 1);
252 
253   if (ChecksumOffsetsAssigned) {
254     OS.emitSymbolValue(Files[Idx].ChecksumTableOffset, 4);
255     return;
256   }
257 
258   const MCSymbolRefExpr *SRE =
259       MCSymbolRefExpr::create(Files[Idx].ChecksumTableOffset, OS.getContext());
260 
261   OS.emitValueImpl(SRE, 4);
262 }
263 
264 void CodeViewContext::addLineEntry(const MCCVLoc &LineEntry) {
265   size_t Offset = MCCVLines.size();
266   auto I = MCCVLineStartStop.insert(
267       {LineEntry.getFunctionId(), {Offset, Offset + 1}});
268   if (!I.second)
269     I.first->second.second = Offset + 1;
270   MCCVLines.push_back(LineEntry);
271 }
272 
273 std::vector<MCCVLoc>
274 CodeViewContext::getFunctionLineEntries(unsigned FuncId) {
275   std::vector<MCCVLoc> FilteredLines;
276   size_t LocBegin;
277   size_t LocEnd;
278   std::tie(LocBegin, LocEnd) = getLineExtentIncludingInlinees(FuncId);
279   if (LocBegin >= LocEnd) {
280     return FilteredLines;
281   }
282 
283   MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId);
284   for (size_t Idx = LocBegin; Idx != LocEnd; ++Idx) {
285     unsigned LocationFuncId = MCCVLines[Idx].getFunctionId();
286     if (LocationFuncId == FuncId) {
287       // This was a .cv_loc directly for FuncId, so record it.
288       FilteredLines.push_back(MCCVLines[Idx]);
289     } else {
290       // Check if the current location is inlined in this function. If it is,
291       // synthesize a statement .cv_loc at the original inlined call site.
292       auto I = SiteInfo->InlinedAtMap.find(LocationFuncId);
293       if (I != SiteInfo->InlinedAtMap.end()) {
294         MCCVFunctionInfo::LineInfo &IA = I->second;
295         // Only add the location if it differs from the previous location.
296         // Large inlined calls will have many .cv_loc entries and we only need
297         // one line table entry in the parent function.
298         if (FilteredLines.empty() ||
299             FilteredLines.back().getFileNum() != IA.File ||
300             FilteredLines.back().getLine() != IA.Line ||
301             FilteredLines.back().getColumn() != IA.Col) {
302           FilteredLines.push_back(MCCVLoc(MCCVLines[Idx].getLabel(), FuncId,
303                                           IA.File, IA.Line, IA.Col, false,
304                                           false));
305         }
306       }
307     }
308   }
309   return FilteredLines;
310 }
311 
312 std::pair<size_t, size_t> CodeViewContext::getLineExtent(unsigned FuncId) {
313   auto I = MCCVLineStartStop.find(FuncId);
314   // Return an empty extent if there are no cv_locs for this function id.
315   if (I == MCCVLineStartStop.end())
316     return {~0ULL, 0};
317   return I->second;
318 }
319 
320 std::pair<size_t, size_t>
321 CodeViewContext::getLineExtentIncludingInlinees(unsigned FuncId) {
322   size_t LocBegin;
323   size_t LocEnd;
324   std::tie(LocBegin, LocEnd) = getLineExtent(FuncId);
325 
326   // Include all child inline call sites in our extent.
327   MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId);
328   if (SiteInfo) {
329     for (auto &KV : SiteInfo->InlinedAtMap) {
330       unsigned ChildId = KV.first;
331       auto Extent = getLineExtent(ChildId);
332       LocBegin = std::min(LocBegin, Extent.first);
333       LocEnd = std::max(LocEnd, Extent.second);
334     }
335   }
336 
337   return {LocBegin, LocEnd};
338 }
339 
340 ArrayRef<MCCVLoc> CodeViewContext::getLinesForExtent(size_t L, size_t R) {
341   if (R <= L)
342     return {};
343   if (L >= MCCVLines.size())
344     return {};
345   return ArrayRef(&MCCVLines[L], R - L);
346 }
347 
348 void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS,
349                                                unsigned FuncId,
350                                                const MCSymbol *FuncBegin,
351                                                const MCSymbol *FuncEnd) {
352   MCContext &Ctx = OS.getContext();
353   MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false),
354            *LineEnd = Ctx.createTempSymbol("linetable_end", false);
355 
356   OS.emitInt32(uint32_t(DebugSubsectionKind::Lines));
357   OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
358   OS.emitLabel(LineBegin);
359   OS.emitCOFFSecRel32(FuncBegin, /*Offset=*/0);
360   OS.emitCOFFSectionIndex(FuncBegin);
361 
362   // Actual line info.
363   std::vector<MCCVLoc> Locs = getFunctionLineEntries(FuncId);
364   bool HaveColumns = any_of(Locs, [](const MCCVLoc &LineEntry) {
365     return LineEntry.getColumn() != 0;
366   });
367   OS.emitInt16(HaveColumns ? int(LF_HaveColumns) : 0);
368   OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4);
369 
370   for (auto I = Locs.begin(), E = Locs.end(); I != E;) {
371     // Emit a file segment for the run of locations that share a file id.
372     unsigned CurFileNum = I->getFileNum();
373     auto FileSegEnd =
374         std::find_if(I, E, [CurFileNum](const MCCVLoc &Loc) {
375           return Loc.getFileNum() != CurFileNum;
376         });
377     unsigned EntryCount = FileSegEnd - I;
378     OS.AddComment(
379         "Segment for file '" +
380         Twine(getStringTableFragment()
381                   ->getContents()[Files[CurFileNum - 1].StringTableOffset]) +
382         "' begins");
383     OS.emitCVFileChecksumOffsetDirective(CurFileNum);
384     OS.emitInt32(EntryCount);
385     uint32_t SegmentSize = 12;
386     SegmentSize += 8 * EntryCount;
387     if (HaveColumns)
388       SegmentSize += 4 * EntryCount;
389     OS.emitInt32(SegmentSize);
390 
391     for (auto J = I; J != FileSegEnd; ++J) {
392       OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
393       unsigned LineData = J->getLine();
394       if (J->isStmt())
395         LineData |= LineInfo::StatementFlag;
396       OS.emitInt32(LineData);
397     }
398     if (HaveColumns) {
399       for (auto J = I; J != FileSegEnd; ++J) {
400         OS.emitInt16(J->getColumn());
401         OS.emitInt16(0);
402       }
403     }
404     I = FileSegEnd;
405   }
406   OS.emitLabel(LineEnd);
407 }
408 
409 static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) {
410   if (isUInt<7>(Data)) {
411     Buffer.push_back(Data);
412     return true;
413   }
414 
415   if (isUInt<14>(Data)) {
416     Buffer.push_back((Data >> 8) | 0x80);
417     Buffer.push_back(Data & 0xff);
418     return true;
419   }
420 
421   if (isUInt<29>(Data)) {
422     Buffer.push_back((Data >> 24) | 0xC0);
423     Buffer.push_back((Data >> 16) & 0xff);
424     Buffer.push_back((Data >> 8) & 0xff);
425     Buffer.push_back(Data & 0xff);
426     return true;
427   }
428 
429   return false;
430 }
431 
432 static bool compressAnnotation(BinaryAnnotationsOpCode Annotation,
433                                SmallVectorImpl<char> &Buffer) {
434   return compressAnnotation(static_cast<uint32_t>(Annotation), Buffer);
435 }
436 
437 static uint32_t encodeSignedNumber(uint32_t Data) {
438   if (Data >> 31)
439     return ((-Data) << 1) | 1;
440   return Data << 1;
441 }
442 
443 void CodeViewContext::emitInlineLineTableForFunction(MCObjectStreamer &OS,
444                                                      unsigned PrimaryFunctionId,
445                                                      unsigned SourceFileId,
446                                                      unsigned SourceLineNum,
447                                                      const MCSymbol *FnStartSym,
448                                                      const MCSymbol *FnEndSym) {
449   // Create and insert a fragment into the current section that will be encoded
450   // later.
451   auto *F = MCCtx->allocFragment<MCCVInlineLineTableFragment>(
452       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
453   OS.insert(F);
454 }
455 
456 MCFragment *CodeViewContext::emitDefRange(
457     MCObjectStreamer &OS,
458     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
459     StringRef FixedSizePortion) {
460   // Create and insert a fragment into the current section that will be encoded
461   // later.
462   auto *F =
463       MCCtx->allocFragment<MCCVDefRangeFragment>(Ranges, FixedSizePortion);
464   OS.insert(F);
465   return F;
466 }
467 
468 static unsigned computeLabelDiff(const MCAssembler &Asm, const MCSymbol *Begin,
469                                  const MCSymbol *End) {
470   MCContext &Ctx = Asm.getContext();
471   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
472   const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
473                *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
474   const MCExpr *AddrDelta =
475       MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
476   int64_t Result;
477   bool Success = AddrDelta->evaluateKnownAbsolute(Result, Asm);
478   assert(Success && "failed to evaluate label difference as absolute");
479   (void)Success;
480   assert(Result >= 0 && "negative label difference requested");
481   assert(Result < UINT_MAX && "label difference greater than 2GB");
482   return unsigned(Result);
483 }
484 
485 void CodeViewContext::encodeInlineLineTable(const MCAssembler &Asm,
486                                             MCCVInlineLineTableFragment &Frag) {
487   size_t LocBegin;
488   size_t LocEnd;
489   std::tie(LocBegin, LocEnd) = getLineExtentIncludingInlinees(Frag.SiteFuncId);
490 
491   if (LocBegin >= LocEnd)
492     return;
493   ArrayRef<MCCVLoc> Locs = getLinesForExtent(LocBegin, LocEnd);
494   if (Locs.empty())
495     return;
496 
497   // Check that the locations are all in the same section.
498 #ifndef NDEBUG
499   const MCSection *FirstSec = &Locs.front().getLabel()->getSection();
500   for (const MCCVLoc &Loc : Locs) {
501     if (&Loc.getLabel()->getSection() != FirstSec) {
502       errs() << ".cv_loc " << Loc.getFunctionId() << ' ' << Loc.getFileNum()
503              << ' ' << Loc.getLine() << ' ' << Loc.getColumn()
504              << " is in the wrong section\n";
505       llvm_unreachable(".cv_loc crosses sections");
506     }
507   }
508 #endif
509 
510   // Make an artificial start location using the function start and the inlinee
511   // lines start location information. All deltas start relative to this
512   // location.
513   MCCVLoc StartLoc = Locs.front();
514   StartLoc.setLabel(Frag.getFnStartSym());
515   StartLoc.setFileNum(Frag.StartFileId);
516   StartLoc.setLine(Frag.StartLineNum);
517   bool HaveOpenRange = false;
518 
519   const MCSymbol *LastLabel = Frag.getFnStartSym();
520   MCCVFunctionInfo::LineInfo LastSourceLoc, CurSourceLoc;
521   LastSourceLoc.File = Frag.StartFileId;
522   LastSourceLoc.Line = Frag.StartLineNum;
523 
524   MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(Frag.SiteFuncId);
525 
526   SmallVectorImpl<char> &Buffer = Frag.getContents();
527   Buffer.clear(); // Clear old contents if we went through relaxation.
528   for (const MCCVLoc &Loc : Locs) {
529     // Exit early if our line table would produce an oversized InlineSiteSym
530     // record. Account for the ChangeCodeLength annotation emitted after the
531     // loop ends.
532     constexpr uint32_t InlineSiteSize = 12;
533     constexpr uint32_t AnnotationSize = 8;
534     size_t MaxBufferSize = MaxRecordLength - InlineSiteSize - AnnotationSize;
535     if (Buffer.size() >= MaxBufferSize)
536       break;
537 
538     if (Loc.getFunctionId() == Frag.SiteFuncId) {
539       CurSourceLoc.File = Loc.getFileNum();
540       CurSourceLoc.Line = Loc.getLine();
541     } else {
542       auto I = SiteInfo->InlinedAtMap.find(Loc.getFunctionId());
543       if (I != SiteInfo->InlinedAtMap.end()) {
544         // This .cv_loc is from a child inline call site. Use the source
545         // location of the inlined call site instead of the .cv_loc directive
546         // source location.
547         CurSourceLoc = I->second;
548       } else {
549         // We've hit a cv_loc not attributed to this inline call site. Use this
550         // label to end the PC range.
551         if (HaveOpenRange) {
552           unsigned Length = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
553           compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
554           compressAnnotation(Length, Buffer);
555           LastLabel = Loc.getLabel();
556         }
557         HaveOpenRange = false;
558         continue;
559       }
560     }
561 
562     // Skip this .cv_loc if we have an open range and this isn't a meaningful
563     // source location update. The current table format does not support column
564     // info, so we can skip updates for those.
565     if (HaveOpenRange && CurSourceLoc.File == LastSourceLoc.File &&
566         CurSourceLoc.Line == LastSourceLoc.Line)
567       continue;
568 
569     HaveOpenRange = true;
570 
571     if (CurSourceLoc.File != LastSourceLoc.File) {
572       unsigned FileOffset = static_cast<const MCConstantExpr *>(
573                                 Files[CurSourceLoc.File - 1]
574                                     .ChecksumTableOffset->getVariableValue())
575                                 ->getValue();
576       compressAnnotation(BinaryAnnotationsOpCode::ChangeFile, Buffer);
577       compressAnnotation(FileOffset, Buffer);
578     }
579 
580     int LineDelta = CurSourceLoc.Line - LastSourceLoc.Line;
581     unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
582     unsigned CodeDelta = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
583     if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
584       // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
585       // encoded line delta uses 3 or fewer set bits and the code offset fits
586       // in one nibble.
587       unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
588       compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset,
589                          Buffer);
590       compressAnnotation(Operand, Buffer);
591     } else {
592       // Otherwise use the separate line and code deltas.
593       if (LineDelta != 0) {
594         compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
595         compressAnnotation(EncodedLineDelta, Buffer);
596       }
597       compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer);
598       compressAnnotation(CodeDelta, Buffer);
599     }
600 
601     LastLabel = Loc.getLabel();
602     LastSourceLoc = CurSourceLoc;
603   }
604 
605   assert(HaveOpenRange);
606 
607   unsigned EndSymLength =
608       computeLabelDiff(Asm, LastLabel, Frag.getFnEndSym());
609   unsigned LocAfterLength = ~0U;
610   ArrayRef<MCCVLoc> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
611   if (!LocAfter.empty()) {
612     // Only try to compute this difference if we're in the same section.
613     const MCCVLoc &Loc = LocAfter[0];
614     if (&Loc.getLabel()->getSection() == &LastLabel->getSection())
615       LocAfterLength = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
616   }
617 
618   compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
619   compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
620 }
621 
622 void CodeViewContext::encodeDefRange(const MCAssembler &Asm,
623                                      MCCVDefRangeFragment &Frag) {
624   MCContext &Ctx = Asm.getContext();
625   SmallVectorImpl<char> &Contents = Frag.getContents();
626   Contents.clear();
627   SmallVectorImpl<MCFixup> &Fixups = Frag.getFixups();
628   Fixups.clear();
629   raw_svector_ostream OS(Contents);
630 
631   // Compute all the sizes up front.
632   SmallVector<std::pair<unsigned, unsigned>, 4> GapAndRangeSizes;
633   const MCSymbol *LastLabel = nullptr;
634   for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) {
635     unsigned GapSize =
636         LastLabel ? computeLabelDiff(Asm, LastLabel, Range.first) : 0;
637     unsigned RangeSize = computeLabelDiff(Asm, Range.first, Range.second);
638     GapAndRangeSizes.push_back({GapSize, RangeSize});
639     LastLabel = Range.second;
640   }
641 
642   // Write down each range where the variable is defined.
643   for (size_t I = 0, E = Frag.getRanges().size(); I != E;) {
644     // If the range size of multiple consecutive ranges is under the max,
645     // combine the ranges and emit some gaps.
646     const MCSymbol *RangeBegin = Frag.getRanges()[I].first;
647     unsigned RangeSize = GapAndRangeSizes[I].second;
648     size_t J = I + 1;
649     for (; J != E; ++J) {
650       unsigned GapAndRangeSize = GapAndRangeSizes[J].first + GapAndRangeSizes[J].second;
651       if (RangeSize + GapAndRangeSize > MaxDefRange)
652         break;
653       RangeSize += GapAndRangeSize;
654     }
655     unsigned NumGaps = J - I - 1;
656 
657     support::endian::Writer LEWriter(OS, llvm::endianness::little);
658 
659     unsigned Bias = 0;
660     // We must split the range into chunks of MaxDefRange, this is a fundamental
661     // limitation of the file format.
662     do {
663       uint16_t Chunk = std::min((uint32_t)MaxDefRange, RangeSize);
664 
665       const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(RangeBegin, Ctx);
666       const MCBinaryExpr *BE =
667           MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(Bias, Ctx), Ctx);
668 
669       // Each record begins with a 2-byte number indicating how large the record
670       // is.
671       StringRef FixedSizePortion = Frag.getFixedSizePortion();
672       // Our record is a fixed sized prefix and a LocalVariableAddrRange that we
673       // are artificially constructing.
674       size_t RecordSize = FixedSizePortion.size() +
675                           sizeof(LocalVariableAddrRange) + 4 * NumGaps;
676       // Write out the record size.
677       LEWriter.write<uint16_t>(RecordSize);
678       // Write out the fixed size prefix.
679       OS << FixedSizePortion;
680       // Make space for a fixup that will eventually have a section relative
681       // relocation pointing at the offset where the variable becomes live.
682       Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_4));
683       LEWriter.write<uint32_t>(0); // Fixup for code start.
684       // Make space for a fixup that will record the section index for the code.
685       Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2));
686       LEWriter.write<uint16_t>(0); // Fixup for section index.
687       // Write down the range's extent.
688       LEWriter.write<uint16_t>(Chunk);
689 
690       // Move on to the next range.
691       Bias += Chunk;
692       RangeSize -= Chunk;
693     } while (RangeSize > 0);
694 
695     // Emit the gaps afterwards.
696     assert((NumGaps == 0 || Bias <= MaxDefRange) &&
697            "large ranges should not have gaps");
698     unsigned GapStartOffset = GapAndRangeSizes[I].second;
699     for (++I; I != J; ++I) {
700       unsigned GapSize, RangeSize;
701       assert(I < GapAndRangeSizes.size());
702       std::tie(GapSize, RangeSize) = GapAndRangeSizes[I];
703       LEWriter.write<uint16_t>(GapStartOffset);
704       LEWriter.write<uint16_t>(GapSize);
705       GapStartOffset += GapSize + RangeSize;
706     }
707   }
708 }
709