summaryrefslogtreecommitdiffstats
path: root/js/src/gc/SweepingAPI.h
blob: c9948d1118b435daee5b25843f0dc2d5fc1c4eaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef js_SweepingAPI_h
#define js_SweepingAPI_h

#include "mozilla/LinkedList.h"
#include "mozilla/Maybe.h"

#include "jstypes.h"

#include "js/GCAnnotations.h"
#include "js/GCHashTable.h"
#include "js/GCPolicyAPI.h"
#include "js/RootingAPI.h"

namespace js {
namespace gc {

JS_PUBLIC_API void LockStoreBuffer(JSRuntime* runtime);
JS_PUBLIC_API void UnlockStoreBuffer(JSRuntime* runtim);

class AutoLockStoreBuffer {
  JSRuntime* runtime;

 public:
  explicit AutoLockStoreBuffer(JSRuntime* runtime) : runtime(runtime) {
    LockStoreBuffer(runtime);
  }
  ~AutoLockStoreBuffer() { UnlockStoreBuffer(runtime); }
};

class WeakCacheBase;
JS_PUBLIC_API void RegisterWeakCache(JS::Zone* zone, WeakCacheBase* cachep);
JS_PUBLIC_API void RegisterWeakCache(JSRuntime* rt, WeakCacheBase* cachep);

class WeakCacheBase : public mozilla::LinkedListElement<WeakCacheBase> {
  WeakCacheBase() = delete;
  explicit WeakCacheBase(const WeakCacheBase&) = delete;

 public:
  enum NeedsLock : bool { LockStoreBuffer = true, DontLockStoreBuffer = false };

  explicit WeakCacheBase(JS::Zone* zone) { RegisterWeakCache(zone, this); }
  explicit WeakCacheBase(JSRuntime* rt) { RegisterWeakCache(rt, this); }
  WeakCacheBase(WeakCacheBase&& other) = default;
  virtual ~WeakCacheBase() = default;

  virtual size_t traceWeak(JSTracer* trc, NeedsLock needLock) = 0;

  // Sweeping will be skipped if the cache is empty already.
  virtual bool empty() = 0;

