visitor.h 13.8 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef INCLUDE_CPPGC_VISITOR_H_
#define INCLUDE_CPPGC_VISITOR_H_

8
#include "cppgc/custom-space.h"
9
#include "cppgc/ephemeron-pair.h"
10 11 12 13 14
#include "cppgc/garbage-collected.h"
#include "cppgc/internal/logging.h"
#include "cppgc/internal/pointer-policies.h"
#include "cppgc/liveness-broker.h"
#include "cppgc/member.h"
15
#include "cppgc/sentinel-pointer.h"
16 17
#include "cppgc/source-location.h"
#include "cppgc/trace-trait.h"
18
#include "cppgc/type-traits.h"
19 20

namespace cppgc {
21

22
namespace internal {
23 24 25
template <typename T, typename WeaknessPolicy, typename LocationPolicy,
          typename CheckingPolicy>
class BasicCrossThreadPersistent;
26 27 28
template <typename T, typename WeaknessPolicy, typename LocationPolicy,
          typename CheckingPolicy>
class BasicPersistent;
29
class ConservativeTracingVisitor;
30
class VisitorBase;
31
class VisitorFactory;
32 33
}  // namespace internal

34 35 36 37
using WeakCallback = void (*)(const LivenessBroker&, const void*);

/**
 * Visitor passed to trace methods. All managed pointers must have called the
38 39 40 41 42 43 44 45 46 47 48 49 50 51
 * Visitor's trace method on them.
 *
 * \code
 * class Foo final : public GarbageCollected<Foo> {
 *  public:
 *   void Trace(Visitor* visitor) const {
 *     visitor->Trace(foo_);
 *     visitor->Trace(weak_foo_);
 *   }
 *  private:
 *   Member<Foo> foo_;
 *   WeakMember<Foo> weak_foo_;
 * };
 * \endcode
52
 */
53
class V8_EXPORT Visitor {
54
 public:
55 56 57 58 59 60 61 62
  class Key {
   private:
    Key() = default;
    friend class internal::VisitorFactory;
  };

  explicit Visitor(Key) {}

63 64
  virtual ~Visitor() = default;

65 66 67 68 69 70 71 72
  /**
   * Trace method for raw pointers. Prefer the versions for managed pointers.
   *
   * \param member Reference retaining an object.
   */
  template <typename T>
  void Trace(const T* t) {
    static_assert(sizeof(T), "Pointee type must be fully defined.");
73
    static_assert(internal::IsGarbageCollectedOrMixinType<T>::value,
74 75 76 77 78 79 80
                  "T must be GarbageCollected or GarbageCollectedMixin type");
    if (!t) {
      return;
    }
    Visit(t, TraceTrait<T>::GetTraceDescriptor(t));
  }

81 82 83 84 85
  /**
   * Trace method for Member.
   *
   * \param member Member reference retaining an object.
   */
86 87 88
  template <typename T>
  void Trace(const Member<T>& member) {
    const T* value = member.GetRawAtomic();
89
    CPPGC_DCHECK(value != kSentinelPointer);
90 91 92
    Trace(value);
  }

93 94 95 96 97
  /**
   * Trace method for WeakMember.
   *
   * \param weak_member WeakMember reference weakly retaining an object.
   */
98 99
  template <typename T>
  void Trace(const WeakMember<T>& weak_member) {
100
    static_assert(sizeof(T), "Pointee type must be fully defined.");
101
    static_assert(internal::IsGarbageCollectedOrMixinType<T>::value,
102
                  "T must be GarbageCollected or GarbageCollectedMixin type");
103 104
    static_assert(!internal::IsAllocatedOnCompactableSpace<T>::value,
                  "Weak references to compactable objects are not allowed");
105 106 107 108 109 110 111 112

    const T* value = weak_member.GetRawAtomic();

    // Bailout assumes that WeakMember emits write barrier.
    if (!value) {
      return;
    }

113
    CPPGC_DCHECK(value != kSentinelPointer);
114
    VisitWeak(value, TraceTrait<T>::GetTraceDescriptor(value),
115 116 117
              &HandleWeak<WeakMember<T>>, &weak_member);
  }

118 119 120 121 122 123
  /**
   * Trace method for inlined objects that are not allocated themselves but
   * otherwise follow managed heap layout and have a Trace() method.
   *
   * \param object reference of the inlined object.
   */
124 125 126 127 128 129 130 131 132 133 134 135
  template <typename T>
  void Trace(const T& object) {
#if V8_ENABLE_CHECKS
    // This object is embedded in potentially multiple nested objects. The
    // outermost object must not be in construction as such objects are (a) not
    // processed immediately, and (b) only processed conservatively if not
    // otherwise possible.
    CheckObjectNotInConstruction(&object);
#endif  // V8_ENABLE_CHECKS
    TraceTrait<T>::Trace(this, &object);
  }

136 137 138 139 140 141
  /**
   * Registers a weak callback method on the object of type T. See
   * LivenessBroker for an usage example.
   *
   * \param object of type T specifying a weak callback method.
   */
142
  template <typename T, void (T::*method)(const LivenessBroker&)>
143 144
  void RegisterWeakCallbackMethod(const T* object) {
    RegisterWeakCallback(&WeakCallbackMethodDelegate<T, method>, object);
145 146
  }

147 148 149 150 151 152 153 154
  /**
   * Trace method for EphemeronPair.
   *
   * \param ephemeron_pair EphemeronPair reference weakly retaining a key object
   * and strongly retaining a value object in case the key object is alive.
   */
  template <typename K, typename V>
  void Trace(const EphemeronPair<K, V>& ephemeron_pair) {
155
    TraceEphemeron(ephemeron_pair.key, &ephemeron_pair.value);
156 157 158
    RegisterWeakCallbackMethod<EphemeronPair<K, V>,
                               &EphemeronPair<K, V>::ClearValueIfKeyIsDead>(
        &ephemeron_pair);
159 160 161
  }

