1//===-- SourcePrinter.cpp - source interleaving utilities ----------------===//
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// This file implements the LiveElementPrinter and SourcePrinter classes to
10// keep track of DWARF info as the current address is updated, and print out the
11// source file line and variable or inlined function liveness as needed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SourcePrinter.h"
16#include "llvm-objdump.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
19#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
20#include "llvm/Demangle/Demangle.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/FormatVariadic.h"
23#include "llvm/Support/Path.h"
24
25#define DEBUG_TYPE "objdump"
26
27namespace llvm {
28namespace objdump {
29
30static bool sourceFileExists(StringRef Path) {
31 if (sys::fs::exists(Path) && !sys::fs::is_directory(Path))
32 return true;
33
34 return false;
35}
36
37static void normalizeSourcePath(SmallVectorImpl<char> &Path) {
38 sys::path::native(path&: Path);
39 sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true);
40}
41
42static std::optional<std::string> trySourcePath(StringRef Path) {
43 SmallString<256> Normalized(Path);
44 normalizeSourcePath(Path&: Normalized);
45 if (sourceFileExists(Path: Normalized))
46 return std::string(Normalized);
47 return std::nullopt;
48}
49
50static std::optional<std::string>
51searchSourceWithDirs(StringRef FileName, ArrayRef<StringRef> SearchDirs,
52 bool TryLiteralFirst) {
53 if (TryLiteralFirst)
54 if (auto Path = trySourcePath(Path: FileName))
55 return Path;
56
57 StringRef PathSuffix = sys::path::relative_path(path: FileName);
58 StringRef BaseName = sys::path::filename(path: FileName);
59 for (StringRef Dir : SearchDirs) {
60 SmallString<256> Candidate(Dir);
61 sys::path::append(path&: Candidate, a: PathSuffix);
62 if (auto Path = trySourcePath(Path: Candidate))
63 return Path;
64 }
65 for (StringRef Dir : SearchDirs) {
66 SmallString<256> Candidate(Dir);
67 sys::path::append(path&: Candidate, a: BaseName);
68 if (auto Path = trySourcePath(Path: Candidate))
69 return Path;
70 }
71 return std::nullopt;
72}
73
74static std::optional<std::string>
75findSourceFilePath(StringRef FileName, ArrayRef<StringRef> SearchDirs) {
76 if (FileName.empty() || FileName == DILineInfo::BadString)
77 return std::nullopt;
78
79 if (sys::path::is_absolute_gnu(path: FileName))
80 return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/true);
81 return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/false);
82}
83
84static std::string applySubstitutePaths(StringRef FileName) {
85 if (SubstitutePaths.empty())
86 return FileName.str();
87
88 // FileName is normalized by the caller, so the components split out of it are
89 // normalized too. Only the rules given on the command line still need it.
90 StringRef BaseName = sys::path::filename(path: FileName);
91 StringRef Directory = sys::path::parent_path(path: FileName);
92
93 for (const auto &[From, To] : SubstitutePaths) {
94 SmallString<256> FromPath(From);
95 normalizeSourcePath(Path&: FromPath);
96 if (!Directory.starts_with(Prefix: FromPath))
97 continue;
98 if (Directory.size() > FromPath.size() &&
99 !sys::path::is_separator(value: Directory[FromPath.size()]))
100 continue;
101
102 SmallString<256> NewDir(To);
103 StringRef Suffix = Directory.substr(Start: FromPath.size());
104 while (!Suffix.empty() && sys::path::is_separator(value: Suffix.front()))
105 Suffix = Suffix.drop_front();
106 if (!Suffix.empty())
107 sys::path::append(path&: NewDir, a: Suffix);
108 normalizeSourcePath(Path&: NewDir);
109
110 if (NewDir.empty())
111 return BaseName.str();
112 SmallString<256> Result(NewDir);
113 sys::path::append(path&: Result, a: BaseName);
114 return std::string(Result);
115 }
116
117 return FileName.str();
118}
119
120bool InlinedFunction::liveAtAddress(object::SectionedAddress Addr) const {
121 if (!Range.valid())
122 return false;
123
124 return Range.LowPC <= Addr.Address && Range.HighPC > Addr.Address;
125}
126
127void InlinedFunction::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {
128 const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName);
129 if (!MangledCallerName)
130 return;
131
132 if (Demangle)
133 OS << "inlined into " << demangle(MangledName: MangledCallerName);
134 else
135 OS << "inlined into " << MangledCallerName;
136}
137
138void InlinedFunction::dump(raw_ostream &OS) const {
139 OS << Name << " @ " << Range << ": ";
140}
141
142void InlinedFunction::printElementLine(raw_ostream &OS,
143 object::SectionedAddress Addr,
144 bool IsEnd) const {
145 uint32_t CallFile, CallLine, CallColumn, CallDiscriminator;
146 InlinedFuncDie.getCallerFrame(CallFile, CallLine, CallColumn,
147 CallDiscriminator);
148 const DWARFDebugLine::LineTable *LineTable =
149 Unit->getContext().getLineTableForUnit(U: Unit);
150 std::string FileName;
151 if (!LineTable->hasFileAtIndex(FileIndex: CallFile))
152 return;
153 if (!LineTable->getFileNameByIndex(
154 FileIndex: CallFile, CompDir: Unit->getCompilationDir(),
155 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Result&: FileName))
156 return;
157
158 if (FileName.empty())
159 return;
160
161 const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName);
162 if (!MangledCallerName)
163 return;
164
165 std::string CallerName = MangledCallerName;
166 std::string CalleeName = Name;
167 if (Demangle) {
168 CallerName = demangle(MangledName: MangledCallerName);
169 CalleeName = demangle(MangledName: Name);
170 }
171
172 OS << "; " << FileName << ":" << CallLine << ":" << CallColumn << ": ";
173 if (IsEnd)
174 OS << "end of ";
175 OS << CalleeName << " inlined into " << CallerName << "\n";
176}
177
178bool LiveVariable::liveAtAddress(object::SectionedAddress Addr) const {
179 if (LocExpr.Range == std::nullopt)
180 return false;
181 return LocExpr.Range->SectionIndex == Addr.SectionIndex &&
182 LocExpr.Range->LowPC <= Addr.Address &&
183 LocExpr.Range->HighPC > Addr.Address;
184}
185
186void LiveVariable::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {
187 DataExtractor Data(LocExpr.Expr, Unit->getContext().isLittleEndian());
188 DWARFExpression Expression(Data, Unit->getAddressByteSize());
189
190 auto GetRegName = [&MRI](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
191 if (std::optional<MCRegister> LLVMRegNum =
192 MRI.getLLVMRegNum(RegNum: DwarfRegNum, isEH: IsEH))
193 if (const char *RegName = MRI.getName(RegNo: *LLVMRegNum))
194 return StringRef(RegName);
195 return {};
196 };
197
198 printDwarfExpressionCompact(E: &Expression, OS, GetNameForDWARFReg: GetRegName);
199}
200
201void LiveVariable::dump(raw_ostream &OS) const {
202 OS << Name << " @ " << LocExpr.Range << ": ";
203}
204
205void LiveElementPrinter::addInlinedFunction(DWARFDie FuncDie,
206 DWARFDie InlinedFuncDie) {
207 uint64_t FuncLowPC, FuncHighPC, SectionIndex;
208 if (!InlinedFuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex))
209 return;
210
211 DWARFUnit *U = InlinedFuncDie.getDwarfUnit();
212 const char *InlinedFuncName = InlinedFuncDie.getName(Kind: DINameKind::LinkageName);
213 DWARFAddressRange Range{FuncLowPC, FuncHighPC, SectionIndex};
214 // Add the new element to the main vector.
215 LiveElements.emplace_back(args: std::make_unique<InlinedFunction>(
216 args&: InlinedFuncName, args&: U, args&: FuncDie, args&: InlinedFuncDie, args&: Range));
217
218 LiveElement *LE = LiveElements.back().get();
219 // Map the element's low address (LowPC) to its pointer for fast range start
220 // lookup.
221 LiveElementsByAddress[FuncLowPC].push_back(x: LE);
222 // Map the element's high address (HighPC) to its pointer for fast range end
223 // lookup.
224 LiveElementsByEndAddress[FuncHighPC].push_back(x: LE);
225 // Map the pointer to its DWARF discovery index for deterministic
226 // ordering.
227 ElementPtrToIndex[LE] = LiveElements.size() - 1;
228}
229
230/// Registers the most recently added LiveVariable into all data structures.
231void LiveElementPrinter::registerNewVariable() {
232 assert(
233 !LiveElements.empty() &&
234 "registerNewVariable called before element was added to LiveElements.");
235 LiveVariable *CurrentVar =
236 static_cast<LiveVariable *>(LiveElements.back().get());
237 assert(ElementPtrToIndex.count(CurrentVar) == 0 &&
238 "Element already registered!");
239
240 // Map from a LiveElement pointer to its index in the LiveElements.
241 ElementPtrToIndex[CurrentVar] = LiveElements.size() - 1;
242
243 if (const std::optional<DWARFAddressRange> &Range =
244 CurrentVar->getLocExpr().Range) {
245 // Add the variable to address-based maps.
246 LiveElementsByAddress[Range->LowPC].push_back(x: CurrentVar);
247 LiveElementsByEndAddress[Range->HighPC].push_back(x: CurrentVar);
248 }
249}
250
251void LiveElementPrinter::addVariable(DWARFDie FuncDie, DWARFDie VarDie) {
252 uint64_t FuncLowPC, FuncHighPC, SectionIndex;
253 FuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex);
254 const char *VarName = VarDie.getName(Kind: DINameKind::ShortName);
255 DWARFUnit *U = VarDie.getDwarfUnit();
256
257 Expected<DWARFLocationExpressionsVector> Locs =
258 VarDie.getLocations(Attr: dwarf::DW_AT_location);
259 if (!Locs) {
260 // If the variable doesn't have any locations, just ignore it. We don't
261 // report an error or warning here as that could be noisy on optimised
262 // code.
263 consumeError(Err: Locs.takeError());
264 return;
265 }
266
267 for (const DWARFLocationExpression &LocExpr : *Locs) {
268 if (LocExpr.Range) {
269 LiveElements.emplace_back(
270 args: std::make_unique<LiveVariable>(args: LocExpr, args&: VarName, args&: U, args&: FuncDie));
271 } else {
272 // If the LocExpr does not have an associated range, it is valid for
273 // the whole of the function.
274 // TODO: technically it is not valid for any range covered by another
275 // LocExpr, does that happen in reality?
276 DWARFLocationExpression WholeFuncExpr{
277 .Range: DWARFAddressRange(FuncLowPC, FuncHighPC, SectionIndex), .Expr: LocExpr.Expr};
278 LiveElements.emplace_back(
279 args: std::make_unique<LiveVariable>(args&: WholeFuncExpr, args&: VarName, args&: U, args&: FuncDie));
280 }
281
282 // Register the new variable with all data structures.
283 registerNewVariable();
284 }
285}
286
287void LiveElementPrinter::addFunction(DWARFDie D) {
288 for (const DWARFDie &Child : D.children()) {
289 if (DbgVariables != DFDisabled &&
290 (Child.getTag() == dwarf::DW_TAG_variable ||
291 Child.getTag() == dwarf::DW_TAG_formal_parameter)) {
292 addVariable(FuncDie: D, VarDie: Child);
293 } else if (DbgInlinedFunctions != DFDisabled &&
294 Child.getTag() == dwarf::DW_TAG_inlined_subroutine) {
295 addInlinedFunction(FuncDie: D, InlinedFuncDie: Child);
296 addFunction(D: Child);
297 } else
298 addFunction(D: Child);
299 }
300}
301
302// Get the column number (in characters) at which the first live element
303// line should be printed.
304unsigned LiveElementPrinter::getIndentLevel() const {
305 return DbgIndent + getInstStartColumn(STI);
306}
307
308// Indent to the first live-range column to the right of the currently
309// printed line, and return the index of that column.
310// TODO: formatted_raw_ostream uses "column" to mean a number of characters
311// since the last \n, and we use it to mean the number of slots in which we
312// put live element lines. Pick a less overloaded word.
313unsigned LiveElementPrinter::moveToFirstVarColumn(formatted_raw_ostream &OS) {
314 // Logical column number: column zero is the first column we print in, each
315 // logical column is 2 physical columns wide.
316 unsigned FirstUnprintedLogicalColumn =
317 std::max(a: (int)(OS.getColumn() - getIndentLevel() + 1) / 2, b: 0);
318 // Physical column number: the actual column number in characters, with
319 // zero being the left-most side of the screen.
320 unsigned FirstUnprintedPhysicalColumn =
321 getIndentLevel() + FirstUnprintedLogicalColumn * 2;
322
323 if (FirstUnprintedPhysicalColumn > OS.getColumn())
324 OS.PadToColumn(NewCol: FirstUnprintedPhysicalColumn);
325
326 return FirstUnprintedLogicalColumn;
327}
328
329unsigned LiveElementPrinter::getOrCreateColumn(unsigned ElementIdx) {
330 // Check if the element already has an assigned column.
331 auto it = ElementToColumn.find(Val: ElementIdx);
332 if (it != ElementToColumn.end())
333 return it->second;
334
335 unsigned ColIdx;
336 if (!FreeCols.empty()) {
337 // Get the smallest available index from the set.
338 ColIdx = *FreeCols.begin();
339 // Remove the index from the set.
340 FreeCols.erase(position: FreeCols.begin());
341 } else {
342 // No free columns, so create a new one.
343 ColIdx = ActiveCols.size();
344 ActiveCols.emplace_back();
345 }
346
347 // Assign the element to the column and update the map.
348 ElementToColumn[ElementIdx] = ColIdx;
349 ActiveCols[ColIdx].ElementIdx = ElementIdx;
350 return ColIdx;
351}
352
353void LiveElementPrinter::freeColumn(unsigned ColIdx) {
354 unsigned ElementIdx = ActiveCols[ColIdx].ElementIdx;
355
356 // Clear the column's data.
357 ActiveCols[ColIdx].clear();
358
359 // Remove the element's entry from the map and add the column to the free
360 // list.
361 ElementToColumn.erase(Val: ElementIdx);
362 FreeCols.insert(x: ColIdx);
363}
364
365std::vector<unsigned>
366LiveElementPrinter::getSortedActiveElementIndices() const {
367 // Get all element indices that currently have an assigned column.
368 std::vector<unsigned> Indices;
369 for (const auto &Pair : ElementToColumn)
370 Indices.push_back(x: Pair.first);
371
372 // Sort by the DWARF discovery order.
373 llvm::stable_sort(Range&: Indices);
374 return Indices;
375}
376
377void LiveElementPrinter::dump() const {
378 for (const std::unique_ptr<LiveElement> &LE : LiveElements) {
379 LE->dump(OS&: dbgs());
380 LE->print(OS&: dbgs(), MRI);
381 dbgs() << "\n";
382 }
383}
384
385void LiveElementPrinter::addCompileUnit(DWARFDie D) {
386 if (D.getTag() == dwarf::DW_TAG_subprogram)
387 addFunction(D);
388 else
389 for (const DWARFDie &Child : D.children())
390 addFunction(D: Child);
391}
392
393/// Update to match the state of the instruction between ThisAddr and
394/// NextAddr. In the common case, any live range active at ThisAddr is
395/// live-in to the instruction, and any live range active at NextAddr is
396/// live-out of the instruction. If IncludeDefinedVars is false, then live
397/// ranges starting at NextAddr will be ignored.
398void LiveElementPrinter::update(object::SectionedAddress ThisAddr,
399 object::SectionedAddress NextAddr,
400 bool IncludeDefinedVars) {
401 // Exit early if only printing function limits.
402 if (DbgInlinedFunctions == DFLimitsOnly)
403 return;
404
405 // Free columns identified in the previous cycle.
406 for (unsigned ColIdx : ColumnsToFreeNextCycle)
407 freeColumn(ColIdx);
408 ColumnsToFreeNextCycle.clear();
409
410 // Update status of active columns and collect those to free next cycle.
411 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) {
412 if (!ActiveCols[ColIdx].isActive())
413 continue;
414
415 const std::unique_ptr<LiveElement> &LE =
416 LiveElements[ActiveCols[ColIdx].ElementIdx];
417 ActiveCols[ColIdx].LiveIn = LE->liveAtAddress(Addr: ThisAddr);
418 ActiveCols[ColIdx].LiveOut = LE->liveAtAddress(Addr: NextAddr);
419
420 LLVM_DEBUG({
421 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();
422 dbgs() << "pass 1, " << ThisAddr.Address << "-" << NextAddr.Address
423 << ", " << Name << ", Col " << ColIdx
424 << ": LiveIn=" << ActiveCols[ColIdx].LiveIn
425 << ", LiveOut=" << ActiveCols[ColIdx].LiveOut << "\n";
426 });
427
428 // If element is fully dead, deactivate column immediately.
429 if (!ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) {
430 ActiveCols[ColIdx].ElementIdx = Column::NullElementIdx;
431 continue;
432 }
433
434 // Mark for cleanup in the next cycle if range ends here.
435 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)
436 ColumnsToFreeNextCycle.push_back(x: ColIdx);
437 }
438
439 // Next, look for variables which don't already have a column, but which
440 // are now live (those starting at ThisAddr or NextAddr).
441 if (IncludeDefinedVars) {
442 // Collect all elements starting at ThisAddr and NextAddr.
443 std::vector<std::pair<unsigned, LiveElement *>> NewLiveElements;
444 auto CollectNewElements = [&](const auto &It) {
445 if (It == LiveElementsByAddress.end())
446 return;
447
448 const std::vector<LiveElement *> &ElementList = It->second;
449 for (LiveElement *LE : ElementList) {
450 auto IndexIt = ElementPtrToIndex.find(Val: LE);
451 assert(IndexIt != ElementPtrToIndex.end() &&
452 "LiveElement in address map but missing from index map!");
453
454 // Get the element index for sorting and column management.
455 unsigned ElementIdx = IndexIt->second;
456 // Skip elements that already have a column.
457 if (ElementToColumn.count(Val: ElementIdx))
458 continue;
459
460 bool LiveIn = LE->liveAtAddress(Addr: ThisAddr);
461 bool LiveOut = LE->liveAtAddress(Addr: NextAddr);
462 if (!LiveIn && !LiveOut)
463 continue;
464
465 NewLiveElements.emplace_back(args&: ElementIdx, args&: LE);
466 }
467 };
468
469 // Collect elements starting at ThisAddr.
470 CollectNewElements(LiveElementsByAddress.find(Key: ThisAddr.Address));
471 // Collect elements starting at NextAddr (the address immediately
472 // following the instruction).
473 CollectNewElements(LiveElementsByAddress.find(Key: NextAddr.Address));
474 // Sort elements by DWARF discovery order for deterministic column
475 // assignment.
476 llvm::stable_sort(Range&: NewLiveElements, C: [](const auto &A, const auto &B) {
477 return A.first < B.first;
478 });
479
480 // Assign columns in deterministic order.
481 for (const auto &ElementPair : NewLiveElements) {
482 unsigned ElementIdx = ElementPair.first;
483 // Skip if element was already added from the first range.
484 if (ElementToColumn.count(Val: ElementIdx))
485 continue;
486
487 LiveElement *LE = ElementPair.second;
488 bool LiveIn = LE->liveAtAddress(Addr: ThisAddr);
489 bool LiveOut = LE->liveAtAddress(Addr: NextAddr);
490
491 // Assign or create a column.
492 unsigned ColIdx = getOrCreateColumn(ElementIdx);
493 LLVM_DEBUG({
494 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();
495 dbgs() << "pass 2, " << ThisAddr.Address << "-" << NextAddr.Address
496 << ", " << Name << ", Col " << ColIdx << ": LiveIn=" << LiveIn
497 << ", LiveOut=" << LiveOut << "\n";
498 });
499
500 ActiveCols[ColIdx].LiveIn = LiveIn;
501 ActiveCols[ColIdx].LiveOut = LiveOut;
502 ActiveCols[ColIdx].MustDrawLabel = true;
503
504 // Mark for cleanup next cycle if range ends here.
505 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)
506 ColumnsToFreeNextCycle.push_back(x: ColIdx);
507 }
508 }
509}
510
511enum class LineChar {
512 RangeStart,
513 RangeMid,
514 RangeEnd,
515 LabelVert,
516 LabelCornerNew,
517 LabelCornerActive,
518 LabelHoriz,
519};
520const char *LiveElementPrinter::getLineChar(LineChar C) const {
521 bool IsASCII = DbgVariables == DFASCII || DbgInlinedFunctions == DFASCII;
522 switch (C) {
523 case LineChar::RangeStart:
524 return IsASCII ? "^" : (const char *)u8"\u2548";
525 case LineChar::RangeMid:
526 return IsASCII ? "|" : (const char *)u8"\u2503";
527 case LineChar::RangeEnd:
528 return IsASCII ? "v" : (const char *)u8"\u253b";
529 case LineChar::LabelVert:
530 return IsASCII ? "|" : (const char *)u8"\u2502";
531 case LineChar::LabelCornerNew:
532 return IsASCII ? "/" : (const char *)u8"\u250c";
533 case LineChar::LabelCornerActive:
534 return IsASCII ? "|" : (const char *)u8"\u2520";
535 case LineChar::LabelHoriz:
536 return IsASCII ? "-" : (const char *)u8"\u2500";
537 }
538 llvm_unreachable("Unhandled LineChar enum");
539}
540
541/// Print live ranges to the right of an existing line. This assumes the
542/// line is not an instruction, so doesn't start or end any live ranges, so
543/// we only need to print active ranges or empty columns. If AfterInst is
544/// true, this is being printed after the last instruction fed to update(),
545/// otherwise this is being printed before it.
546void LiveElementPrinter::printAfterOtherLine(formatted_raw_ostream &OS,
547 bool AfterInst) {
548 if (ActiveCols.size()) {
549 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
550 for (size_t ColIdx = FirstUnprintedColumn, End = ActiveCols.size();
551 ColIdx < End; ++ColIdx) {
552 if (ActiveCols[ColIdx].isActive()) {
553 if ((AfterInst && ActiveCols[ColIdx].LiveOut) ||
554 (!AfterInst && ActiveCols[ColIdx].LiveIn))
555 OS << getLineChar(C: LineChar::RangeMid);
556 else if (!AfterInst && ActiveCols[ColIdx].LiveOut)
557 OS << getLineChar(C: LineChar::LabelVert);
558 else
559 OS << " ";
560 }
561 OS << " ";
562 }
563 }
564 OS << "\n";
565}
566
567/// Print any live element range info needed to the right of a
568/// non-instruction line of disassembly. This is where we print the element
569/// names and expressions, with thin line-drawing characters connecting them
570/// to the live range which starts at the next instruction. If MustPrint is
571/// true, we have to print at least one line (with the continuation of any
572/// already-active live ranges) because something has already been printed
573/// earlier on this line.
574void LiveElementPrinter::printBetweenInsts(formatted_raw_ostream &OS,
575 bool MustPrint) {
576 bool PrintedSomething = false;
577 // Get all active elements, sorted by discovery order.
578 std::vector<unsigned> SortedElementIndices = getSortedActiveElementIndices();
579 // The outer loop iterates over the deterministic DWARF discovery order.
580 for (unsigned ElementIdx : SortedElementIndices) {
581 // Look up the physical column index (ColIdx) assigned to this
582 // element. We use .at() because we are certain the element is active.
583 unsigned ColIdx = ElementToColumn.at(Val: ElementIdx);
584 if (ActiveCols[ColIdx].isActive() && ActiveCols[ColIdx].MustDrawLabel) {
585 // First we need to print the live range markers for any active
586 // columns to the left of this one.
587 OS.PadToColumn(NewCol: getIndentLevel());
588 for (unsigned ColIdx2 = 0; ColIdx2 < ColIdx; ++ColIdx2) {
589 if (ActiveCols[ColIdx2].isActive()) {
590 if (ActiveCols[ColIdx2].MustDrawLabel && !ActiveCols[ColIdx2].LiveIn)
591 OS << getLineChar(C: LineChar::LabelVert) << " ";
592 else
593 OS << getLineChar(C: LineChar::RangeMid) << " ";
594 } else
595 OS << " ";
596 }
597
598 const std::unique_ptr<LiveElement> &LE = LiveElements[ElementIdx];
599 // Then print the variable name and location of the new live range,
600 // with box drawing characters joining it to the live range line.
601 OS << getLineChar(C: ActiveCols[ColIdx].LiveIn ? LineChar::LabelCornerActive
602 : LineChar::LabelCornerNew)
603 << getLineChar(C: LineChar::LabelHoriz) << " ";
604
605 std::string Name = Demangle ? demangle(MangledName: LE->getName()) : LE->getName();
606 WithColor(OS, raw_ostream::GREEN) << Name;
607 OS << " = ";
608 {
609 WithColor ExprColor(OS, raw_ostream::CYAN);
610 LE->print(OS, MRI);
611 }
612
613 // If there are any columns to the right of the expression we just
614 // printed, then continue their live range lines.
615 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
616 for (unsigned ColIdx2 = FirstUnprintedColumn, End = ActiveCols.size();
617 ColIdx2 < End; ++ColIdx2) {
618 if (ActiveCols[ColIdx2].isActive() && ActiveCols[ColIdx2].LiveIn)
619 OS << getLineChar(C: LineChar::RangeMid) << " ";
620 else
621 OS << " ";
622 }
623
624 OS << "\n";
625 PrintedSomething = true;
626 }
627 }
628
629 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx)
630 if (ActiveCols[ColIdx].isActive())
631 ActiveCols[ColIdx].MustDrawLabel = false;
632
633 // If we must print something (because we printed a line/column number),
634 // but don't have any new variables to print, then print a line which
635 // just continues any existing live ranges.
636 if (MustPrint && !PrintedSomething)
637 printAfterOtherLine(OS, AfterInst: false);
638}
639
640/// Print the live element ranges to the right of a disassembled instruction.
641void LiveElementPrinter::printAfterInst(formatted_raw_ostream &OS) {
642 if (!ActiveCols.size())
643 return;
644 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
645 for (unsigned ColIdx = FirstUnprintedColumn, End = ActiveCols.size();
646 ColIdx < End; ++ColIdx) {
647 if (!ActiveCols[ColIdx].isActive())
648 OS << " ";
649 else if (ActiveCols[ColIdx].LiveIn && ActiveCols[ColIdx].LiveOut)
650 OS << getLineChar(C: LineChar::RangeMid) << " ";
651 else if (ActiveCols[ColIdx].LiveOut)
652 OS << getLineChar(C: LineChar::RangeStart) << " ";
653 else if (ActiveCols[ColIdx].LiveIn)
654 OS << getLineChar(C: LineChar::RangeEnd) << " ";
655 else
656 llvm_unreachable("var must be live in or out!");
657 }
658}
659
660void LiveElementPrinter::printBoundaryLine(formatted_raw_ostream &OS,
661 object::SectionedAddress Addr,
662 bool IsEnd) {
663 // Only print the start/end line for inlined functions if DFLimitsOnly is
664 // enabled.
665 if (DbgInlinedFunctions != DFLimitsOnly)
666 return;
667
668 // Select the appropriate map based on whether we are checking the start
669 // (LowPC) or end (HighPC) address.
670 const auto &AddressMap =
671 IsEnd ? LiveElementsByEndAddress : LiveElementsByAddress;
672
673 // Use the map to find all elements that start/end at the given address.
674 std::vector<unsigned> ElementIndices;
675 auto It = AddressMap.find(Key: Addr.Address);
676 if (It != AddressMap.end()) {
677 for (LiveElement *LE : It->second) {
678 // Look up the element index from the pointer.
679 auto IndexIt = ElementPtrToIndex.find(Val: LE);
680 assert(IndexIt != ElementPtrToIndex.end() &&
681 "LiveElement found in address map but missing index!");
682 ElementIndices.push_back(x: IndexIt->second);
683 }
684 }
685
686 // Sort the indices to ensure deterministic output order (by DWARF discovery
687 // order).
688 llvm::stable_sort(Range&: ElementIndices);
689
690 for (unsigned ElementIdx : ElementIndices) {
691 LiveElement *LE = LiveElements[ElementIdx].get();
692 LE->printElementLine(OS, Address: Addr, IsEnd);
693 }
694}
695
696bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
697 std::unique_ptr<MemoryBuffer> Buffer;
698 if (LineInfo.Source) {
699 Buffer = MemoryBuffer::getMemBuffer(InputData: *LineInfo.Source);
700 } else {
701 std::string PathToOpen = LineInfo.FileName;
702 if (!SourceDirs.empty()) {
703 SmallVector<StringRef, 8> SearchDirs;
704 for (const std::string &Dir : SourceDirs)
705 SearchDirs.push_back(Elt: Dir);
706 if (std::optional<std::string> Resolved =
707 findSourceFilePath(FileName: LineInfo.FileName, SearchDirs))
708 PathToOpen = std::move(*Resolved);
709 }
710
711 auto BufferOrError = MemoryBuffer::getFile(Filename: PathToOpen, /*IsText=*/true);
712 if (!BufferOrError) {
713 if (MissingSources.insert(key: LineInfo.FileName).second)
714 reportWarning(Message: "failed to find source " + LineInfo.FileName,
715 File: Obj->getFileName());
716 return false;
717 }
718 Buffer = std::move(*BufferOrError);
719 }
720 // Chomp the file to get lines
721 const char *BufferStart = Buffer->getBufferStart(),
722 *BufferEnd = Buffer->getBufferEnd();
723 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
724 const char *Start = BufferStart;
725 for (const char *I = BufferStart; I != BufferEnd; ++I)
726 if (*I == '\n') {
727 Lines.emplace_back(args&: Start, args: I - Start - (BufferStart < I && I[-1] == '\r'));
728 Start = I + 1;
729 }
730 if (Start < BufferEnd)
731 Lines.emplace_back(args&: Start, args: BufferEnd - Start);
732 SourceCache[LineInfo.FileName] = std::move(Buffer);
733 return true;
734}
735
736void SourcePrinter::printSourceLine(formatted_raw_ostream &OS,
737 object::SectionedAddress Address,
738 StringRef ObjectFilename,
739 LiveElementPrinter &LEP,
740 StringRef Delimiter) {
741 if (!Symbolizer)
742 return;
743
744 DILineInfo LineInfo = DILineInfo();
745 Expected<DILineInfo> ExpectedLineInfo =
746 Symbolizer->symbolizeCode(Obj: *Obj, ModuleOffset: Address);
747 if (ExpectedLineInfo) {
748 LineInfo = *ExpectedLineInfo;
749 if (LineInfo.FileName != DILineInfo::BadString) {
750 SmallString<256> NormalizedName(LineInfo.FileName);
751 normalizeSourcePath(Path&: NormalizedName);
752 LineInfo.FileName = std::string(NormalizedName);
753 }
754 } else if (!WarnedInvalidDebugInfo) {
755 WarnedInvalidDebugInfo = true;
756 // TODO Untested.
757 reportWarning(Message: "failed to parse debug information: " +
758 toString(E: ExpectedLineInfo.takeError()),
759 File: ObjectFilename);
760 }
761 if (!objdump::SubstitutePaths.empty() &&
762 LineInfo.FileName != DILineInfo::BadString)
763 LineInfo.FileName = applySubstitutePaths(FileName: LineInfo.FileName);
764
765 if (!objdump::Prefix.empty() &&
766 sys::path::is_absolute_gnu(path: LineInfo.FileName)) {
767 // FileName has at least one character since is_absolute_gnu is false for
768 // an empty string.
769 assert(!LineInfo.FileName.empty());
770 if (PrefixStrip > 0) {
771 uint32_t Level = 0;
772 auto StrippedNameStart = LineInfo.FileName.begin();
773
774 // Path.h iterator skips extra separators. Therefore it cannot be used
775 // here to keep compatibility with GNU Objdump.
776 for (auto Pos = StrippedNameStart + 1, End = LineInfo.FileName.end();
777 Pos != End && Level < PrefixStrip; ++Pos) {
778 if (sys::path::is_separator(value: *Pos)) {
779 StrippedNameStart = Pos;
780 ++Level;
781 }
782 }
783
784 LineInfo.FileName =
785 std::string(StrippedNameStart, LineInfo.FileName.end());
786 }
787
788 SmallString<128> FilePath;
789 sys::path::append(path&: FilePath, a: Prefix, b: LineInfo.FileName);
790
791 LineInfo.FileName = std::string(FilePath);
792 }
793
794 if (PrintLines)
795 printLines(OS, Address, LineInfo, Delimiter, LEP);
796 if (PrintSource)
797 printSources(OS, LineInfo, ObjectFilename, Delimiter, LEP);
798 OldLineInfo = std::move(LineInfo);
799}
800
801void SourcePrinter::printLines(formatted_raw_ostream &OS,
802 object::SectionedAddress Address,
803 const DILineInfo &LineInfo, StringRef Delimiter,
804 LiveElementPrinter &LEP) {
805 bool PrintFunctionName = LineInfo.FunctionName != DILineInfo::BadString &&
806 LineInfo.FunctionName != OldLineInfo.FunctionName;
807 if (PrintFunctionName) {
808 OS << Delimiter << LineInfo.FunctionName;
809 // If demangling is successful, FunctionName will end with "()". Print it
810 // only if demangling did not run or was unsuccessful.
811 if (!StringRef(LineInfo.FunctionName).ends_with(Suffix: "()"))
812 OS << "()";
813 OS << ":\n";
814 }
815 if (LineInfo.FileName != DILineInfo::BadString && LineInfo.Line != 0 &&
816 (OldLineInfo.Line != LineInfo.Line ||
817 OldLineInfo.FileName != LineInfo.FileName || PrintFunctionName)) {
818 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line;
819 LEP.printBetweenInsts(OS, MustPrint: true);
820 }
821}
822
823// Get the source line text for LineInfo:
824// - use LineInfo::LineSource if available;
825// - use LineCache if LineInfo::Source otherwise.
826StringRef SourcePrinter::getLine(const DILineInfo &LineInfo,
827 StringRef ObjectFilename) {
828 if (LineInfo.LineSource)
829 return LineInfo.LineSource.value();
830
831 if (SourceCache.find(Key: LineInfo.FileName) == SourceCache.end())
832 if (!cacheSource(LineInfo))
833 return {};
834
835 auto LineBuffer = LineCache.find(Key: LineInfo.FileName);
836 if (LineBuffer == LineCache.end())
837 return {};
838
839 if (LineInfo.Line > LineBuffer->second.size()) {
840 reportWarning(
841 Message: formatv(Fmt: "debug info line number {0} exceeds the number of lines in {1}",
842 Vals: LineInfo.Line, Vals: LineInfo.FileName),
843 File: ObjectFilename);
844 return {};
845 }
846
847 // Vector begins at 0, line numbers are non-zero
848 return LineBuffer->second[LineInfo.Line - 1];
849}
850
851void SourcePrinter::printSources(formatted_raw_ostream &OS,
852 const DILineInfo &LineInfo,
853 StringRef ObjectFilename, StringRef Delimiter,
854 LiveElementPrinter &LEP) {
855 if (LineInfo.FileName == DILineInfo::BadString || LineInfo.Line == 0 ||
856 (OldLineInfo.Line == LineInfo.Line &&
857 OldLineInfo.FileName == LineInfo.FileName))
858 return;
859
860 StringRef Line = getLine(LineInfo, ObjectFilename);
861 if (!Line.empty()) {
862 OS << Delimiter << Line;
863 LEP.printBetweenInsts(OS, MustPrint: true);
864 }
865}
866
867SourcePrinter::SourcePrinter(const object::ObjectFile *Obj,
868 StringRef DefaultArch)
869 : Obj(Obj) {
870 symbolize::LLVMSymbolizer::Options SymbolizerOpts;
871 SymbolizerOpts.PrintFunctions =
872 DILineInfoSpecifier::FunctionNameKind::LinkageName;
873 SymbolizerOpts.Demangle = Demangle;
874 SymbolizerOpts.DefaultArch = std::string(DefaultArch);
875 Symbolizer.reset(p: new symbolize::LLVMSymbolizer(SymbolizerOpts));
876}
877
878} // namespace objdump
879} // namespace llvm
880