cpp

Coverage Report

Created: 2024-07-28 06:14

/home/uke/oil/mycpp/mark_sweep_heap.h
Line
Count
Source (jump to first uncovered line)
1
#ifndef MARKSWEEP_HEAP_H
2
#define MARKSWEEP_HEAP_H
3
4
#include <stdlib.h>
5
6
#include <vector>
7
8
#include "mycpp/common.h"
9
#include "mycpp/gc_obj.h"
10
11
class MarkSet {
12
 public:
13
27
  MarkSet() : bits_() {
14
27
  }
15
16
  // ReInit() must be called at the start of MarkObjects().  Allocate() should
17
  // keep track of the maximum object ID.
18
27
  void ReInit(int max_obj_id) {
19
    // https://stackoverflow.com/questions/8848575/fastest-way-to-reset-every-value-of-stdvectorint-to-0
20
27
    std::fill(bits_.begin(), bits_.end(), 0);
21
27
    int max_byte_index = (max_obj_id >> 3) + 1;  // round up
22
    // log("ReInit max_byte_index %d", max_byte_index);
23
27
    bits_.resize(max_byte_index);
24
27
  }
25
26
  // Called by MarkObjects()
27
0
  void Mark(int obj_id) {
28
0
    DCHECK(obj_id >= 0);
29
    // log("obj id %d", obj_id);
30
0
    DCHECK(!IsMarked(obj_id));
31
0
    int byte_index = obj_id >> 3;  // 8 bits per byte
32
0
    int bit_index = obj_id & 0b111;
33
    // log("byte_index %d %d", byte_index, bit_index);
34
0
    bits_[byte_index] |= (1 << bit_index);
35
0
  }
36
37
  // Called by Sweep()
38
9.32k
  bool IsMarked(int obj_id) {
39
9.32k
    DCHECK(obj_id >= 0);
40
0
    int byte_index = obj_id >> 3;
41
9.32k
    int bit_index = obj_id & 0b111;
42
9.32k
    return bits_[byte_index] & (1 << bit_index);
43
9.32k
  }
44
45
0
  void Debug() {
46
0
    int n = bits_.size();
47
0
    dprintf(2, "[ ");
48
0
    for (int i = 0; i < n; ++i) {
49
0
      dprintf(2, "%02x ", bits_[i]);
50
0
    }
51
0
    dprintf(2, "] (%d bytes) \n", n);
52
0
    dprintf(2, "[ ");
53
0
    int num_bits = 0;
54
0
    for (int i = 0; i < n; ++i) {
55
0
      for (int j = 0; j < 8; ++j) {
56
0
        int bit = (bits_[i] & (1 << j)) != 0;
57
0
        dprintf(2, "%d", bit);
58
0
        num_bits += bit;
59
0
      }
60
0
    }
61
0
    dprintf(2, " ] (%d bits set)\n", num_bits);
62
0
  }
63
64
  std::vector<uint8_t> bits_;  // bit vector indexed by obj_id
65
};
66
67
// A simple Pool allocator for allocating small objects. It maintains an ever
68
// growing number of Blocks each consisting of a number of fixed size Cells.
69
// Memory is handed out one Cell at a time.
70
// Note: within the context of the Pool allocator we refer to object IDs as cell
71
// IDs because in addition to identifying an object they're also used to index
72
// into the Cell storage.
73
template <int CellsPerBlock, size_t CellSize>
74
class Pool {
75
 public:
76
  static constexpr size_t kMaxObjSize = CellSize;
77
  static constexpr int kBlockSize = CellSize * CellsPerBlock;
78
79
18
  Pool() = default;
_ZN4PoolILi682ELm24EEC2Ev
Line
Count
Source
79
9
  Pool() = default;
_ZN4PoolILi341ELm48EEC2Ev
Line
Count
Source
79
9
  Pool() = default;
80
81
696
  void* Allocate(int* obj_id) {
82
696
    num_allocated_++;
83
84
696
    if (!free_list_) {
85
      // Allocate a new Block and add every new Cell to the free list.
86
18
      Block* block = static_cast<Block*>(malloc(sizeof(Block)));
87
18
      blocks_.push_back(block);
88
18
      bytes_allocated_ += kBlockSize;
89
18
      num_free_ += CellsPerBlock;
90
91
      // The starting cell_id for Cells in this block.
92
18
      int cell_id = (blocks_.size() - 1) * CellsPerBlock;
93
9.20k
      for (Cell& cell : block->cells) {
94
9.20k
        FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
95
9.20k
        free_cell->id = cell_id++;
96
9.20k
        free_cell->next = free_list_;
97
9.20k
        free_list_ = free_cell;
98
9.20k
      }
99
18
    }
100
101
696
    FreeCell* cell = free_list_;
102
696
    free_list_ = free_list_->next;
103
696
    num_free_--;
104
696
    *obj_id = cell->id;
105
696
    return cell;
106
696
  }
_ZN4PoolILi682ELm24EE8AllocateEPi
Line
Count
Source
81
443
  void* Allocate(int* obj_id) {
82
443
    num_allocated_++;
83
84
443
    if (!free_list_) {
85
      // Allocate a new Block and add every new Cell to the free list.
86
9
      Block* block = static_cast<Block*>(malloc(sizeof(Block)));
87
9
      blocks_.push_back(block);
88
9
      bytes_allocated_ += kBlockSize;
89
9
      num_free_ += CellsPerBlock;
90
91
      // The starting cell_id for Cells in this block.
92
9
      int cell_id = (blocks_.size() - 1) * CellsPerBlock;
93
6.13k
      for (Cell& cell : block->cells) {
94
6.13k
        FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
95
6.13k
        free_cell->id = cell_id++;
96
6.13k
        free_cell->next = free_list_;
97
6.13k
        free_list_ = free_cell;
98
6.13k
      }
99
9
    }
100
101
443
    FreeCell* cell = free_list_;
102
443
    free_list_ = free_list_->next;
103
443
    num_free_--;
104
443
    *obj_id = cell->id;
105
443
    return cell;
106
443
  }
_ZN4PoolILi341ELm48EE8AllocateEPi
Line
Count
Source
81
253
  void* Allocate(int* obj_id) {
82
253
    num_allocated_++;
83
84
253
    if (!free_list_) {
85
      // Allocate a new Block and add every new Cell to the free list.
86
9
      Block* block = static_cast<Block*>(malloc(sizeof(Block)));
87
9
      blocks_.push_back(block);
88
9
      bytes_allocated_ += kBlockSize;
89
9
      num_free_ += CellsPerBlock;
90
91
      // The starting cell_id for Cells in this block.
92
9
      int cell_id = (blocks_.size() - 1) * CellsPerBlock;
93
3.06k
      for (Cell& cell : block->cells) {
94
3.06k
        FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
95
3.06k
        free_cell->id = cell_id++;
96
3.06k
        free_cell->next = free_list_;
97
3.06k
        free_list_ = free_cell;
98
3.06k
      }
99
9
    }
100
101
253
    FreeCell* cell = free_list_;
102
253
    free_list_ = free_list_->next;
103
253
    num_free_--;
104
253
    *obj_id = cell->id;
105
253
    return cell;
106
253
  }
107
108
18
  void PrepareForGc() {
109
18
    DCHECK(!gc_underway_);
110
0
    gc_underway_ = true;
111
18
    mark_set_.ReInit(blocks_.size() * CellsPerBlock);
112
18
  }
_ZN4PoolILi682ELm24EE12PrepareForGcEv
Line
Count
Source
108
9
  void PrepareForGc() {
109
9
    DCHECK(!gc_underway_);
110
0
    gc_underway_ = true;
111
9
    mark_set_.ReInit(blocks_.size() * CellsPerBlock);
112
9
  }
_ZN4PoolILi341ELm48EE12PrepareForGcEv
Line
Count
Source
108
9
  void PrepareForGc() {
109
9
    DCHECK(!gc_underway_);
110
0
    gc_underway_ = true;
111
9
    mark_set_.ReInit(blocks_.size() * CellsPerBlock);
112
9
  }
113
114
0
  bool IsMarked(int cell_id) {
115
0
    DCHECK(gc_underway_);
116
0
    return mark_set_.IsMarked(cell_id);
117
0
  }
Unexecuted instantiation: _ZN4PoolILi682ELm24EE8IsMarkedEi
Unexecuted instantiation: _ZN4PoolILi341ELm48EE8IsMarkedEi
118
119
0
  void Mark(int cell_id) {
120
0
    DCHECK(gc_underway_);
121
0
    mark_set_.Mark(cell_id);
122
0
  }
Unexecuted instantiation: _ZN4PoolILi682ELm24EE4MarkEi
Unexecuted instantiation: _ZN4PoolILi341ELm48EE4MarkEi
123
124
18
  void Sweep() {
125
18
    DCHECK(gc_underway_);
126
    // Iterate over every Cell linking the free ones into a new free list.
127
0
    num_free_ = 0;
128
18
    free_list_ = nullptr;
129
18
    int cell_id = 0;
130
18
    for (Block* block : blocks_) {
131
9.20k
      for (Cell& cell : block->cells) {
132
9.20k
        if (!mark_set_.IsMarked(cell_id)) {
133
9.20k
          num_free_++;
134
9.20k
          FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
135
9.20k
          free_cell->id = cell_id;
136
9.20k
          free_cell->next = free_list_;
137
9.20k
          free_list_ = free_cell;
138
9.20k
        }
139
9.20k
        cell_id++;
140
9.20k
      }
141
18
    }
142
18
    gc_underway_ = false;
143
18
  }
_ZN4PoolILi682ELm24EE5SweepEv
Line
Count
Source
124
9
  void Sweep() {
125
9
    DCHECK(gc_underway_);
126
    // Iterate over every Cell linking the free ones into a new free list.
127
0
    num_free_ = 0;
128
9
    free_list_ = nullptr;
129
9
    int cell_id = 0;
130
9
    for (Block* block : blocks_) {
131
6.13k
      for (Cell& cell : block->cells) {
132
6.13k
        if (!mark_set_.IsMarked(cell_id)) {
133
6.13k
          num_free_++;
134
6.13k
          FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
135
6.13k
          free_cell->id = cell_id;
136
6.13k
          free_cell->next = free_list_;
137
6.13k
          free_list_ = free_cell;
138
6.13k
        }
139
6.13k
        cell_id++;
140
6.13k
      }
141
9
    }
142
9
    gc_underway_ = false;
143
9
  }
_ZN4PoolILi341ELm48EE5SweepEv
Line
Count
Source
124
9
  void Sweep() {
125
9
    DCHECK(gc_underway_);
126
    // Iterate over every Cell linking the free ones into a new free list.
127
0
    num_free_ = 0;
128
9
    free_list_ = nullptr;
129
9
    int cell_id = 0;
130
9
    for (Block* block : blocks_) {
131
3.06k
      for (Cell& cell : block->cells) {
132
3.06k
        if (!mark_set_.IsMarked(cell_id)) {
133
3.06k
          num_free_++;
134
3.06k
          FreeCell* free_cell = reinterpret_cast<FreeCell*>(cell);
135
3.06k
          free_cell->id = cell_id;
136
3.06k
          free_cell->next = free_list_;
137
3.06k
          free_list_ = free_cell;
138
3.06k
        }
139
3.06k
        cell_id++;
140
3.06k
      }
141
9
    }
142
9
    gc_underway_ = false;
143
9
  }
144
145
18
  void Free() {
146
18
    for (Block* block : blocks_) {
147
18
      free(block);
148
18
    }
149
18
    blocks_.clear();
150
18
  }
_ZN4PoolILi682ELm24EE4FreeEv
Line
Count
Source
145
9
  void Free() {
146
9
    for (Block* block : blocks_) {
147
9
      free(block);
148
9
    }
149
9
    blocks_.clear();
150
9
  }
_ZN4PoolILi341ELm48EE4FreeEv
Line
Count
Source
145
9
  void Free() {
146
9
    for (Block* block : blocks_) {
147
9
      free(block);
148
9
    }
149
9
    blocks_.clear();
150
9
  }
151
152
0
  int num_allocated() {
153
0
    return num_allocated_;
154
0
  }
Unexecuted instantiation: _ZN4PoolILi682ELm24EE13num_allocatedEv
Unexecuted instantiation: _ZN4PoolILi341ELm48EE13num_allocatedEv
155
156
0
  int64_t bytes_allocated() {
157
0
    return bytes_allocated_;
158
0
  }
Unexecuted instantiation: _ZN4PoolILi682ELm24EE15bytes_allocatedEv
Unexecuted instantiation: _ZN4PoolILi341ELm48EE15bytes_allocatedEv
159
160
54
  int num_live() {
161
54
    return blocks_.size() * CellsPerBlock - num_free_;
162
54
  }
_ZN4PoolILi682ELm24EE8num_liveEv
Line
Count
Source
160
27
  int num_live() {
161
27
    return blocks_.size() * CellsPerBlock - num_free_;
162
27
  }
_ZN4PoolILi341ELm48EE8num_liveEv
Line
Count
Source
160
27
  int num_live() {
161
27
    return blocks_.size() * CellsPerBlock - num_free_;
162
27
  }
163
164
 private:
165
  using Cell = uint8_t[CellSize];
166
167
  struct Block {
168
    Cell cells[CellsPerBlock];
169
  };
170
171
  // Unused/free cells are tracked via a linked list of FreeCells. The FreeCells
172
  // are stored in the unused Cells, so it takes no extra memory to track them.
173
  struct FreeCell {
174
    int id;
175
    FreeCell* next;
176
  };
177
  static_assert(CellSize >= sizeof(FreeCell), "CellSize is too small");
178
179
  // Whether a GC is underway, for asserting that calls are in order.
180
  bool gc_underway_ = false;
181
182
  FreeCell* free_list_ = nullptr;
183
  int num_free_ = 0;
184
  int num_allocated_ = 0;
185
  int64_t bytes_allocated_ = 0;
186
  std::vector<Block*> blocks_;
187
  MarkSet mark_set_;
188
189
  DISALLOW_COPY_AND_ASSIGN(Pool<CellsPerBlock COMMA CellSize>);
190
};
191
192
class MarkSweepHeap {
193
 public:
194
  // reserve 32 frames to start
195
9
  MarkSweepHeap() {
196
9
  }
197
198
  void Init();  // use default threshold
199
  void Init(int gc_threshold);
200
201
2
  void PushRoot(RawObject** p) {
202
2
    roots_.push_back(p);
203
2
  }
204
205
2
  void PopRoot() {
206
2
    roots_.pop_back();
207
2
  }
208
209
1
  void RootGlobalVar(void* root) {
210
1
    global_roots_.push_back(reinterpret_cast<RawObject*>(root));
211
1
  }
212
213
  void* Allocate(size_t num_bytes, int* obj_id, int* pool_id);
214
215
#if 0
216
  void* Reallocate(void* p, size_t num_bytes);
217
#endif
218
  int MaybeCollect();
219
  int Collect();
220
221
  void MaybeMarkAndPush(RawObject* obj);
222
  void TraceChildren();
223
224
  void Sweep();
225
226
  void PrintStats(int fd);  // public for testing
227
228
  void CleanProcessExit();  // do one last GC, used in unit tests
229
  void ProcessExit();       // main() lets OS clean up, except ASAN variant
230
231
27
  int num_live() {
232
27
    return num_live_
233
27
#ifndef NO_POOL_ALLOC
234
27
           + pool1_.num_live() + pool2_.num_live()
235
27
#endif
236
27
        ;
237
27
  }
238
239
  bool is_initialized_ = true;  // mark/sweep doesn't need to be initialized
240
241
  // Runtime params
242
243
  // Threshold is a number of live objects, since we aren't keeping track of
244
  // total bytes
245
  int gc_threshold_;
246
247
  // Show debug logging
248
  bool gc_verbose_ = false;
249
250
  // Current stats
251
  int num_live_ = 0;
252
  // Should we keep track of sizes?
253
  // int64_t bytes_live_ = 0;
254
255
  // Cumulative stats
256
  int max_survived_ = 0;  // max # live after a collection
257
  int num_allocated_ = 0;
258
  int64_t bytes_allocated_ = 0;  // avoid overflow
259
  int num_gc_points_ = 0;        // manual collection points
260
  int num_collections_ = 0;
261
  int num_growths_;
262
  double max_gc_millis_ = 0.0;
263
  double total_gc_millis_ = 0.0;
264
265
#ifndef NO_POOL_ALLOC
266
  // 16,384 / 24 bytes = 682 cells (rounded), 16,368 bytes
267
  // 16,384 / 48 bytes = 341 cells (rounded), 16,368 bytes
268
  // Conveniently, the glibc malloc header is 16 bytes, giving exactly 16 Ki
269
  // differences
270
  Pool<682, 24> pool1_;
271
  Pool<341, 48> pool2_;
272
#endif
273
274
  std::vector<RawObject**> roots_;
275
  std::vector<RawObject*> global_roots_;
276
277
  // Allocate() appends live objects, and Sweep() compacts it
278
  std::vector<ObjHeader*> live_objs_;
279
  // Allocate lazily frees these, and Sweep() replenishes it
280
  std::vector<ObjHeader*> to_free_;
281
282
  std::vector<ObjHeader*> gray_stack_;
283
  MarkSet mark_set_;
284
285
  int greatest_obj_id_ = 0;
286
287
 private:
288
  void FreeEverything();
289
  void MaybePrintStats();
290
291
  DISALLOW_COPY_AND_ASSIGN(MarkSweepHeap);
292
};
293
294
#endif  // MARKSWEEP_HEAP_H