  /**
162 163
   * Trace method for a single ephemeron. Used for tracing a raw ephemeron in
   * which the `key` and `value` are kept separately.
164
   *
165 166
   * \param weak_member_key WeakMember reference weakly retaining a key object.
   * \param member_value Member reference with ephemeron semantics.
167
   */
168
  template <typename KeyType, typename ValueType>
169 170 171 172
  void TraceEphemeron(const WeakMember<KeyType>& weak_member_key,
                      const Member<ValueType>* member_value) {
    const KeyType* key = weak_member_key.GetRawAtomic();
    if (!key) return;
173 174

    // `value` must always be non-null.
175 176 177
    CPPGC_DCHECK(member_value);
    const ValueType* value = member_value->GetRawAtomic();
    if (!value) return;
178

179 180 181 182
    // KeyType and ValueType may refer to GarbageCollectedMixin.
    TraceDescriptor value_desc =
        TraceTrait<ValueType>::GetTraceDescriptor(value);
    CPPGC_DCHECK(value_desc.base_object_payload);
183
    const void* key_base_object_payload =
184
        TraceTrait<KeyType>::GetTraceDescriptor(key).base_object_payload;
185 186 187 188 189 190
    CPPGC_DCHECK(key_base_object_payload);

    VisitEphemeron(key_base_object_payload, value, value_desc);
  }

