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