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/DataFormatters/TypeSummary.h" 13 #include "lldb/Utility/ConstString.h" 14 #include "lldb/Utility/RealpathPrefixes.h" 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 27 namespace lldb_private { 28 29 using StatsClock = std::chrono::high_resolution_clock; 30 using StatsTimepoint = std::chrono::time_point<StatsClock>; 31 class SummaryStatistics; 32 // Declaring here as there is no private forward 33 typedef std::shared_ptr<SummaryStatistics> SummaryStatisticsSP; 34 35 class StatsDuration { 36 public: 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 46 StatsDuration &operator+=(Duration dur) { 47 value.fetch_add(std::chrono::duration_cast<InternalDuration>(dur).count(), 48 std::memory_order_relaxed); 49 return *this; 50 } 51 52 private: 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. 76 class ElapsedTime { 77 public: 78 /// Set to the start time when the object is created. 79 StatsTimepoint m_start_time; 80 /// Elapsed time in seconds to increment when this object goes out of scope. 81 StatsDuration &m_elapsed_time; 82 83 public: 84 ElapsedTime(StatsDuration &opt_time) : m_elapsed_time(opt_time) { 85 m_start_time = StatsClock::now(); 86 } 87 ~ElapsedTime() { 88 StatsClock::duration elapsed = StatsClock::now() - m_start_time; 89 m_elapsed_time += elapsed; 90 } 91 }; 92 93 /// A class to count success/fail statistics. 94 struct StatsSuccessFail { 95 StatsSuccessFail(llvm::StringRef n) : name(n.str()) {} 96 97 void NotifySuccess() { ++successes; } 98 void NotifyFailure() { ++failures; } 99 100 llvm::json::Value ToJSON() const; 101 std::string name; 102 uint32_t successes = 0; 103 uint32_t failures = 0; 104 }; 105 106 /// A class that represents statistics for a since lldb_private::Module. 107 struct ModuleStats { 108 llvm::json::Value ToJSON() const; 109 intptr_t identifier; 110 std::string path; 111 std::string uuid; 112 std::string triple; 113 // Path separate debug info file, or empty if none. 114 std::string symfile_path; 115 // If the debug info is contained in multiple files where each one is 116 // represented as a separate lldb_private::Module, then these are the 117 // identifiers of these modules in the global module list. This allows us to 118 // track down all of the stats that contribute to this module. 119 std::vector<intptr_t> symfile_modules; 120 llvm::StringMap<llvm::json::Value> type_system_stats; 121 double symtab_parse_time = 0.0; 122 double symtab_index_time = 0.0; 123 double debug_parse_time = 0.0; 124 double debug_index_time = 0.0; 125 uint64_t debug_info_size = 0; 126 bool symtab_loaded_from_cache = false; 127 bool symtab_saved_to_cache = false; 128 bool debug_info_index_loaded_from_cache = false; 129 bool debug_info_index_saved_to_cache = false; 130 bool debug_info_enabled = true; 131 bool symtab_stripped = false; 132 bool debug_info_had_variable_errors = false; 133 bool debug_info_had_incomplete_types = false; 134 }; 135 136 struct ConstStringStats { 137 llvm::json::Value ToJSON() const; 138 ConstString::MemoryStats stats = ConstString::GetMemoryStats(); 139 }; 140 141 struct StatisticsOptions { 142 public: 143 void SetSummaryOnly(bool value) { m_summary_only = value; } 144 bool GetSummaryOnly() const { return m_summary_only.value_or(false); } 145 146 void SetLoadAllDebugInfo(bool value) { m_load_all_debug_info = value; } 147 bool GetLoadAllDebugInfo() const { 148 return m_load_all_debug_info.value_or(false); 149 } 150 151 void SetIncludeTargets(bool value) { m_include_targets = value; } 152 bool GetIncludeTargets() const { 153 if (m_include_targets.has_value()) 154 return m_include_targets.value(); 155 // Default to true in both default mode and summary mode. 156 return true; 157 } 158 159 void SetIncludeModules(bool value) { m_include_modules = value; } 160 bool GetIncludeModules() const { 161 if (m_include_modules.has_value()) 162 return m_include_modules.value(); 163 // `m_include_modules` has no value set, so return a value based on 164 // `m_summary_only`. 165 return !GetSummaryOnly(); 166 } 167 168 void SetIncludeTranscript(bool value) { m_include_transcript = value; } 169 bool GetIncludeTranscript() const { 170 if (m_include_transcript.has_value()) 171 return m_include_transcript.value(); 172 // `m_include_transcript` has no value set, so return a value based on 173 // `m_summary_only`. 174 return !GetSummaryOnly(); 175 } 176 177 private: 178 std::optional<bool> m_summary_only; 179 std::optional<bool> m_load_all_debug_info; 180 std::optional<bool> m_include_targets; 181 std::optional<bool> m_include_modules; 182 std::optional<bool> m_include_transcript; 183 }; 184 185 /// A class that represents statistics about a TypeSummaryProviders invocations 186 /// \note All members of this class need to be accessed in a thread safe manner 187 class SummaryStatistics { 188 public: 189 explicit SummaryStatistics(std::string name, std::string impl_type) 190 : m_total_time(), m_impl_type(std::move(impl_type)), 191 m_name(std::move(name)), m_count(0) {} 192 193 std::string GetName() const { return m_name; }; 194 double GetTotalTime() const { return m_total_time.get().count(); } 195 196 uint64_t GetSummaryCount() const { 197 return m_count.load(std::memory_order_relaxed); 198 } 199 200 StatsDuration &GetDurationReference() { return m_total_time; }; 201 202 std::string GetSummaryKindName() const { return m_impl_type; } 203 204 llvm::json::Value ToJSON() const; 205 206 void Reset() { m_total_time.reset(); } 207 208 /// Basic RAII class to increment the summary count when the call is complete. 209 class SummaryInvocation { 210 public: 211 SummaryInvocation(SummaryStatisticsSP summary_stats) 212 : m_stats(summary_stats), 213 m_elapsed_time(summary_stats->GetDurationReference()) {} 214 ~SummaryInvocation() { m_stats->OnInvoked(); } 215 216 /// Delete the copy constructor and assignment operator to prevent 217 /// accidental double counting. 218 /// @{ 219 SummaryInvocation(const SummaryInvocation &) = delete; 220 SummaryInvocation &operator=(const SummaryInvocation &) = delete; 221 /// @} 222 223 private: 224 SummaryStatisticsSP m_stats; 225 ElapsedTime m_elapsed_time; 226 }; 227 228 private: 229 void OnInvoked() noexcept { m_count.fetch_add(1, std::memory_order_relaxed); } 230 lldb_private::StatsDuration m_total_time; 231 const std::string m_impl_type; 232 const std::string m_name; 233 std::atomic<uint64_t> m_count; 234 }; 235 236 /// A class that wraps a std::map of SummaryStatistics objects behind a mutex. 237 class SummaryStatisticsCache { 238 public: 239 /// Get the SummaryStatistics object for a given provider name, or insert 240 /// if statistics for that provider is not in the map. 241 SummaryStatisticsSP 242 GetSummaryStatisticsForProvider(lldb_private::TypeSummaryImpl &provider) { 243 std::lock_guard<std::mutex> guard(m_map_mutex); 244 if (auto iterator = m_summary_stats_map.find(provider.GetName()); 245 iterator != m_summary_stats_map.end()) 246 return iterator->second; 247 248 auto it = m_summary_stats_map.try_emplace( 249 provider.GetName(), 250 std::make_shared<SummaryStatistics>(provider.GetName(), 251 provider.GetSummaryKindName())); 252 return it.first->second; 253 } 254 255 llvm::json::Value ToJSON(); 256 257 void Reset(); 258 259 private: 260 llvm::StringMap<SummaryStatisticsSP> m_summary_stats_map; 261 std::mutex m_map_mutex; 262 }; 263 264 /// A class that represents statistics for a since lldb_private::Target. 265 class TargetStats { 266 public: 267 llvm::json::Value ToJSON(Target &target, 268 const lldb_private::StatisticsOptions &options); 269 270 void SetLaunchOrAttachTime(); 271 void SetFirstPrivateStopTime(); 272 void SetFirstPublicStopTime(); 273 void IncreaseSourceMapDeduceCount(); 274 void IncreaseSourceRealpathAttemptCount(uint32_t count); 275 void IncreaseSourceRealpathCompatibleCount(uint32_t count); 276 277 StatsDuration &GetCreateTime() { return m_create_time; } 278 StatsSuccessFail &GetExpressionStats() { return m_expr_eval; } 279 StatsSuccessFail &GetFrameVariableStats() { return m_frame_var; } 280 void Reset(Target &target); 281 282 protected: 283 StatsDuration m_create_time; 284 std::optional<StatsTimepoint> m_launch_or_attach_time; 285 std::optional<StatsTimepoint> m_first_private_stop_time; 286 std::optional<StatsTimepoint> m_first_public_stop_time; 287 StatsSuccessFail m_expr_eval{"expressionEvaluation"}; 288 StatsSuccessFail m_frame_var{"frameVariable"}; 289 std::vector<intptr_t> m_module_identifiers; 290 uint32_t m_source_map_deduce_count = 0; 291 uint32_t m_source_realpath_attempt_count = 0; 292 uint32_t m_source_realpath_compatible_count = 0; 293 void CollectStats(Target &target); 294 }; 295 296 class DebuggerStats { 297 public: 298 static void SetCollectingStats(bool enable) { g_collecting_stats = enable; } 299 static bool GetCollectingStats() { return g_collecting_stats; } 300 301 /// Get metrics associated with one or all targets in a debugger in JSON 302 /// format. 303 /// 304 /// \param debugger 305 /// The debugger to get the target list from if \a target is NULL. 306 /// 307 /// \param target 308 /// The single target to emit statistics for if non NULL, otherwise dump 309 /// statistics only for the specified target. 310 /// 311 /// \param summary_only 312 /// If true, only report high level summary statistics without 313 /// targets/modules/breakpoints etc.. details. 314 /// 315 /// \return 316 /// Returns a JSON value that contains all target metrics. 317 static llvm::json::Value 318 ReportStatistics(Debugger &debugger, Target *target, 319 const lldb_private::StatisticsOptions &options); 320 321 /// Reset metrics associated with one or all targets in a debugger. 322 /// 323 /// \param debugger 324 /// The debugger to reset the target list from if \a target is NULL. 325 /// 326 /// \param target 327 /// The target to reset statistics for, or if null, reset statistics 328 /// for all targets 329 static void ResetStatistics(Debugger &debugger, Target *target); 330 331 protected: 332 // Collecting stats can be set to true to collect stats that are expensive 333 // to collect. By default all stats that are cheap to collect are enabled. 334 // This settings is here to maintain compatibility with "statistics enable" 335 // and "statistics disable". 336 static bool g_collecting_stats; 337 }; 338 339 } // namespace lldb_private 340 341 #endif // LLDB_TARGET_STATISTICS_H 342