  // Enable/disable read barrier during incremental sweeping and set the tracer
  // to use.
  virtual bool setIncrementalBarrierTracer(JSTracer* trc) {
    // Derived classes do not support incremental barriers by default.
    return false;
  }
  virtual bool needsIncrementalBarrier() const {
    // Derived classes do not support incremental barriers by default.
    return false;
  }
};

}  // namespace gc

// A WeakCache stores the given Sweepable container and links itself into a
// list of such caches that are swept during each GC. A WeakCache can be
// specific to a zone, or across a whole runtime, depending on which
// constructor is used.
template <typename T>
class WeakCache : protected gc::WeakCacheBase,
                  public js::MutableWrappedPtrOperations<T, WeakCache<T>> {
  T cache;

 public:
  using Type = T;

  template <typename... Args>
  explicit WeakCache(Zone* zone, Args&&... args)
      : WeakCacheBase(zone), cache(std::forward<Args>(args)...) {}
  template <typename... Args>
  explicit WeakCache(JSRuntime* rt, Args&&... args)
      : WeakCacheBase(rt), cache(std::forward<Args>(args)...) {}

  const T& get() const { return cache; }
  T& get() { return cache; }

  size_t traceWeak(JSTracer* trc, NeedsLock needsLock) override {
    // Take the store buffer lock in case sweeping triggers any generational
    // post barriers. This is not always required and WeakCache specializations
    // may delay or skip taking the lock as appropriate.
    mozilla::Maybe<js::gc::AutoLockStoreBuffer> lock;
    if (needsLock) {
      lock.emplace(trc->runtime());
    }

    JS::GCPolicy<T>::traceWeak(trc, &cache);
    return 0;
  }

  bool empty() override { return cache.empty(); }
} JS_HAZ_NON_GC_POINTER;

// Specialize WeakCache for GCHashMap to provide a barriered map that does not
// need to be swept immediately.
template <typename Key, typename Value, typename HashPolicy,
          typename AllocPolicy, typename MapEntryGCPolicy>
class WeakCache<
    GCHashMap<Key, Value, HashPolicy, AllocPolicy, MapEntryGCPolicy>>
    final : protected gc::WeakCacheBase {
  using Map = GCHashMap<Key, Value, HashPolicy, AllocPolicy, MapEntryGCPolicy>;
  using Self = WeakCache<Map>;

  Map map;
  JSTracer* barrierTracer = nullptr;

 public:
  template <typename... Args>
  explicit WeakCache(Zone* zone, Args&&... args)
      : WeakCacheBase(zone), map(std::forward<Args>(args)...) {}
  template <typename... Args>
  explicit WeakCache(JSRuntime* rt, Args&&... args)
      : WeakCacheBase(rt), map(std::forward<Args>(args)...) {}
  ~WeakCache() { MOZ_ASSERT(!barrierTracer); }

  bool empty() override { return map.empty(); }

  size_t traceWeak(JSTracer* trc, NeedsLock needsLock) override {
    size_t steps = map.count();

    // Create an Enum and sweep the table entries.
    mozilla::Maybe<typename Map::Enum> e;
    e.emplace(map);
    map.traceWeakEntries(trc, e.ref());

    // Potentially take a lock while the Enum's destructor is called as this can
    // rehash/resize the table and access the store buffer.
    mozilla::Maybe<js::gc::AutoLockStoreBuffer> lock;
    if (needsLock) {
      lock.emplace(trc->runtime());
    }
    e.reset();

    return steps;
  }

  bool setIncrementalBarrierTracer(JSTracer* trc) override {
    MOZ_ASSERT(bool(barrierTracer) != bool(trc));
    barrierTracer = trc;
    return true;
  }

  bool needsIncrementalBarrier() const override { return barrierTracer; }

 private:
  using Entry = typename Map::Entry;

  static bool entryNeedsSweep(JSTracer* barrierTracer, const Entry& prior) {
    Key key(prior.key());
    Value value(prior.value());
    bool needsSweep = !MapEntryGCPolicy::traceWeak(barrierTracer, &key, &value);
    MOZ_ASSERT_IF(!needsSweep,
                  prior.key() == key);  // We shouldn't update here.
    MOZ_ASSERT_IF(!needsSweep,
                  prior.value() == value);  // We shouldn't update here.
    return needsSweep;
  }

 public:
  using Lookup = typename Map::Lookup;
  using Ptr = typename Map::Ptr;
  using AddPtr = typename Map::AddPtr;

  // Iterator over the whole collection.
  struct Range {
    explicit Range(Self& self) : cache(self), range(self.map.all()) {
      settle();
    }
    Range() = default;

    bool empty() const { return range.empty(); }
    const Entry& front() const { return range.front(); }

    void popFront() {
      range.popFront();
      settle();
    }

   private:
    Self& cache;
    typename Map::Range range;

    void settle() {
      if (JSTracer* trc = cache.barrierTracer) {
        while (!empty() && entryNeedsSweep(trc, front())) {
          popFront();
        }
      }
    }
  };

  struct Enum : public Map::Enum {
    explicit Enum(Self& cache) : Map::Enum(cache.map) {
      // This operation is not allowed while barriers are in place as we
      // may also need to enumerate the set for sweeping.
      MOZ_ASSERT(!cache.barrierTracer);
    }
  };

  Ptr lookup(const Lookup& l) const {
    Ptr ptr = map.lookup(l);
    if (barrierTracer && ptr && entryNeedsSweep(barrierTracer, *ptr)) {
      const_cast<Map&>(map).remove(ptr);
      return Ptr();
    }
    return ptr;
  }

  AddPtr lookupForAdd(const Lookup& l) {
    AddPtr ptr = map.lookupForAdd(l);
    if (barrierTracer && ptr && entryNeedsSweep(barrierTracer, *ptr)) {
      const_cast<Map&>(map).remove(ptr);
      return map.lookupForAdd(l);
    }
    return ptr;
  }

  Range all() const { return Range(*const_cast<Self*>(this)); }

  bool empty() const {
    // This operation is not currently allowed while barriers are in place
    // as it would require iterating the map and the caller expects a
    // constant time operation.
    MOZ_ASSERT(!barrierTracer);
    return map.empty();
  }

  uint32_t count() const {
    // This operation is not currently allowed while barriers are in place
    // as it would require iterating the set and the caller expects a
    // constant time operation.
    MOZ_ASSERT(!barrierTracer);
    return map.count();
  }

  size_t capacity() const { return map.capacity(); }

  bool has(const Lookup& l) const { return lookup(l).found(); }

  size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
    return map.sizeOfExcludingThis(mallocSizeOf);
  }
  size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
    return mallocSizeOf(this) + map.shallowSizeOfExcludingThis(mallocSizeOf);
  }

  void clear() {
    // This operation is not currently allowed while barriers are in place
    // since it doesn't make sense to clear a cache while it is being swept.
    MOZ_ASSERT(!barrierTracer);
    map.clear();
  }

  void clearAndCompact() {
    // This operation is not currently allowed while barriers are in place
    // since it doesn't make sense to clear a cache while it is being swept.
    MOZ_ASSERT(!barrierTracer);
    map.clearAndCompact();
  }

  void remove(Ptr p) {
    // This currently supports removing entries during incremental
    // sweeping. If we allow these tables to be swept incrementally this may
    // no longer be possible.
    map.remove(p);
  }

  void remove(const Lookup& l) {
    Ptr p = lookup(l);
    if (p) {
      remove(p);
    }
  }

  template <typename KeyInput, typename ValueInput>
  bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) {
    return map.add(p, std::forward<KeyInput>(k), std::forward<ValueInput>(v));
  }

  template <typename KeyInput, typename ValueInput>
  bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) {
    return map.relookupOrAdd(p, std::forward<KeyInput>(k),
                             std::forward<ValueInput>(v));
  }

  template <typename KeyInput, typename ValueInput>
  bool put(KeyInput&& k, ValueInput&& v) {
    return map.put(std::forward<KeyInput>(k), std::forward<ValueInput>(v));
  }

  template <typename KeyInput, typename ValueInput>
  bool putNew(KeyInput&& k, ValueInput&& v) {
    return map.putNew(std::forward<KeyInput>(k), std::forward<ValueInput>(v));
  }
} JS_HAZ_NON_GC_POINTER;

