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