1// Copyright 2014 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_COMPILER_ZONE_STATS_H_
6#define V8_COMPILER_ZONE_STATS_H_
7
8#include <map>
9#include <vector>
10
11#include "src/common/globals.h"
12#include "src/zone/zone.h"
13
14namespace v8 {
15namespace internal {
16namespace compiler {
17
18class V8_EXPORT_PRIVATE ZoneStats final {
19 public:
20  class V8_NODISCARD Scope final {
21   public:
22    explicit Scope(ZoneStats* zone_stats, const char* zone_name,
23                   bool support_zone_compression = false)
24        : zone_name_(zone_name),
25          zone_stats_(zone_stats),
26          zone_(nullptr),
27          support_zone_compression_(support_zone_compression) {}
28    ~Scope() { Destroy(); }
29
30    Scope(const Scope&) = delete;
31    Scope& operator=(const Scope&) = delete;
32
33    Zone* zone() {
34      if (zone_ == nullptr)
35        zone_ =
36            zone_stats_->NewEmptyZone(zone_name_, support_zone_compression_);
37      return zone_;
38    }
39    void Destroy() {
40      if (zone_ != nullptr) zone_stats_->ReturnZone(zone_);
41      zone_ = nullptr;
42    }
43
44    ZoneStats* zone_stats() const { return zone_stats_; }
45
46   private:
47    const char* zone_name_;
48    ZoneStats* const zone_stats_;
49    Zone* zone_;
50    const bool support_zone_compression_;
51  };
52
53  class V8_EXPORT_PRIVATE V8_NODISCARD StatsScope final {
54   public:
55    explicit StatsScope(ZoneStats* zone_stats);
56    ~StatsScope();
57    StatsScope(const StatsScope&) = delete;
58    StatsScope& operator=(const StatsScope&) = delete;
59
60    size_t GetMaxAllocatedBytes();
61    size_t GetCurrentAllocatedBytes();
62    size_t GetTotalAllocatedBytes();
63
64   private:
65    friend class ZoneStats;
66    void ZoneReturned(Zone* zone);
67
68    using InitialValues = std::map<Zone*, size_t>;
69
70    ZoneStats* const zone_stats_;
71    InitialValues initial_values_;
72    size_t total_allocated_bytes_at_start_;
73    size_t max_allocated_bytes_;
74  };
75
76  explicit ZoneStats(AccountingAllocator* allocator);
77  ~ZoneStats();
78  ZoneStats(const ZoneStats&) = delete;
79  ZoneStats& operator=(const ZoneStats&) = delete;
80
81  size_t GetMaxAllocatedBytes() const;
82  size_t GetTotalAllocatedBytes() const;
83  size_t GetCurrentAllocatedBytes() const;
84
85 private:
86  Zone* NewEmptyZone(const char* zone_name, bool support_zone_compression);
87  void ReturnZone(Zone* zone);
88
89  static const size_t kMaxUnusedSize = 3;
90  using Zones = std::vector<Zone*>;
91  using Stats = std::vector<StatsScope*>;
92
93  Zones zones_;
94  Stats stats_;
95  size_t max_allocated_bytes_;
96  size_t total_deleted_bytes_;
97  AccountingAllocator* allocator_;
98};
99
100}  // namespace compiler
101}  // namespace internal
102}  // namespace v8
103
104#endif  // V8_COMPILER_ZONE_STATS_H_
105