// Specialize WeakCache for GCHashSet to provide a barriered set that does not
// need to be swept immediately.
template <typename T, typename HashPolicy, typename AllocPolicy>
class WeakCache<GCHashSet<T, HashPolicy, AllocPolicy>> final
    : protected gc::WeakCacheBase {
  using Set = GCHashSet<T, HashPolicy, AllocPolicy>;
  using Self = WeakCache<Set>;

  Set set;
  JSTracer* barrierTracer = nullptr;

 public:
  using Entry = typename Set::Entry;

  template <typename... Args>
  explicit WeakCache(Zone* zone, Args&&... args)
      : WeakCacheBase(zone), set(std::forward<Args>(args)...) {}
  template <typename... Args>
  explicit WeakCache(JSRuntime* rt, Args&&... args)
      : WeakCacheBase(rt), set(std::forward<Args>(args)...) {}

  size_t traceWeak(JSTracer* trc, NeedsLock needsLock) override {
    size_t steps = set.count();

    // Create an Enum and sweep the table entries. It's not necessary to take
    // the store buffer lock yet.
    mozilla::Maybe<typename Set::Enum> e;
    e.emplace(set);
    set.traceWeakEntries(trc, e.ref());

    // Destroy the Enum, potentially rehashing or resizing the table. Since this
    // can access the store buffer, we need to take a lock for this if we're
    // called off main thread.
    mozilla::Maybe<js::gc::AutoLockStoreBuffer> lock;
    if (needsLock) {
      lock.emplace(trc->runtime());
    }
    e.reset();

    return steps;
  }

  bool empty() override { return set.empty(); }

  bool setIncrementalBarrierTracer(JSTracer* trc) override {
    MOZ_ASSERT(bool(barrierTracer) != bool(trc));
    barrierTracer = trc;
    return true;
  }

  bool needsIncrementalBarrier() const override { return barrierTracer; }

 private:
  static bool entryNeedsSweep(JSTracer* barrierTracer, const Entry& prior) {
    Entry entry(prior);
    bool needsSweep = !JS::GCPolicy<T>::traceWeak(barrierTracer, &entry);
    MOZ_ASSERT_IF(!needsSweep, prior == entry);  // We shouldn't update here.
    return needsSweep;
  }

 public:
  using Lookup = typename Set::Lookup;
  using Ptr = typename Set::Ptr;
  using AddPtr = typename Set::AddPtr;

  // Iterator over the whole collection.
  struct Range {
    explicit Range(Self& self) : cache(self), range(self.set.all()) {
      settle();
    }
    Range() = default;

    bool empty() const { return range.empty(); }
    const Entry& front() const { return range.front(); }

    void popFront() {
      range.popFront();
      settle();
    }

   private:
    Self& cache;
    typename Set::Range range;

    void settle() {
      if (JSTracer* trc = cache.barrierTracer) {
        while (!empty() && entryNeedsSweep(trc, front())) {
          popFront();
        }
      }
    }
  };

  struct Enum : public Set::Enum {
    explicit Enum(Self& cache) : Set::Enum(cache.set) {
      // This operation is not allowed while barriers are in place as we
      // may also need to enumerate the set for sweeping.
      MOZ_ASSERT(!cache.barrierTracer);
    }
  };

  Ptr lookup(const Lookup& l) const {
    Ptr ptr = set.lookup(l);
    if (barrierTracer && ptr && entryNeedsSweep(barrierTracer, *ptr)) {
      const_cast<Set&>(set).remove(ptr);
      return Ptr();
    }
    return ptr;
  }

  AddPtr lookupForAdd(const Lookup& l) {
    AddPtr ptr = set.lookupForAdd(l);
    if (barrierTracer && ptr && entryNeedsSweep(barrierTracer, *ptr)) {
      const_cast<Set&>(set).remove(ptr);
      return set.lookupForAdd(l);
    }
    return ptr;
  }

  Range all() const { return Range(*const_cast<Self*>(this)); }

  bool empty() const {
    // This operation is not currently allowed while barriers are in place
    // as it would require iterating the set and the caller expects a
    // constant time operation.
    MOZ_ASSERT(!barrierTracer);
    return set.empty();
  }

  uint32_t count() const {
    // This operation is not currently allowed while barriers are in place
    // as it would require iterating the set and the caller expects a
    // constant time operation.
    MOZ_ASSERT(!barrierTracer);
    return set.count();
  }

  size_t capacity() const { return set.capacity(); }

  bool has(const Lookup& l) const { return lookup(l).found(); }

  size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
    return set.shallowSizeOfExcludingThis(mallocSizeOf);
  }
  size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
    return mallocSizeOf(this) + set.shallowSizeOfExcludingThis(mallocSizeOf);
  }

  void clear() {
    // This operation is not currently allowed while barriers are in place
    // since it doesn't make sense to clear a cache while it is being swept.
    MOZ_ASSERT(!barrierTracer);
    set.clear();
  }

  void clearAndCompact() {
    // This operation is not currently allowed while barriers are in place
    // since it doesn't make sense to clear a cache while it is being swept.
    MOZ_ASSERT(!barrierTracer);
    set.clearAndCompact();
  }

  void remove(Ptr p) {
    // This currently supports removing entries during incremental
    // sweeping. If we allow these tables to be swept incrementally this may
    // no longer be possible.
    set.remove(p);
  }

  void remove(const Lookup& l) {
    Ptr p = lookup(l);
    if (p) {
      remove(p);
    }
  }

  template <typename TInput>
  void replaceKey(Ptr p, const Lookup& l, TInput&& newValue) {
    set.replaceKey(p, l, std::forward<TInput>(newValue));
  }

  template <typename TInput>
  bool add(AddPtr& p, TInput&& t) {
    return set.add(p, std::forward<TInput>(t));
  }

  template <typename TInput>
  bool relookupOrAdd(AddPtr& p, const Lookup& l, TInput&& t) {
    return set.relookupOrAdd(p, l, std::forward<TInput>(t));
  }

  template <typename TInput>
  bool put(TInput&& t) {
    return set.put(std::forward<TInput>(t));
  }

  template <typename TInput>
  bool putNew(TInput&& t) {
    return set.putNew(std::forward<TInput>(t));
  }

  template <typename TInput>
  bool putNew(const Lookup& l, TInput&& t) {
    return set.putNew(l, std::forward<TInput>(t));
  }
} JS_HAZ_NON_GC_POINTER;

}  // namespace js

#endif  // js_SweepingAPI_h