Coverage Report

Created: 2019-07-24 05:18

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