  /**
191 192 193
   * Trace method for a single ephemeron. Used for tracing a raw ephemeron in
   * which the `key` and `value` are kept separately. Note that this overload
   * is for non-GarbageCollected `value`s that can be traced though.
194
   *
195 196 197 198 199
   * \param key `WeakMember` reference weakly retaining a key object.
   * \param value Reference weakly retaining a value object. Note that
   *   `ValueType` here should not be `Member`. It is expected that
   *   `TraceTrait<ValueType>::GetTraceDescriptor(value)` returns a
   *   `TraceDescriptor` with a null base pointer but a valid trace method.
200 201
   */
  template <typename KeyType, typename ValueType>
202 203
  void TraceEphemeron(const WeakMember<KeyType>& weak_member_key,
                      const ValueType* value) {
204 205
    static_assert(!IsGarbageCollectedOrMixinTypeV<ValueType>,
                  "garbage-collected types must use WeakMember and Member");
206 207
    const KeyType* key = weak_member_key.GetRawAtomic();
    if (!key) return;
208 209 210

    // `value` must always be non-null.
    CPPGC_DCHECK(value);
211 212
    TraceDescriptor value_desc =
        TraceTrait<ValueType>::GetTraceDescriptor(value);
213 214 215 216
    // `value_desc.base_object_payload` must be null as this override is only
    // taken for non-garbage-collected values.
    CPPGC_DCHECK(!value_desc.base_object_payload);

217 218
    // KeyType might be a GarbageCollectedMixin.
    const void* key_base_object_payload =
219
        TraceTrait<KeyType>::GetTraceDescriptor(key).base_object_payload;
220
    CPPGC_DCHECK(key_base_object_payload);
221

222
    VisitEphemeron(key_base_object_payload, value, value_desc);
223 224
  }

225 226 227 228 229 230 231 232 233 234 235 236
  /**
   * Trace method that strongifies a WeakMember.
   *
   * \param weak_member WeakMember reference retaining an object.
   */
  template <typename T>
  void TraceStrongly(const WeakMember<T>& weak_member) {
    const T* value = weak_member.GetRawAtomic();
    CPPGC_DCHECK(value != kSentinelPointer);
    Trace(value);
  }

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  /**
   * Trace method for weak containers.
   *
   * \param object reference of the weak container.
   * \param callback to be invoked.
   * \param data custom data that is passed to the callback.
   */
  template <typename T>
  void TraceWeakContainer(const T* object, WeakCallback callback,
                          const void* data) {
    if (!object) return;
    VisitWeakContainer(object, TraceTrait<T>::GetTraceDescriptor(object),
                       TraceTrait<T>::GetWeakTraceDescriptor(object), callback,
                       data);
  }

253 254 255 256 257 258 259 260 261 262 263
  /**
   * Registers a slot containing a reference to an object allocated on a
   * compactable space. Such references maybe be arbitrarily moved by the GC.
   *
   * \param slot location of reference to object that might be moved by the GC.
   */
  template <typename T>
  void RegisterMovableReference(const T** slot) {
    static_assert(internal::IsAllocatedOnCompactableSpace<T>::value,
                  "Only references to objects allocated on compactable spaces "
                  "should be registered as movable slots.");
264
    static_assert(!IsGarbageCollectedMixinTypeV<T>,
265 266 267 268
                  "Mixin types do not support compaction.");
    HandleMovableReference(reinterpret_cast<const void**>(slot));
  }

269 270 271 272 273 274 275
  /**
   * Registers a weak callback that is invoked during garbage collection.
   *
   * \param callback to be invoked.
   * \param data custom data that is passed to the callback.
   */
  virtual void RegisterWeakCallback(WeakCallback callback, const void* data) {}
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  /**
   * Defers tracing an object from a concurrent thread to the mutator thread.
   * Should be called by Trace methods of types that are not safe to trace
   * concurrently.
   *
   * \param parameter tells the trace callback which object was deferred.
   * \param callback to be invoked for tracing on the mutator thread.
   * \param deferred_size size of deferred object.
   *
   * \returns false if the object does not need to be deferred (i.e. currently
   * traced on the mutator thread) and true otherwise (i.e. currently traced on
   * a concurrent thread).
   */
  virtual V8_WARN_UNUSED_RESULT bool DeferTraceToMutatorThreadIfConcurrent(
      const void* parameter, TraceCallback callback, size_t deferred_size) {
    // By default tracing is not deferred.
    return false;
  }

296
 protected:
297 298 299
  virtual void Visit(const void* self, TraceDescriptor) {}
  virtual void VisitWeak(const void* self, TraceDescriptor, WeakCallback,
                         const void* weak_member) {}
300
  virtual void VisitRoot(const void*, TraceDescriptor, const SourceLocation&) {}
301
  virtual void VisitWeakRoot(const void* self, TraceDescriptor, WeakCallback,
302
                             const void* weak_root, const SourceLocation&) {}
303 304
  virtual void VisitEphemeron(const void* key, const void* value,
                              TraceDescriptor value_desc) {}
305 306 307
  virtual void VisitWeakContainer(const void* self, TraceDescriptor strong_desc,
                                  TraceDescriptor weak_desc,
                                  WeakCallback callback, const void* data) {}
308
  virtual void HandleMovableReference(const void**) {}
309 310

