LLVM  16.0.0git
DIPrinter.cpp
Go to the documentation of this file.
1 //===- lib/DebugInfo/Symbolize/DIPrinter.cpp ------------------------------===//
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 defines the DIPrinter class, which is responsible for printing
10 // structures defined in DebugInfo/DIContext.h
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/ErrorOr.h"
18 #include "llvm/Support/Format.h"
21 #include <algorithm>
22 #include <cmath>
23 #include <cstddef>
24 #include <cstdint>
25 #include <memory>
26 #include <string>
27 
28 namespace llvm {
29 namespace symbolize {
30 
31 class SourceCode {
32  std::unique_ptr<MemoryBuffer> MemBuf;
33 
34  Optional<StringRef> load(StringRef FileName,
35  const Optional<StringRef> &EmbeddedSource) {
36  if (Lines <= 0)
37  return None;
38 
39  if (EmbeddedSource)
40  return EmbeddedSource;
41  else {
43  MemoryBuffer::getFile(FileName);
44  if (!BufOrErr)
45  return None;
46  MemBuf = std::move(*BufOrErr);
47  return MemBuf->getBuffer();
48  }
49  }
50 
51  Optional<StringRef> pruneSource(const Optional<StringRef> &Source) {
52  if (!Source)
53  return None;
54  size_t FirstLinePos = StringRef::npos, Pos = 0;
55  for (int64_t L = 1; L <= LastLine; ++L, ++Pos) {
56  if (L == FirstLine)
57  FirstLinePos = Pos;
58  Pos = Source->find('\n', Pos);
59  if (Pos == StringRef::npos)
60  break;
61  }
62  if (FirstLinePos == StringRef::npos)
63  return None;
64  return Source->substr(FirstLinePos, (Pos == StringRef::npos)
66  : Pos - FirstLinePos);
67  }
68 
69 public:
70  const int64_t Line;
71  const int Lines;
72  const int64_t FirstLine;
73  const int64_t LastLine;
75 
77  StringRef FileName, int64_t Line, int Lines,
78  const Optional<StringRef> &EmbeddedSource = Optional<StringRef>())
79  : Line(Line), Lines(Lines),
80  FirstLine(std::max(static_cast<int64_t>(1), Line - Lines / 2)),
81  LastLine(FirstLine + Lines - 1),
82  PrunedSource(pruneSource(load(FileName, EmbeddedSource))) {}
83 
84  void format(raw_ostream &OS) {
85  if (!PrunedSource)
86  return;
87  size_t MaxLineNumberWidth = std::ceil(std::log10(LastLine));
88  int64_t L = FirstLine;
89  for (size_t Pos = 0; Pos < PrunedSource->size(); ++L) {
90  size_t PosEnd = PrunedSource->find('\n', Pos);
91  StringRef String = PrunedSource->substr(
92  Pos, (PosEnd == StringRef::npos) ? StringRef::npos : (PosEnd - Pos));
93  if (String.endswith("\r"))
94  String = String.drop_back(1);
95  OS << format_decimal(L, MaxLineNumberWidth);
96  if (L == Line)
97  OS << " >: ";
98  else
99  OS << " : ";
100  OS << String << '\n';
101  if (PosEnd == StringRef::npos)
102  break;
103  Pos = PosEnd + 1;
104  }
105  }
106 };
107 
108 void PlainPrinterBase::printHeader(uint64_t Address) {
109  if (Config.PrintAddress) {
110  OS << "0x";
111  OS.write_hex(Address);
112  StringRef Delimiter = Config.Pretty ? ": " : "\n";
113  OS << Delimiter;
114  }
115 }
116 
117 // Prints source code around in the FileName the Line.
120 }
121 
122 void PlainPrinterBase::printFunctionName(StringRef FunctionName, bool Inlined) {
123  if (Config.PrintFunctions) {
124  if (FunctionName == DILineInfo::BadString)
125  FunctionName = DILineInfo::Addr2LineBadString;
126  StringRef Delimiter = Config.Pretty ? " at " : "\n";
127  StringRef Prefix = (Config.Pretty && Inlined) ? " (inlined by) " : "";
128  OS << Prefix << FunctionName << Delimiter;
129  }
130 }
131 
132 void LLVMPrinter::printSimpleLocation(StringRef Filename,
133  const DILineInfo &Info) {
134  OS << Filename << ':' << Info.Line << ':' << Info.Column << '\n';
135  printContext(
136  SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
137 }
138 
139 void GNUPrinter::printSimpleLocation(StringRef Filename,
140  const DILineInfo &Info) {
141  OS << Filename << ':' << Info.Line;
142  if (Info.Discriminator)
143  OS << " (discriminator " << Info.Discriminator << ')';
144  OS << '\n';
145  printContext(
146  SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
147 }
148 
150  const DILineInfo &Info) {
151  OS << " Filename: " << Filename << '\n';
152  if (Info.StartLine) {
153  OS << " Function start filename: " << Info.StartFileName << '\n';
154  OS << " Function start line: " << Info.StartLine << '\n';
155  }
157  OS << " Line: " << Info.Line << '\n';
158  OS << " Column: " << Info.Column << '\n';
159  if (Info.Discriminator)
160  OS << " Discriminator: " << Info.Discriminator << '\n';
161 }
162 
163 void LLVMPrinter::printStartAddress(const DILineInfo &Info) {
164  if (Info.StartAddress) {
165  OS << " Function start address: 0x";
166  OS.write_hex(*Info.StartAddress);
167  OS << '\n';
168  }
169 }
170 
171 void LLVMPrinter::printFooter() { OS << '\n'; }
172 
173 void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
174  printFunctionName(Info.FunctionName, Inlined);
175  StringRef Filename = Info.FileName;
176  if (Filename == DILineInfo::BadString)
178  if (Config.Verbose)
179  printVerbose(Filename, Info);
180  else
181  printSimpleLocation(Filename, Info);
182 }
183 
185  printHeader(*Request.Address);
186  print(Info, false);
187  printFooter();
188 }
189 
191  const DIInliningInfo &Info) {
192  printHeader(*Request.Address);
193  uint32_t FramesNum = Info.getNumberOfFrames();
194  if (FramesNum == 0)
195  print(DILineInfo(), false);
196  else
197  for (uint32_t I = 0; I < FramesNum; ++I)
198  print(Info.getFrame(I), I > 0);
199  printFooter();
200 }
201 
202 void PlainPrinterBase::print(const Request &Request, const DIGlobal &Global) {
203  printHeader(*Request.Address);
204  StringRef Name = Global.Name;
205  if (Name == DILineInfo::BadString)
207  OS << Name << "\n";
208  OS << Global.Start << " " << Global.Size << "\n";
209  if (Global.DeclFile.empty())
210  OS << "??:?\n";
211  else
212  OS << Global.DeclFile << ":" << Global.DeclLine << "\n";
213  printFooter();
214 }
215 
217  const std::vector<DILocal> &Locals) {
218  printHeader(*Request.Address);
219  if (Locals.empty())
221  else
222  for (const DILocal &L : Locals) {
223  if (L.FunctionName.empty())
225  else
226  OS << L.FunctionName;
227  OS << '\n';
228 
229  if (L.Name.empty())
231  else
232  OS << L.Name;
233  OS << '\n';
234 
235  if (L.DeclFile.empty())
237  else
238  OS << L.DeclFile;
239 
240  OS << ':' << L.DeclLine << '\n';
241 
242  if (L.FrameOffset)
243  OS << *L.FrameOffset;
244  else
246  OS << ' ';
247 
248  if (L.Size)
249  OS << *L.Size;
250  else
252  OS << ' ';
253 
254  if (L.TagOffset)
255  OS << *L.TagOffset;
256  else
258  OS << '\n';
259  }
260  printFooter();
261 }
262 
264  StringRef Command) {
265  OS << Command << '\n';
266 }
267 
269  const ErrorInfoBase &ErrorInfo,
270  StringRef ErrorBanner) {
271  ES << ErrorBanner;
272  ErrorInfo.log(ES);
273  ES << '\n';
274  // Print an empty struct too.
275  return true;
276 }
277 
278 static std::string toHex(uint64_t V) {
279  return ("0x" + Twine::utohexstr(V)).str();
280 }
281 
282 static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
283  json::Object Json({{"ModuleName", Request.ModuleName.str()}});
284  if (Request.Address)
285  Json["Address"] = toHex(*Request.Address);
286  if (!ErrorMsg.empty())
287  Json["Error"] = json::Object({{"Message", ErrorMsg.str()}});
288  return Json;
289 }
290 
292  DIInliningInfo InliningInfo;
293  InliningInfo.addFrame(Info);
294  print(Request, InliningInfo);
295 }
296 
298  json::Array Array;
299  for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
300  const DILineInfo &LineInfo = Info.getFrame(I);
302  {{"FunctionName", LineInfo.FunctionName != DILineInfo::BadString
303  ? LineInfo.FunctionName
304  : ""},
305  {"StartFileName", LineInfo.StartFileName != DILineInfo::BadString
306  ? LineInfo.StartFileName
307  : ""},
308  {"StartLine", LineInfo.StartLine},
309  {"StartAddress",
310  LineInfo.StartAddress ? toHex(*LineInfo.StartAddress) : ""},
311  {"FileName",
312  LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
313  {"Line", LineInfo.Line},
314  {"Column", LineInfo.Column},
315  {"Discriminator", LineInfo.Discriminator}});
316  SourceCode SourceCode(LineInfo.FileName, LineInfo.Line,
317  Config.SourceContextLines, LineInfo.Source);
318  std::string FormattedSource;
319  raw_string_ostream Stream(FormattedSource);
320  SourceCode.format(Stream);
321  if (!FormattedSource.empty())
322  Object["Source"] = std::move(FormattedSource);
323  Array.push_back(std::move(Object));
324  }
325  json::Object Json = toJSON(Request);
326  Json["Symbol"] = std::move(Array);
327  if (ObjectList)
328  ObjectList->push_back(std::move(Json));
329  else
330  printJSON(std::move(Json));
331 }
332 
333 void JSONPrinter::print(const Request &Request, const DIGlobal &Global) {
335  {{"Name", Global.Name != DILineInfo::BadString ? Global.Name : ""},
336  {"Start", toHex(Global.Start)},
337  {"Size", toHex(Global.Size)}});
338  json::Object Json = toJSON(Request);
339  Json["Data"] = std::move(Data);
340  if (ObjectList)
341  ObjectList->push_back(std::move(Json));
342  else
343  printJSON(std::move(Json));
344 }
345 
347  const std::vector<DILocal> &Locals) {
348  json::Array Frame;
349  for (const DILocal &Local : Locals) {
350  json::Object FrameObject(
351  {{"FunctionName", Local.FunctionName},
352  {"Name", Local.Name},
353  {"DeclFile", Local.DeclFile},
354  {"DeclLine", int64_t(Local.DeclLine)},
355  {"Size", Local.Size ? toHex(*Local.Size) : ""},
356  {"TagOffset", Local.TagOffset ? toHex(*Local.TagOffset) : ""}});
357  if (Local.FrameOffset)
358  FrameObject["FrameOffset"] = *Local.FrameOffset;
359  Frame.push_back(std::move(FrameObject));
360  }
361  json::Object Json = toJSON(Request);
362  Json["Frame"] = std::move(Frame);
363  if (ObjectList)
364  ObjectList->push_back(std::move(Json));
365  else
366  printJSON(std::move(Json));
367 }
368 
370  StringRef Command) {
372  StringError("unable to parse arguments: " + Command,
373  std::make_error_code(std::errc::invalid_argument)),
374  "");
375 }
376 
378  const ErrorInfoBase &ErrorInfo,
379  StringRef ErrorBanner) {
381  if (ObjectList)
382  ObjectList->push_back(std::move(Json));
383  else
384  printJSON(std::move(Json));
385  return false;
386 }
387 
389  assert(!ObjectList);
390  ObjectList = std::make_unique<json::Array>();
391 }
392 
394  assert(ObjectList);
395  printJSON(std::move(*ObjectList));
396  ObjectList.reset();
397 }
398 
399 } // end namespace symbolize
400 } // end namespace llvm
MemoryBuffer.h
llvm::ErrorInfoBase::log
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
llvm::DILineInfo::Source
Optional< StringRef > Source
Definition: DIContext.h:39
llvm::symbolize::SourceCode::FirstLine
const int64_t FirstLine
Definition: DIPrinter.cpp:72
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::symbolize::PlainPrinterBase::printInvalidCommand
void printInvalidCommand(const Request &Request, StringRef Command) override
Definition: DIPrinter.cpp:263
llvm::symbolize::PlainPrinterBase::printContext
void printContext(SourceCode SourceCode)
Definition: DIPrinter.cpp:118
llvm::symbolize::SourceCode::LastLine
const int64_t LastLine
Definition: DIPrinter.cpp:73
ceil
We have fiadd patterns now but the followings have the same cost and complexity We need a way to specify the later is more profitable def def The FP stackifier should handle simple permutates to reduce number of shuffle e g ceil
Definition: README-FPStack.txt:54
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:161
llvm::DIInliningInfo
A format-neutral container for inlined code description.
Definition: DIContext.h:87
StringRef.h
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:629
llvm::symbolize::JSONPrinter::listBegin
void listBegin() override
Definition: DIPrinter.cpp:388
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:52
llvm::symbolize::PlainPrinterBase::Config
PrinterConfig Config
Definition: DIPrinter.h:74
llvm::DILineInfo::BadString
static constexpr const char *const BadString
Definition: DIContext.h:33
llvm::format_decimal
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:211
llvm::symbolize::PlainPrinterBase::OS
raw_ostream & OS
Definition: DIPrinter.h:72
llvm::symbolize::PlainPrinterBase::print
void print(const DILineInfo &Info, bool Inlined)
Definition: DIPrinter.cpp:173
llvm::Optional
Definition: APInt.h:33
llvm::symbolize::PlainPrinterBase::printFooter
virtual void printFooter()
Definition: DIPrinter.h:83
llvm::symbolize::JSONPrinter::print
void print(const Request &Request, const DILineInfo &Info) override
Definition: DIPrinter.cpp:291
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
Format.h
llvm::symbolize::toJSON
static json::Object toJSON(const Request &Request, StringRef ErrorMsg="")
Definition: DIPrinter.cpp:282
llvm::json::Array::push_back
void push_back(const Value &E)
Definition: JSON.h:531
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, Optional< Align > Alignment=None)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:244
llvm::DILineInfo::FunctionName
std::string FunctionName
Definition: DIContext.h:37
llvm::symbolize::Request::Address
Optional< uint64_t > Address
Definition: DIPrinter.h:37
llvm::DILineInfo::Addr2LineBadString
static constexpr const char *const Addr2LineBadString
Definition: DIContext.h:35
llvm::DILineInfo::Column
uint32_t Column
Definition: DIContext.h:41
llvm::symbolize::PrinterConfig::PrintAddress
bool PrintAddress
Definition: DIPrinter.h:63
llvm::symbolize::PlainPrinterBase::printStartAddress
virtual void printStartAddress(const DILineInfo &Info)
Definition: DIPrinter.h:82
llvm::DIInliningInfo::addFrame
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:107
llvm::symbolize::JSONPrinter::printInvalidCommand
void printInvalidCommand(const Request &Request, StringRef Command) override
Definition: DIPrinter.cpp:369
llvm::symbolize::SourceCode::SourceCode
SourceCode(StringRef FileName, int64_t Line, int Lines, const Optional< StringRef > &EmbeddedSource=Optional< StringRef >())
Definition: DIPrinter.cpp:76
llvm::json::Array
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:158
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::DILineInfo::StartLine
uint32_t StartLine
Definition: DIContext.h:42
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
llvm::symbolize::PrinterConfig::PrintFunctions
bool PrintFunctions
Definition: DIPrinter.h:64
llvm::symbolize::Request::ModuleName
StringRef ModuleName
Definition: DIPrinter.h:36
llvm::ErrorInfoBase
Base class for error info classes.
Definition: Error.h:46
llvm::ErrorInfoBase::message
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:54
llvm::symbolize::PrinterConfig::SourceContextLines
int SourceContextLines
Definition: DIPrinter.h:67
llvm::OutputFileType::Object
@ Object
llvm::DILineInfo::Line
uint32_t Line
Definition: DIContext.h:40
llvm::Twine::utohexstr
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:404
uint64_t
llvm::symbolize::toHex
static std::string toHex(uint64_t V)
Definition: DIPrinter.cpp:278
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
ErrorOr.h
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::symbolize::PrinterConfig::Verbose
bool Verbose
Definition: DIPrinter.h:66
llvm::DILineInfo
A format-neutral container for source line information.
Definition: DIContext.h:31
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::DILineInfo::Discriminator
uint32_t Discriminator
Definition: DIContext.h:46
llvm::StringError
This class wraps a string in an Error.
Definition: Error.h:1215
llvm::ErrorInfo
Base class for user error types.
Definition: Error.h:347
llvm::Sched::Source
@ Source
Definition: TargetLowering.h:99
DIPrinter.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
uint32_t
llvm::symbolize::PrinterConfig::Pretty
bool Pretty
Definition: DIPrinter.h:65
llvm::make_error_code
std::error_code make_error_code(BitcodeError E)
Definition: BitcodeReader.h:274
DIContext.h
std
Definition: BitVector.h:851
llvm::DIGlobal
Container for description of a global variable.
Definition: DIContext.h:113
llvm::None
constexpr std::nullopt_t None
Definition: None.h:27
llvm::symbolize::PlainPrinterBase::printVerbose
void printVerbose(StringRef Filename, const DILineInfo &Info)
Definition: DIPrinter.cpp:149
llvm::DILocal
Definition: DIContext.h:123
llvm::symbolize::Request
Definition: DIPrinter.h:35
llvm::symbolize::PlainPrinterBase::printSimpleLocation
virtual void printSimpleLocation(StringRef Filename, const DILineInfo &Info)=0
llvm::DILineInfo::StartAddress
Optional< uint64_t > StartAddress
Definition: DIContext.h:43
llvm::symbolize::JSONPrinter::listEnd
void listEnd() override
Definition: DIPrinter.cpp:393
llvm::symbolize::SourceCode
Definition: DIPrinter.cpp:31
llvm::symbolize::PlainPrinterBase::ES
raw_ostream & ES
Definition: DIPrinter.h:73
llvm::symbolize::SourceCode::format
void format(raw_ostream &OS)
Definition: DIPrinter.cpp:84
llvm::DILineInfo::FileName
std::string FileName
Definition: DIContext.h:36
llvm::symbolize::PlainPrinterBase::printError
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo, StringRef ErrorBanner) override
Definition: DIPrinter.cpp:268
N
#define N
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::symbolize::JSONPrinter::printError
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo, StringRef ErrorBanner) override
Definition: DIPrinter.cpp:377
llvm::StringRef::str
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:221
llvm::symbolize::SourceCode::Lines
const int Lines
Definition: DIPrinter.cpp:71
raw_ostream.h
llvm::json::Object
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:92
llvm::symbolize::SourceCode::Line
const int64_t Line
Definition: DIPrinter.cpp:70
llvm::symbolize::SourceCode::PrunedSource
const Optional< StringRef > PrunedSource
Definition: DIPrinter.cpp:74
llvm::symbolize::PlainPrinterBase::printFunctionName
void printFunctionName(StringRef FunctionName, bool Inlined)
Definition: DIPrinter.cpp:122
llvm::raw_ostream::write_hex
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
Definition: raw_ostream.cpp:138
llvm::DILineInfo::StartFileName
std::string StartFileName
Definition: DIContext.h:38