LLVM 22.0.0git
DebugCounter.cpp
Go to the documentation of this file.
2
3#include "DebugOptions.h"
4
8
9using namespace llvm;
10
11namespace llvm {
12
17
18} // namespace llvm
19
20namespace {
21// This class overrides the default list implementation of printing so we
22// can pretty print the list of debug counter options. This type of
23// dynamic option is pretty rare (basically this and pass lists).
24class DebugCounterList : public cl::list<std::string, DebugCounter> {
25private:
27
28public:
29 template <class... Mods>
30 explicit DebugCounterList(Mods &&... Ms) : Base(std::forward<Mods>(Ms)...) {}
31
32private:
33 void printOptionInfo(size_t GlobalWidth) const override {
34 // This is a variant of from generic_parser_base::printOptionInfo. Sadly,
35 // it's not easy to make it more usable. We could get it to print these as
36 // options if we were a cl::opt and registered them, but lists don't have
37 // options, nor does the parser for std::string. The other mechanisms for
38 // options are global and would pollute the global namespace with our
39 // counters. Rather than go that route, we have just overridden the
40 // printing, which only a few things call anyway.
41 outs() << " -" << ArgStr;
42 // All of the other options in CommandLine.cpp use ArgStr.size() + 6 for
43 // width, so we do the same.
44 Option::printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
45 const auto &CounterInstance = DebugCounter::instance();
46 for (const auto &Entry : CounterInstance) {
47 const auto &[Name, Desc] = CounterInstance.getCounterDesc(Entry.second);
48 size_t NumSpaces = GlobalWidth - Name.size() - 8;
49 outs() << " =" << Name;
50 outs().indent(NumSpaces) << " - " << Desc << '\n';
51 }
52 }
53};
54
55// All global objects associated to the DebugCounter, including the DebugCounter
56// itself, are owned by a single global instance of the DebugCounterOwner
57// struct. This makes it easier to control the order in which constructors and
58// destructors are run.
59struct DebugCounterOwner : DebugCounter {
60 DebugCounterList DebugCounterOption{
61 "debug-counter", cl::Hidden,
62 cl::desc("Comma separated list of debug counter skip and count"),
64 cl::opt<bool, true> PrintDebugCounter{
65 "print-debug-counter",
68 cl::location(this->ShouldPrintCounter),
69 cl::init(false),
70 cl::desc("Print out debug counter info after all counters accumulated"),
71 cl::callback([&](const bool &Value) {
72 if (Value)
73 activateAllCounters();
74 })};
75 cl::opt<bool, true> PrintDebugCounterQueries{
76 "print-debug-counter-queries",
79 cl::location(this->ShouldPrintCounterQueries),
80 cl::init(false),
81 cl::desc("Print out each query of an enabled debug counter")};
82 cl::opt<bool, true> BreakOnLastCount{
83 "debug-counter-break-on-last",
86 cl::location(this->BreakOnLast),
87 cl::init(false),
88 cl::desc("Insert a break point on the last enabled count of a "
89 "chunks list")};
90
91 DebugCounterOwner() {
92 // Our destructor uses the debug stream. By referencing it here, we
93 // ensure that its destructor runs after our destructor.
94 (void)dbgs();
95 }
96
97 // Print information when destroyed, iff command line option is specified.
98 ~DebugCounterOwner() {
99 if (ShouldPrintCounter)
100 print(dbgs());
101 }
102};
103
104} // anonymous namespace
105
106// Use ManagedStatic instead of function-local static variable to ensure
107// the destructor (which accesses counters and streams) runs during
108// llvm_shutdown() rather than at some unspecified point.
110
112
114
115// This is called by the command line parser when it sees a value for the
116// debug-counter option defined above.
117void DebugCounter::push_back(const std::string &Val) {
118 if (Val.empty())
119 return;
120
121 // The strings should come in as counter=chunk_list
122 auto CounterPair = StringRef(Val).split('=');
123 if (CounterPair.second.empty()) {
124 errs() << "DebugCounter Error: " << Val << " does not have an = in it\n";
125 exit(1);
126 }
127 StringRef CounterName = CounterPair.first;
128
129 CounterInfo *Counter = getCounterInfo(CounterName);
130 if (!Counter) {
131 errs() << "DebugCounter Error: " << CounterName
132 << " is not a registered counter\n";
133 return;
134 }
135
136 auto ExpectedChunks =
137 IntegerInclusiveIntervalUtils::parseIntervals(CounterPair.second, ':');
138 if (!ExpectedChunks) {
139 handleAllErrors(ExpectedChunks.takeError(), [&](const StringError &E) {
140 errs() << "DebugCounter Error: " << E.getMessage() << "\n";
141 });
142 exit(1);
143 }
144 Counter->Chunks = std::move(*ExpectedChunks);
145 Counter->Active = Counter->IsSet = true;
146}
147
149 SmallVector<StringRef, 16> CounterNames(Counters.keys());
150 sort(CounterNames);
151
152 OS << "Counters and values:\n";
153 for (StringRef CounterName : CounterNames) {
154 const CounterInfo *C = getCounterInfo(CounterName);
155 OS << left_justify(C->Name, 32) << ": {" << C->Count << ",";
156 printChunks(OS, C->Chunks);
157 OS << "}\n";
158 }
159}
160
162 int64_t CurrCount = Info.Count++;
163 uint64_t CurrIdx = Info.CurrChunkIdx;
164
165 if (Info.Chunks.empty())
166 return true;
167 if (CurrIdx >= Info.Chunks.size())
168 return false;
169
170 bool Res = Info.Chunks[CurrIdx].contains(CurrCount);
171 if (BreakOnLast && CurrIdx == (Info.Chunks.size() - 1) &&
172 CurrCount == Info.Chunks[CurrIdx].getEnd()) {
174 }
175 if (CurrCount > Info.Chunks[CurrIdx].getEnd()) {
176 Info.CurrChunkIdx++;
177
178 /// Handle consecutive blocks.
179 if (Info.CurrChunkIdx < Info.Chunks.size() &&
180 CurrCount == Info.Chunks[Info.CurrChunkIdx].getBegin())
181 return true;
182 }
183 return Res;
184}
185
187 auto &Us = instance();
188 bool Res = Us.handleCounterIncrement(Counter);
189 if (Us.ShouldPrintCounterQueries && Counter.IsSet) {
190 dbgs() << "DebugCounter " << Counter.Name << "=" << (Counter.Count - 1)
191 << (Res ? " execute" : " skip") << "\n";
192 }
193 return Res;
194}
195
196#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
198 print(dbgs());
199}
200#endif
#define LLVM_BUILTIN_DEBUGTRAP
LLVM_BUILTIN_DEBUGTRAP - On compilers which support it, expands to an expression which causes the pro...
Definition Compiler.h:493
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
static ManagedStatic< DebugCounterOwner > Owner
This file provides an implementation of debug counters.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Struct to store counter info.
CounterInfo * getCounterInfo(StringRef Name) const
static LLVM_ABI void printChunks(raw_ostream &OS, ArrayRef< IntegerInclusiveInterval > Intervals)
bool handleCounterIncrement(CounterInfo &Info)
LLVM_ABI void push_back(const std::string &)
static LLVM_ABI bool shouldExecuteImpl(CounterInfo &Counter)
static LLVM_ABI DebugCounter & instance()
Returns a reference to the singleton instance.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_DUMP_METHOD void dump() const
MapVector< StringRef, CounterInfo * > Counters
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class wraps a string in an Error.
Definition Error.h:1282
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:712
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
void printIntervals(raw_ostream &OS, ArrayRef< IntegerInclusiveInterval > Intervals, char Separator=',')
Print intervals to output stream.
Expected< IntervalList > parseIntervals(StringRef IntervalStr, char Separator=',')
Parse a interval specification string like "1-10,20-30,45" or "1-10:20-30:45".
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
cb< typename detail::callback_traits< F >::result_type, typename detail::callback_traits< F >::arg_type > callback(F CB)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:990
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
void initDebugCounterOptions()
Op::Description Desc
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition Format.h:150
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870