LLVM 20.0.0git
DebugUtils.cpp
Go to the documentation of this file.
1//===---------- DebugUtils.cpp - Utilities for debugging ORC JITs ---------===//
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
10
13#include "llvm/Support/Debug.h"
16#include "llvm/Support/Path.h"
18
19#define DEBUG_TYPE "orc"
20
21using namespace llvm;
22
23namespace {
24
25#ifndef NDEBUG
26
27cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(true),
28 cl::desc("debug print hidden symbols defined by "
29 "materialization units"),
31
32cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(true),
33 cl::desc("debug print callable symbols defined by "
34 "materialization units"),
36
37cl::opt<bool> PrintData("debug-orc-print-data", cl::init(true),
38 cl::desc("debug print data symbols defined by "
39 "materialization units"),
41
42#endif // NDEBUG
43
44// SetPrinter predicate that prints every element.
45template <typename T> struct PrintAll {
46 bool operator()(const T &E) { return true; }
47};
48
49bool anyPrintSymbolOptionSet() {
50#ifndef NDEBUG
51 return PrintHidden || PrintCallable || PrintData;
52#else
53 return false;
54#endif // NDEBUG
55}
56
57bool flagsMatchCLOpts(const JITSymbolFlags &Flags) {
58#ifndef NDEBUG
59 // Bail out early if this is a hidden symbol and we're not printing hiddens.
60 if (!PrintHidden && !Flags.isExported())
61 return false;
62
63 // Return true if this is callable and we're printing callables.
64 if (PrintCallable && Flags.isCallable())
65 return true;
66
67 // Return true if this is data and we're printing data.
68 if (PrintData && !Flags.isCallable())
69 return true;
70
71 // otherwise return false.
72 return false;
73#else
74 return false;
75#endif // NDEBUG
76}
77
78// Prints a sequence of items, filtered by an user-supplied predicate.
79template <typename Sequence,
80 typename Pred = PrintAll<typename Sequence::value_type>>
81class SequencePrinter {
82public:
83 SequencePrinter(const Sequence &S, char OpenSeq, char CloseSeq,
84 Pred ShouldPrint = Pred())
85 : S(S), OpenSeq(OpenSeq), CloseSeq(CloseSeq),
86 ShouldPrint(std::move(ShouldPrint)) {}
87
88 void printTo(llvm::raw_ostream &OS) const {
89 bool PrintComma = false;
90 OS << OpenSeq;
91 for (auto &E : S) {
92 if (ShouldPrint(E)) {
93 if (PrintComma)
94 OS << ',';
95 OS << ' ' << E;
96 PrintComma = true;
97 }
98 }
99 OS << ' ' << CloseSeq;
100 }
101
102private:
103 const Sequence &S;
104 char OpenSeq;
105 char CloseSeq;
106 mutable Pred ShouldPrint;
107};
108
109template <typename Sequence, typename Pred>
110SequencePrinter<Sequence, Pred> printSequence(const Sequence &S, char OpenSeq,
111 char CloseSeq, Pred P = Pred()) {
112 return SequencePrinter<Sequence, Pred>(S, OpenSeq, CloseSeq, std::move(P));
113}
114
115// Render a SequencePrinter by delegating to its printTo method.
116template <typename Sequence, typename Pred>
118 const SequencePrinter<Sequence, Pred> &Printer) {
119 Printer.printTo(OS);
120 return OS;
121}
122
123struct PrintSymbolFlagsMapElemsMatchingCLOpts {
124 bool operator()(const orc::SymbolFlagsMap::value_type &KV) {
125 return flagsMatchCLOpts(KV.second);
126 }
127};
128
129struct PrintSymbolMapElemsMatchingCLOpts {
130 bool operator()(const orc::SymbolMap::value_type &KV) {
131 return flagsMatchCLOpts(KV.second.getFlags());
132 }
133};
134
135} // end anonymous namespace
136
137namespace llvm {
138namespace orc {
139
141 return OS << printSequence(Symbols, '{', '}', PrintAll<SymbolStringPtr>());
142}
143
145 return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
146}
147
149 return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
150}
151
153 if (Flags.hasError())
154 OS << "[*ERROR*]";
155 if (Flags.isCallable())
156 OS << "[Callable]";
157 else
158 OS << "[Data]";
159 if (Flags.isWeak())
160 OS << "[Weak]";
161 else if (Flags.isCommon())
162 OS << "[Common]";
163
164 if (!Flags.isExported())
165 OS << "[Hidden]";
166
167 return OS;
168}
169
171 return OS << Sym.getAddress() << " " << Sym.getFlags();
172}
173
175 return OS << "(\"" << KV.first << "\", " << KV.second << ")";
176}
177
179 return OS << "(\"" << KV.first << "\": " << KV.second << ")";
180}
181
183 return OS << printSequence(SymbolFlags, '{', '}',
184 PrintSymbolFlagsMapElemsMatchingCLOpts());
185}
186
188 return OS << printSequence(Symbols, '{', '}',
189 PrintSymbolMapElemsMatchingCLOpts());
190}
191
194 return OS << "(" << KV.first->getName() << ", " << KV.second << ")";
195}
196
198 return OS << printSequence(Deps, '{', '}',
199 PrintAll<SymbolDependenceMap::value_type>());
200}
201
203 OS << "MU@" << &MU << " (\"" << MU.getName() << "\"";
204 if (anyPrintSymbolOptionSet())
205 OS << ", " << MU.getSymbols();
206 return OS << ")";
207}
208
210 switch (K) {
212 return OS << "Static";
214 return OS << "DLSym";
215 }
216 llvm_unreachable("Invalid lookup kind");
217}
218
220 const JITDylibLookupFlags &JDLookupFlags) {
221 switch (JDLookupFlags) {
223 return OS << "MatchExportedSymbolsOnly";
225 return OS << "MatchAllSymbols";
226 }
227 llvm_unreachable("Invalid JITDylib lookup flags");
228}
229
231 switch (LookupFlags) {
233 return OS << "RequiredSymbol";
235 return OS << "WeaklyReferencedSymbol";
236 }
237 llvm_unreachable("Invalid symbol lookup flags");
238}
239
241 const SymbolLookupSet::value_type &KV) {
242 return OS << "(" << KV.first << ", " << KV.second << ")";
243}
244
246 return OS << printSequence(LookupSet, '{', '}',
247 PrintAll<SymbolLookupSet::value_type>());
248}
249
251 const JITDylibSearchOrder &SearchOrder) {
252 OS << "[";
253 if (!SearchOrder.empty()) {
254 assert(SearchOrder.front().first &&
255 "JITDylibList entries must not be null");
256 OS << " (\"" << SearchOrder.front().first->getName() << "\", "
257 << SearchOrder.begin()->second << ")";
258 for (auto &KV : llvm::drop_begin(SearchOrder)) {
259 assert(KV.first && "JITDylibList entries must not be null");
260 OS << ", (\"" << KV.first->getName() << "\", " << KV.second << ")";
261 }
262 }
263 OS << " ]";
264 return OS;
265}
266
268 OS << "{";
269 for (auto &KV : Aliases)
270 OS << " " << *KV.first << ": " << KV.second.Aliasee << " "
271 << KV.second.AliasFlags;
272 OS << " }";
273 return OS;
274}
275
277 switch (S) {
279 return OS << "Invalid";
281 return OS << "Never-Searched";
283 return OS << "Materializing";
285 return OS << "Resolved";
287 return OS << "Emitted";
289 return OS << "Ready";
290 }
291 llvm_unreachable("Invalid state");
292}
293
295 std::lock_guard<std::mutex> Lock(SSP.PoolMutex);
297 for (auto &KV : SSP.Pool)
298 Vec.emplace_back(KV.first(), KV.second);
299 llvm::sort(Vec, less_first());
300 for (auto &[K, V] : Vec)
301 OS << K << ": " << V << "\n";
302 return OS;
303}
304
305DumpObjects::DumpObjects(std::string DumpDir, std::string IdentifierOverride)
306 : DumpDir(std::move(DumpDir)),
307 IdentifierOverride(std::move(IdentifierOverride)) {
308
309 /// Discard any trailing separators.
310 while (!this->DumpDir.empty() &&
311 sys::path::is_separator(this->DumpDir.back()))
312 this->DumpDir.pop_back();
313}
314
316DumpObjects::operator()(std::unique_ptr<MemoryBuffer> Obj) {
317 size_t Idx = 1;
318
319 std::string DumpPathStem;
320 raw_string_ostream(DumpPathStem)
321 << DumpDir << (DumpDir.empty() ? "" : "/") << getBufferIdentifier(*Obj);
322
323 std::string DumpPath = DumpPathStem + ".o";
324 while (sys::fs::exists(DumpPath)) {
325 DumpPath.clear();
326 raw_string_ostream(DumpPath) << DumpPathStem << "." << (++Idx) << ".o";
327 }
328
329 LLVM_DEBUG({
330 dbgs() << "Dumping object buffer [ " << (const void *)Obj->getBufferStart()
331 << " -- " << (const void *)(Obj->getBufferEnd() - 1) << " ] to "
332 << DumpPath << "\n";
333 });
334
335 std::error_code EC;
336 raw_fd_ostream DumpStream(DumpPath, EC);
337 if (EC)
338 return errorCodeToError(EC);
339 DumpStream.write(Obj->getBufferStart(), Obj->getBufferSize());
340
341 return std::move(Obj);
342}
343
344StringRef DumpObjects::getBufferIdentifier(MemoryBuffer &B) {
345 if (!IdentifierOverride.empty())
346 return IdentifierOverride;
347 StringRef Identifier = B.getBufferIdentifier();
348 Identifier.consume_back(".o");
349 return Identifier;
350}
351
352} // End namespace orc.
353} // End namespace llvm.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
dxil pretty DXIL Metadata Pretty Printer
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
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
BucketT value_type
Definition: DenseMap.h:69
Tagged union holding either a T or a Error.
Definition: Error.h:481
Flags for symbols in the JIT.
Definition: JITSymbol.h:74
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
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
Expected< std::unique_ptr< MemoryBuffer > > operator()(std::unique_ptr< MemoryBuffer > Obj)
Dumps the given buffer to disk.
Definition: DebugUtils.cpp:316
DumpObjects(std::string DumpDir="", std::string IdentifierOverride="")
Construct a DumpObjects transform that will dump objects to disk.
Definition: DebugUtils.cpp:305
Represents a defining location for a JIT symbol.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
virtual StringRef getName() const =0
Return the name of this materialization unit.
const SymbolFlagsMap & getSymbols() const
Return the set of symbols that this source provides.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:194
std::pair< SymbolStringPtr, SymbolLookupFlags > value_type
Definition: Core.h:196
String pool for symbol names used by the JIT.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write(unsigned char C)
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
Definition: raw_ostream.h:396
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:173
raw_ostream & operator<<(raw_ostream &OS, const SymbolNameSet &Symbols)
Render a SymbolNameSet.
Definition: DebugUtils.cpp:140
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition: Core.h:156
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:146
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:168
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
Definition: Core.h:767
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Emitted
Assigned address, still materializing.
@ Resolved
Queried, materialization begun.
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1077
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:601
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:303
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1467