LLDB mainline
Statistics.h
Go to the documentation of this file.
1//===-- Statistics.h --------------------------------------------*- 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#ifndef LLDB_TARGET_STATISTICS_H
10#define LLDB_TARGET_STATISTICS_H
11
15#include "lldb/Utility/Stream.h"
16#include "lldb/lldb-forward.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/Support/JSON.h"
19#include <atomic>
20#include <chrono>
21#include <mutex>
22#include <optional>
23#include <ratio>
24#include <string>
25#include <vector>
26
27namespace lldb_private {
28
29using StatsClock = std::chrono::high_resolution_clock;
30using StatsTimepoint = std::chrono::time_point<StatsClock>;
32// Declaring here as there is no private forward
33typedef std::shared_ptr<SummaryStatistics> SummaryStatisticsSP;
34
36public:
37 using Duration = std::chrono::duration<double>;
38
39 Duration get() const {
40 return Duration(InternalDuration(value.load(std::memory_order_relaxed)));
41 }
42 operator Duration() const { return get(); }
43
44 void reset() { value.store(0, std::memory_order_relaxed); }
45
47 value.fetch_add(std::chrono::duration_cast<InternalDuration>(dur).count(),
48 std::memory_order_relaxed);
49 return *this;
50 }
51
52private:
53 using InternalDuration = std::chrono::duration<uint64_t, std::micro>;
54 std::atomic<uint64_t> value{0};
55};
56
57/// A class that measures elapsed time in an exception safe way.
58///
59/// This is a RAII class is designed to help gather timing statistics within
60/// LLDB where objects have optional Duration variables that get updated with
61/// elapsed times. This helps LLDB measure statistics for many things that are
62/// then reported in LLDB commands.
63///
64/// Objects that need to measure elapsed times should have a variable of type
65/// "StatsDuration m_time_xxx;" which can then be used in the constructor of
66/// this class inside a scope that wants to measure something:
67///
68/// ElapsedTime elapsed(m_time_xxx);
69/// // Do some work
70///
71/// This class will increment the m_time_xxx variable with the elapsed time
72/// when the object goes out of scope. The "m_time_xxx" variable will be
73/// incremented when the class goes out of scope. This allows a variable to
74/// measure something that might happen in stages at different times, like
75/// resolving a breakpoint each time a new shared library is loaded.
77public:
78 /// Set to the start time when the object is created.
80 /// Elapsed time in seconds to increment when this object goes out of scope.
82
83public:
84 ElapsedTime(StatsDuration &opt_time) : m_elapsed_time(opt_time) {
85 m_start_time = StatsClock::now();
86 }
88 StatsClock::duration elapsed = StatsClock::now() - m_start_time;
90 }
91};
92
93/// A class to count time for plugins
95public:
96 void add(llvm::StringRef key, double value) {
97 if (key.empty())
98 return;
99 auto it = map.find(key);
100 if (it == map.end())
101 map.try_emplace(key, value);
102 else
103 it->second += value;
104 }
105 void merge(StatisticsMap map_to_merge) {
106 for (const auto &entry : map_to_merge.map) {
107 add(entry.first(), entry.second);
108 }
109 }
110 llvm::StringMap<double> map;
111};
112
113/// A class to count success/fail statistics.
115 StatsSuccessFail(llvm::StringRef n) : name(n.str()) {}
116
119
120 llvm::json::Value ToJSON() const;
121 std::string name;
122 uint32_t successes = 0;
123 uint32_t failures = 0;
124};
125
126/// Holds statistics about DWO (Debug With Object) files.
127struct DWOStats {
129 uint32_t dwo_file_count = 0;
130 uint32_t dwo_error_count = 0;
131
138
139 friend DWOStats operator+(DWOStats lhs, const DWOStats &rhs) {
140 lhs += rhs;
141 return lhs;
142 }
143};
144
145/// A class that represents statistics for a since lldb_private::Module.
147 llvm::json::Value ToJSON() const;
148 intptr_t identifier;
149 std::string path;
150 std::string uuid;
151 std::string triple;
152 // Path separate debug info file, or empty if none.
153 std::string symfile_path;
154 // If the debug info is contained in multiple files where each one is
155 // represented as a separate lldb_private::Module, then these are the
156 // identifiers of these modules in the global module list. This allows us to
157 // track down all of the stats that contribute to this module.
158 std::vector<intptr_t> symfile_modules;
159 llvm::StringMap<llvm::json::Value> type_system_stats;
161 double symtab_parse_time = 0.0;
162 double symtab_index_time = 0.0;
164 double debug_parse_time = 0.0;
165 double debug_index_time = 0.0;
166 uint64_t debug_info_size = 0;
172 bool symtab_stripped = false;
176};
177
182
184public:
185 void SetSummaryOnly(bool value) { m_summary_only = value; }
186 bool GetSummaryOnly() const { return m_summary_only.value_or(false); }
187
188 void SetLoadAllDebugInfo(bool value) { m_load_all_debug_info = value; }
189 bool GetLoadAllDebugInfo() const {
190 return m_load_all_debug_info.value_or(false);
191 }
192
193 void SetIncludeTargets(bool value) { m_include_targets = value; }
194 bool GetIncludeTargets() const {
195 if (m_include_targets.has_value())
196 return m_include_targets.value();
197 // Default to true in both default mode and summary mode.
198 return true;
199 }
200
201 void SetIncludeModules(bool value) { m_include_modules = value; }
202 bool GetIncludeModules() const {
203 if (m_include_modules.has_value())
204 return m_include_modules.value();
205 // `m_include_modules` has no value set, so return a value based on
206 // `m_summary_only`.
207 return !GetSummaryOnly();
208 }
209
210 void SetIncludeTranscript(bool value) { m_include_transcript = value; }
211 bool GetIncludeTranscript() const {
212 return m_include_transcript.value_or(false);
213 }
214
215 void SetIncludePlugins(bool value) { m_include_plugins = value; }
216 bool GetIncludePlugins() const {
217 if (m_include_plugins.has_value())
218 return m_include_plugins.value();
219 // Default to true in both default mode and summary mode.
220 return true;
221 }
222
223private:
224 std::optional<bool> m_summary_only;
225 std::optional<bool> m_load_all_debug_info;
226 std::optional<bool> m_include_targets;
227 std::optional<bool> m_include_modules;
228 std::optional<bool> m_include_transcript;
229 std::optional<bool> m_include_plugins;
230};
231
232/// A class that represents statistics about a TypeSummaryProviders invocations
233/// \note All members of this class need to be accessed in a thread safe manner
235public:
236 explicit SummaryStatistics(std::string name, std::string impl_type)
237 : m_total_time(), m_impl_type(std::move(impl_type)),
238 m_name(std::move(name)), m_count(0) {}
239
240 std::string GetName() const { return m_name; };
241 double GetTotalTime() const { return m_total_time.get().count(); }
242
243 uint64_t GetSummaryCount() const {
244 return m_count.load(std::memory_order_relaxed);
245 }
246
248
249 std::string GetSummaryKindName() const { return m_impl_type; }
250
251 llvm::json::Value ToJSON() const;
252
253 void Reset() { m_total_time.reset(); }
254
255 /// Basic RAII class to increment the summary count when the call is complete.
257 public:
259 : m_stats(summary_stats),
260 m_elapsed_time(summary_stats->GetDurationReference()) {}
261 ~SummaryInvocation() { m_stats->OnInvoked(); }
262
263 /// Delete the copy constructor and assignment operator to prevent
264 /// accidental double counting.
265 /// @{
268 /// @}
269
270 private:
273 };
274
275private:
276 void OnInvoked() noexcept { m_count.fetch_add(1, std::memory_order_relaxed); }
278 const std::string m_impl_type;
279 const std::string m_name;
280 std::atomic<uint64_t> m_count;
281};
282
283/// A class that wraps a std::map of SummaryStatistics objects behind a mutex.
285public:
286 /// Get the SummaryStatistics object for a given provider name, or insert
287 /// if statistics for that provider is not in the map.
290 std::lock_guard<std::mutex> guard(m_map_mutex);
291 if (auto iterator = m_summary_stats_map.find(provider.GetName());
292 iterator != m_summary_stats_map.end())
293 return iterator->second;
294
295 auto it = m_summary_stats_map.try_emplace(
296 provider.GetName(),
297 std::make_shared<SummaryStatistics>(provider.GetName(),
298 provider.GetSummaryKindName()));
299 return it.first->second;
300 }
301
302 llvm::json::Value ToJSON();
303
304 void Reset();
305
306private:
307 llvm::StringMap<SummaryStatisticsSP> m_summary_stats_map;
308 std::mutex m_map_mutex;
309};
310
311/// A class that represents statistics for a since lldb_private::Target.
313public:
314 llvm::json::Value ToJSON(Target &target,
315 const lldb_private::StatisticsOptions &options);
316
321 void IncreaseSourceRealpathAttemptCount(uint32_t count);
322 void IncreaseSourceRealpathCompatibleCount(uint32_t count);
323
327 void Reset(Target &target);
328
329protected:
331 std::optional<StatsTimepoint> m_launch_or_attach_time;
332 std::optional<StatsTimepoint> m_first_private_stop_time;
333 std::optional<StatsTimepoint> m_first_public_stop_time;
334 StatsSuccessFail m_expr_eval{"expressionEvaluation"};
336 std::vector<intptr_t> m_module_identifiers;
340 void CollectStats(Target &target);
341};
342
344public:
345 static void SetCollectingStats(bool enable) { g_collecting_stats = enable; }
346 static bool GetCollectingStats() { return g_collecting_stats; }
347
348 /// Get metrics associated with one or all targets in a debugger in JSON
349 /// format.
350 ///
351 /// \param debugger
352 /// The debugger to get the target list from if \a target is NULL.
353 ///
354 /// \param target
355 /// The single target to emit statistics for if non NULL, otherwise dump
356 /// statistics only for the specified target.
357 ///
358 /// \param summary_only
359 /// If true, only report high level summary statistics without
360 /// targets/modules/breakpoints etc.. details.
361 ///
362 /// \return
363 /// Returns a JSON value that contains all target metrics.
364 static llvm::json::Value
365 ReportStatistics(Debugger &debugger, Target *target,
366 const lldb_private::StatisticsOptions &options);
367
368 /// Reset metrics associated with one or all targets in a debugger.
369 ///
370 /// \param debugger
371 /// The debugger to reset the target list from if \a target is NULL.
372 ///
373 /// \param target
374 /// The target to reset statistics for, or if null, reset statistics
375 /// for all targets
376 static void ResetStatistics(Debugger &debugger, Target *target);
377
378protected:
379 // Collecting stats can be set to true to collect stats that are expensive
380 // to collect. By default all stats that are cheap to collect are enabled.
381 // This settings is here to maintain compatibility with "statistics enable"
382 // and "statistics disable".
384};
385
386} // namespace lldb_private
387
388#endif // LLDB_TARGET_STATISTICS_H
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
static MemoryStats GetMemoryStats()
static void SetCollectingStats(bool enable)
Definition Statistics.h:345
static bool GetCollectingStats()
Definition Statistics.h:346
static void ResetStatistics(Debugger &debugger, Target *target)
Reset metrics associated with one or all targets in a debugger.
static llvm::json::Value ReportStatistics(Debugger &debugger, Target *target, const lldb_private::StatisticsOptions &options)
Get metrics associated with one or all targets in a debugger in JSON format.
A class to manage flag bits.
Definition Debugger.h:80
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
StatsDuration & m_elapsed_time
Elapsed time in seconds to increment when this object goes out of scope.
Definition Statistics.h:81
ElapsedTime(StatsDuration &opt_time)
Definition Statistics.h:84
StatsTimepoint m_start_time
Set to the start time when the object is created.
Definition Statistics.h:79
A class to count time for plugins.
Definition Statistics.h:94
llvm::StringMap< double > map
Definition Statistics.h:110
void add(llvm::StringRef key, double value)
Definition Statistics.h:96
void merge(StatisticsMap map_to_merge)
Definition Statistics.h:105
std::atomic< uint64_t > value
Definition Statistics.h:54
std::chrono::duration< double > Duration
Definition Statistics.h:37
StatsDuration & operator+=(Duration dur)
Definition Statistics.h:46
std::chrono::duration< uint64_t, std::micro > InternalDuration
Definition Statistics.h:53
A class that wraps a std::map of SummaryStatistics objects behind a mutex.
Definition Statistics.h:284
llvm::StringMap< SummaryStatisticsSP > m_summary_stats_map
Definition Statistics.h:307
SummaryStatisticsSP GetSummaryStatisticsForProvider(lldb_private::TypeSummaryImpl &provider)
Get the SummaryStatistics object for a given provider name, or insert if statistics for that provider...
Definition Statistics.h:289
SummaryInvocation & operator=(const SummaryInvocation &)=delete
SummaryInvocation(const SummaryInvocation &)=delete
Delete the copy constructor and assignment operator to prevent accidental double counting.
SummaryInvocation(SummaryStatisticsSP summary_stats)
Definition Statistics.h:258
A class that represents statistics about a TypeSummaryProviders invocations.
Definition Statistics.h:234
const std::string m_impl_type
Definition Statistics.h:278
llvm::json::Value ToJSON() const
std::string GetSummaryKindName() const
Definition Statistics.h:249
SummaryStatistics(std::string name, std::string impl_type)
Definition Statistics.h:236
std::atomic< uint64_t > m_count
Definition Statistics.h:280
std::string GetName() const
Definition Statistics.h:240
uint64_t GetSummaryCount() const
Definition Statistics.h:243
StatsDuration & GetDurationReference()
Definition Statistics.h:247
lldb_private::StatsDuration m_total_time
Definition Statistics.h:277
A class that represents statistics for a since lldb_private::Target.
Definition Statistics.h:312
void Reset(Target &target)
StatsSuccessFail m_frame_var
Definition Statistics.h:335
std::optional< StatsTimepoint > m_launch_or_attach_time
Definition Statistics.h:331
void CollectStats(Target &target)
StatsSuccessFail & GetFrameVariableStats()
Definition Statistics.h:326
llvm::json::Value ToJSON(Target &target, const lldb_private::StatisticsOptions &options)
StatsDuration m_create_time
Definition Statistics.h:330
std::optional< StatsTimepoint > m_first_public_stop_time
Definition Statistics.h:333
void IncreaseSourceRealpathAttemptCount(uint32_t count)
StatsDuration & GetCreateTime()
Definition Statistics.h:324
uint32_t m_source_realpath_compatible_count
Definition Statistics.h:339
StatsSuccessFail & GetExpressionStats()
Definition Statistics.h:325
StatsSuccessFail m_expr_eval
Definition Statistics.h:334
std::vector< intptr_t > m_module_identifiers
Definition Statistics.h:336
uint32_t m_source_realpath_attempt_count
Definition Statistics.h:338
void IncreaseSourceRealpathCompatibleCount(uint32_t count)
std::optional< StatsTimepoint > m_first_private_stop_time
Definition Statistics.h:332
virtual std::string GetName()=0
Get the name of the Type Summary Provider, either a C++ class, a summary string, or a script function...
virtual std::string GetSummaryKindName()
Get the name of the kind of Summary Provider, either c++, summary string, script or python.
A class that represents a running process on the host machine.
std::chrono::high_resolution_clock StatsClock
Definition Statistics.h:29
std::shared_ptr< SummaryStatistics > SummaryStatisticsSP
Definition Statistics.h:33
std::chrono::time_point< StatsClock > StatsTimepoint
Definition Statistics.h:30
ConstString::MemoryStats stats
Definition Statistics.h:180
llvm::json::Value ToJSON() const
Holds statistics about DWO (Debug With Object) files.
Definition Statistics.h:127
friend DWOStats operator+(DWOStats lhs, const DWOStats &rhs)
Definition Statistics.h:139
DWOStats & operator+=(const DWOStats &rhs)
Definition Statistics.h:132
uint32_t loaded_dwo_file_count
Definition Statistics.h:128
A class that represents statistics for a since lldb_private::Module.
Definition Statistics.h:146
llvm::json::Value ToJSON() const
llvm::StringMap< llvm::json::Value > type_system_stats
Definition Statistics.h:159
StatisticsMap symbol_locator_time
Definition Statistics.h:160
std::vector< intptr_t > symfile_modules
Definition Statistics.h:158
void SetIncludePlugins(bool value)
Definition Statistics.h:215
std::optional< bool > m_load_all_debug_info
Definition Statistics.h:225
void SetIncludeTranscript(bool value)
Definition Statistics.h:210
void SetSummaryOnly(bool value)
Definition Statistics.h:185
std::optional< bool > m_include_plugins
Definition Statistics.h:229
std::optional< bool > m_include_modules
Definition Statistics.h:227
std::optional< bool > m_include_transcript
Definition Statistics.h:228
void SetIncludeModules(bool value)
Definition Statistics.h:201
std::optional< bool > m_summary_only
Definition Statistics.h:224
std::optional< bool > m_include_targets
Definition Statistics.h:226
void SetLoadAllDebugInfo(bool value)
Definition Statistics.h:188
void SetIncludeTargets(bool value)
Definition Statistics.h:193
A class to count success/fail statistics.
Definition Statistics.h:114
StatsSuccessFail(llvm::StringRef n)
Definition Statistics.h:115
llvm::json::Value ToJSON() const