 private:
311 312 313 314 315 316 317 318
  template <typename T, void (T::*method)(const LivenessBroker&)>
  static void WeakCallbackMethodDelegate(const LivenessBroker& info,
                                         const void* self) {
    // Callback is registered through a potential const Trace method but needs
    // to be able to modify fields. See HandleWeak.
    (const_cast<T*>(static_cast<const T*>(self))->*method)(info);
  }

319 320 321
  template <typename PointerType>
  static void HandleWeak(const LivenessBroker& info, const void* object) {
    const PointerType* weak = static_cast<const PointerType*>(object);
322
    auto* raw_ptr = weak->GetFromGC();
323
    // Sentinel values are preserved for weak pointers.
324 325
    if (raw_ptr == kSentinelPointer) return;
    if (!info.IsHeapObjectAlive(raw_ptr)) {
326
      weak->ClearFromGC();
327 328 329
    }
  }

330 331 332 333 334 335
  template <typename Persistent,
            std::enable_if_t<Persistent::IsStrongPersistent::value>* = nullptr>
  void TraceRoot(const Persistent& p, const SourceLocation& loc) {
    using PointeeType = typename Persistent::PointeeType;
    static_assert(sizeof(PointeeType),
                  "Persistent's pointee type must be fully defined");
336
    static_assert(internal::IsGarbageCollectedOrMixinType<PointeeType>::value,
337 338
                  "Persistent's pointee type must be GarbageCollected or "
                  "GarbageCollectedMixin");
339 340
    auto* ptr = p.GetFromGC();
    if (!ptr) {
341 342
      return;
    }
343
    VisitRoot(ptr, TraceTrait<PointeeType>::GetTraceDescriptor(ptr), loc);
344 345 346 347 348 349 350 351 352
  }

  template <
      typename WeakPersistent,
      std::enable_if_t<!WeakPersistent::IsStrongPersistent::value>* = nullptr>
  void TraceRoot(const WeakPersistent& p, const SourceLocation& loc) {
    using PointeeType = typename WeakPersistent::PointeeType;
    static_assert(sizeof(PointeeType),
                  "Persistent's pointee type must be fully defined");
353
    static_assert(internal::IsGarbageCollectedOrMixinType<PointeeType>::value,
354 355
                  "Persistent's pointee type must be GarbageCollected or "
                  "GarbageCollectedMixin");
356 357
    static_assert(!internal::IsAllocatedOnCompactableSpace<PointeeType>::value,
                  "Weak references to compactable objects are not allowed");
358 359
    auto* ptr = p.GetFromGC();
    VisitWeakRoot(ptr, TraceTrait<PointeeType>::GetTraceDescriptor(ptr),
360
                  &HandleWeak<WeakPersistent>, &p, loc);
361 362
  }

363
#if V8_ENABLE_CHECKS
364
  void CheckObjectNotInConstruction(const void* address);
365 366
#endif  // V8_ENABLE_CHECKS

367 368 369
  template <typename T, typename WeaknessPolicy, typename LocationPolicy,
            typename CheckingPolicy>
  friend class internal::BasicCrossThreadPersistent;
370 371 372
  template <typename T, typename WeaknessPolicy, typename LocationPolicy,
            typename CheckingPolicy>
  friend class internal::BasicPersistent;
373
  friend class internal::ConservativeTracingVisitor;
374
  friend class internal::VisitorBase;
375 376 377 378 379
};

}  // namespace cppgc

#endif  // INCLUDE_CPPGC_VISITOR_H_