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 
12 #include "lldb/Utility/ConstString.h"
13 #include "lldb/Utility/Stream.h"
14 #include "lldb/lldb-forward.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/Support/JSON.h"
17 #include <atomic>
18 #include <chrono>
19 #include <optional>
20 #include <ratio>
21 #include <string>
22 #include <vector>
23 
24 namespace lldb_private {
25 
26 using StatsClock = std::chrono::high_resolution_clock;
27 using StatsTimepoint = std::chrono::time_point<StatsClock>;
28 
29 class StatsDuration {
30 public:
31   using Duration = std::chrono::duration<double>;
32 
get()33   Duration get() const {
34     return Duration(InternalDuration(value.load(std::memory_order_relaxed)));
35   }
Duration()36   operator Duration() const { return get(); }
37 
38   StatsDuration &operator+=(Duration dur) {
39     value.fetch_add(std::chrono::duration_cast<InternalDuration>(dur).count(),
40                     std::memory_order_relaxed);
41     return *this;
42   }
43 
44 private:
45   using InternalDuration = std::chrono::duration<uint64_t, std::micro>;
46   std::atomic<uint64_t> value{0};
47 };
48 
49 /// A class that measures elapsed time in an exception safe way.
50 ///
51 /// This is a RAII class is designed to help gather timing statistics within
52 /// LLDB where objects have optional Duration variables that get updated with
53 /// elapsed times. This helps LLDB measure statistics for many things that are
54 /// then reported in LLDB commands.
55 ///
56 /// Objects that need to measure elapsed times should have a variable of type
57 /// "StatsDuration m_time_xxx;" which can then be used in the constructor of
58 /// this class inside a scope that wants to measure something:
59 ///
60 ///   ElapsedTime elapsed(m_time_xxx);
61 ///   // Do some work
62 ///
63 /// This class will increment the m_time_xxx variable with the elapsed time
64 /// when the object goes out of scope. The "m_time_xxx" variable will be
65 /// incremented when the class goes out of scope. This allows a variable to
66 /// measure something that might happen in stages at different times, like
67 /// resolving a breakpoint each time a new shared library is loaded.
68 class ElapsedTime {
69 public:
70   /// Set to the start time when the object is created.
71   StatsTimepoint m_start_time;
72   /// Elapsed time in seconds to increment when this object goes out of scope.
73   StatsDuration &m_elapsed_time;
74 
75 public:
ElapsedTime(StatsDuration & opt_time)76   ElapsedTime(StatsDuration &opt_time) : m_elapsed_time(opt_time) {
77     m_start_time = StatsClock::now();
78   }
~ElapsedTime()79   ~ElapsedTime() {
80     StatsClock::duration elapsed = StatsClock::now() - m_start_time;
81     m_elapsed_time += elapsed;
82   }
83 };
84 
85 /// A class to count success/fail statistics.
86 struct StatsSuccessFail {
StatsSuccessFailStatsSuccessFail87   StatsSuccessFail(llvm::StringRef n) : name(n.str()) {}
88 
NotifySuccessStatsSuccessFail89   void NotifySuccess() { ++successes; }
NotifyFailureStatsSuccessFail90   void NotifyFailure() { ++failures; }
91 
92   llvm::json::Value ToJSON() const;
93   std::string name;
94   uint32_t successes = 0;
95   uint32_t failures = 0;
96 };
97 
98 /// A class that represents statistics for a since lldb_private::Module.
99 struct ModuleStats {
100   llvm::json::Value ToJSON() const;
101   intptr_t identifier;
102   std::string path;
103   std::string uuid;
104   std::string triple;
105   // Path separate debug info file, or empty if none.
106   std::string symfile_path;
107   // If the debug info is contained in multiple files where each one is
108   // represented as a separate lldb_private::Module, then these are the
109   // identifiers of these modules in the global module list. This allows us to
110   // track down all of the stats that contribute to this module.
111   std::vector<intptr_t> symfile_modules;
112   llvm::StringMap<llvm::json::Value> type_system_stats;
113   double symtab_parse_time = 0.0;
114   double symtab_index_time = 0.0;
115   double debug_parse_time = 0.0;
116   double debug_index_time = 0.0;
117   uint64_t debug_info_size = 0;
118   bool symtab_loaded_from_cache = false;
119   bool symtab_saved_to_cache = false;
120   bool debug_info_index_loaded_from_cache = false;
121   bool debug_info_index_saved_to_cache = false;
122   bool debug_info_enabled = true;
123   bool symtab_stripped = false;
124   bool debug_info_had_variable_errors = false;
125   bool debug_info_had_incomplete_types = false;
126 };
127 
128 struct ConstStringStats {
129   llvm::json::Value ToJSON() const;
130   ConstString::MemoryStats stats = ConstString::GetMemoryStats();
131 };
132 
133 struct StatisticsOptions {
134   bool summary_only = false;
135   bool load_all_debug_info = false;
136 };
137 
138 /// A class that represents statistics for a since lldb_private::Target.
139 class TargetStats {
140 public:
141   llvm::json::Value ToJSON(Target &target,
142                            const lldb_private::StatisticsOptions &options);
143 
144   void SetLaunchOrAttachTime();
145   void SetFirstPrivateStopTime();
146   void SetFirstPublicStopTime();
147   void IncreaseSourceMapDeduceCount();
148 
GetCreateTime()149   StatsDuration &GetCreateTime() { return m_create_time; }
GetExpressionStats()150   StatsSuccessFail &GetExpressionStats() { return m_expr_eval; }
GetFrameVariableStats()151   StatsSuccessFail &GetFrameVariableStats() { return m_frame_var; }
152 
153 protected:
154   StatsDuration m_create_time;
155   std::optional<StatsTimepoint> m_launch_or_attach_time;
156   std::optional<StatsTimepoint> m_first_private_stop_time;
157   std::optional<StatsTimepoint> m_first_public_stop_time;
158   StatsSuccessFail m_expr_eval{"expressionEvaluation"};
159   StatsSuccessFail m_frame_var{"frameVariable"};
160   std::vector<intptr_t> m_module_identifiers;
161   uint32_t m_source_map_deduce_count = 0;
162   void CollectStats(Target &target);
163 };
164 
165 class DebuggerStats {
166 public:
SetCollectingStats(bool enable)167   static void SetCollectingStats(bool enable) { g_collecting_stats = enable; }
GetCollectingStats()168   static bool GetCollectingStats() { return g_collecting_stats; }
169 
170   /// Get metrics associated with one or all targets in a debugger in JSON
171   /// format.
172   ///
173   /// \param debugger
174   ///   The debugger to get the target list from if \a target is NULL.
175   ///
176   /// \param target
177   ///   The single target to emit statistics for if non NULL, otherwise dump
178   ///   statistics only for the specified target.
179   ///
180   /// \param summary_only
181   ///   If true, only report high level summary statistics without
182   ///   targets/modules/breakpoints etc.. details.
183   ///
184   /// \return
185   ///     Returns a JSON value that contains all target metrics.
186   static llvm::json::Value
187   ReportStatistics(Debugger &debugger, Target *target,
188                    const lldb_private::StatisticsOptions &options);
189 
190 protected:
191   // Collecting stats can be set to true to collect stats that are expensive
192   // to collect. By default all stats that are cheap to collect are enabled.
193   // This settings is here to maintain compatibility with "statistics enable"
194   // and "statistics disable".
195   static bool g_collecting_stats;
196 };
197 
198 } // namespace lldb_private
199 
200 #endif // LLDB_TARGET_STATISTICS_H
201