Debian Codegraph @

js/src/gc/Cell.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef gc_Cell_h
8 #define gc_Cell_h
9
10 #include "mozilla/Atomics.h"
11 #include "mozilla/EndianUtils.h"
12
13 #include <type_traits>
14
15 #include "gc/GCContext.h"
16 #include "gc/Heap.h"
17 #include "gc/TraceKind.h"
18 #include "js/GCAnnotations.h"
19 #include "js/shadow/Zone.h" // JS::shadow::Zone
20 #include "js/TypeDecls.h"
21
22 namespace JS {
23 enum class TraceKind;
24 } /* namespace JS */
25
26 namespace js {
27
28 class JS_PUBLIC_API GenericPrinter;
29
30 extern bool RuntimeFromMainThreadIsHeapMajorCollecting(
31 JS::shadow::Zone* shadowZone);
32
33 #ifdef DEBUG
34 // Barriers can't be triggered during offthread baseline or Ion
35 // compilation, which may run on a helper thread.
36 extern bool CurrentThreadIsBaselineCompiling();
37 extern bool CurrentThreadIsIonCompiling();
38 extern bool CurrentThreadIsOffThreadCompiling();
39 #endif
40
41 extern void TraceManuallyBarrieredGenericPointerEdge(JSTracer* trc,
42 gc::Cell** thingp,
43 const char* name);
44
45 namespace gc {
46
47 enum class AllocKind : uint8_t;
48 class CellAllocator; // Declared so subtypes of Cell can friend it easily.
49 class StoreBuffer;
50 class TenuredCell;
51
52 extern void PerformIncrementalReadBarrier(TenuredCell* cell);
53 extern void PerformIncrementalPreWriteBarrier(TenuredCell* cell);
54 extern void PerformIncrementalBarrierDuringFlattening(JSString* str);
55 extern void UnmarkGrayGCThingRecursively(TenuredCell* cell);
56
57 // Like gc::MarkColor but allows the possibility of the cell being unmarked.
58 enum class CellColor : uint8_t { White = 0, Gray = 1, Black = 2 };
59 static_assert(uint8_t(CellColor::Gray) == uint8_t(MarkColor::Gray));
60 static_assert(uint8_t(CellColor::Black) == uint8_t(MarkColor::Black));
61
62 inline bool IsMarked(CellColor color) { return color != CellColor::White; }
63 inline MarkColor AsMarkColor(CellColor color) {
64 MOZ_ASSERT(IsMarked(color));
65 return MarkColor(color);
66 }
67 inline CellColor AsCellColor(MarkColor color) { return CellColor(color); }
68 extern const char* CellColorName(CellColor color);
69
70 // Cell header word. Stores GC flags and derived class data.
71 //
72 // Loads of GC flags + all stores are marked as (relaxed) atomic operations,
73 // to deal with the following benign data race during compacting GC:
74 //
75 // - Thread 1 checks isForwarded (which is always false in this situation).
76 // - Thread 2 updates the derived class data (without changing the forwarded
77 // flag).
78 //
79 // To improve performance, we don't use atomic operations for get() because
80 // atomic operations inhibit certain compiler optimizations: GCC and Clang are
81 // unable to fold multiple loads even if they're both relaxed atomics. This is
82 // especially a problem for chained loads such as obj->shape->base->clasp.
83 class HeaderWord {
84 // Indicates whether the cell has been forwarded (moved) by generational or
85 // compacting GC and is now a RelocationOverlay.
86 static constexpr uintptr_t FORWARD_BIT = Bit(0);
87 // Bits 1 and 2 are reserved for future use by the GC.
88
89 uintptr_t value_;
90
91 void setAtomic(uintptr_t value) {
92 __atomic_store_n(&value_, value, __ATOMIC_RELAXED);
93 }
94
95 public:
96 static constexpr uintptr_t RESERVED_MASK =
97 BitMask(gc::CellFlagBitsReservedForGC);
98 static_assert(gc::CellFlagBitsReservedForGC >= 3,
99 "Not enough flag bits reserved for GC");
100
101 uintptr_t getAtomic() const {
102 return __atomic_load_n(&value_, __ATOMIC_RELAXED);
103 }
104
105 // Accessors for derived class data.
106 uintptr_t get() const {
107 // Note: non-atomic load. See class comment.
108 uintptr_t value = value_;
109 MOZ_ASSERT((value & RESERVED_MASK) == 0);
110 return value;
111 }
112 void set(uintptr_t value) {
113 MOZ_ASSERT((value & RESERVED_MASK) == 0);
114 setAtomic(value);
115 }
116
117 // Accessors for GC data.
118 uintptr_t flags() const { return getAtomic() & RESERVED_MASK; }
119 bool isForwarded() const { return flags() & FORWARD_BIT; }
120 void setForwardingAddress(uintptr_t ptr) {
121 MOZ_ASSERT((ptr & RESERVED_MASK) == 0);
122 setAtomic(ptr | FORWARD_BIT);
123 }
124 uintptr_t getForwardingAddress() const {
125 MOZ_ASSERT(isForwarded());
126 return getAtomic() & ~RESERVED_MASK;
127 }
128 };
129
130 // [SMDOC] GC Cell
131 //
132 // A GC cell is the ultimate base class for all GC things. All types allocated
133 // on the GC heap extend either gc::Cell or gc::TenuredCell. If a type is always
134 // tenured, prefer the TenuredCell class as base.
135 //
136 // The first word of Cell is a HeaderWord (a uintptr_t) that reserves the low
137 // three bits for GC purposes. The remaining bits are available to sub-classes
138 // and can be used store a pointer to another gc::Cell. To make use of the
139 // remaining space, sub-classes derive from a helper class such as
140 // TenuredCellWithNonGCPointer.
141 //
142 // During moving GC operation a Cell may be marked as forwarded. This indicates
143 // that a gc::RelocationOverlay is currently stored in the Cell's memory and
144 // should be used to find the new location of the Cell.
145 struct Cell {
146 // Cell header word. Stores GC flags and derived class data.
147 HeaderWord header_;
148
149 public:
150 Cell() = default;
151
152 Cell(const Cell&) = delete;
153 void operator=(const Cell&) = delete;
154
155 bool isForwarded() const { return header_.isForwarded(); }
156 uintptr_t flags() const { return header_.flags(); }
157
158 MOZ_ALWAYS_INLINE bool isTenured() const { return !IsInsideNursery(this); }
159 MOZ_ALWAYS_INLINE const TenuredCell& asTenured() const;
160 MOZ_ALWAYS_INLINE TenuredCell& asTenured();
161
162 MOZ_ALWAYS_INLINE bool isMarkedAny() const;
163 MOZ_ALWAYS_INLINE bool isMarkedBlack() const;
164 MOZ_ALWAYS_INLINE bool isMarkedGray() const;
165 MOZ_ALWAYS_INLINE bool isMarked(gc::MarkColor color) const;
166 MOZ_ALWAYS_INLINE bool isMarkedAtLeast(gc::MarkColor color) const;
167 MOZ_ALWAYS_INLINE CellColor color() const;
168
169 inline JSRuntime* runtimeFromMainThread() const;
170
171 // Note: Unrestricted access to the runtime of a GC thing from an arbitrary
172 // thread can easily lead to races. Use this method very carefully.
173 inline JSRuntime* runtimeFromAnyThread() const;
174
175 // May be overridden by GC thing kinds that have a compartment pointer.
176 inline JS::Compartment* maybeCompartment() const { return nullptr; }
177
178 // The StoreBuffer used to record incoming pointers from the tenured heap.
179 // This will return nullptr for a tenured cell.
180 inline StoreBuffer* storeBuffer() const;
181
182 inline JS::TraceKind getTraceKind() const;
183
184 static MOZ_ALWAYS_INLINE bool needPreWriteBarrier(JS::Zone* zone);
185
186 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
187 inline bool is() const {
188 return getTraceKind() == JS::MapTypeToTraceKind<T>::kind;
189 }
190
191 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
192 inline T* as() {
193 // |this|-qualify the |is| call below to avoid compile errors with even
194 // fairly recent versions of gcc, e.g. 7.1.1 according to bz.
195 MOZ_ASSERT(this->is<T>());
196 return static_cast<T*>(this);
197 }
198
199 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
200 inline const T* as() const {
201 // |this|-qualify the |is| call below to avoid compile errors with even
202 // fairly recent versions of gcc, e.g. 7.1.1 according to bz.
203 MOZ_ASSERT(this->is<T>());
204 return static_cast<const T*>(this);
205 }
206
207 inline JS::Zone* zone() const;
208 inline JS::Zone* zoneFromAnyThread() const;
209
210 // Get the zone for a cell known to be in the nursery.
211 inline JS::Zone* nurseryZone() const;
212 inline JS::Zone* nurseryZoneFromAnyThread() const;
213
214 inline ChunkBase* chunk() const;
215
216 // Default implementation for kinds that cannot be permanent. This may be
217 // overriden by derived classes.
218 MOZ_ALWAYS_INLINE bool isPermanentAndMayBeShared() const { return false; }
219
220 #ifdef DEBUG
221 static inline void assertThingIsNotGray(Cell* cell);
222 inline bool isAligned() const;
223 void dump(GenericPrinter& out) const;
224 void dump() const;
225 #endif
226
227 protected:
228 uintptr_t address() const;
229
230 private:
231 // Cells are destroyed by the GC. Do not delete them directly.
232 void operator delete(void*) = delete;
233 } JS_HAZ_GC_THING;
234
235 // A GC TenuredCell gets behaviors that are valid for things in the Tenured
236 // heap, such as access to the arena and mark bits.
237 class TenuredCell : public Cell {
238 public:
239 MOZ_ALWAYS_INLINE bool isTenured() const {
240 MOZ_ASSERT(!IsInsideNursery(this));
241 return true;
242 }
243
244 ArenaChunk* chunk() const { return static_cast<ArenaChunk*>(Cell::chunk()); }
245
246 // Mark bit management.
247 MOZ_ALWAYS_INLINE bool isMarkedAny() const;
248 MOZ_ALWAYS_INLINE bool isMarkedBlack() const;
249 MOZ_ALWAYS_INLINE bool isMarkedGray() const;
250 MOZ_ALWAYS_INLINE CellColor color() const;
251
252 // The return value indicates if the cell went from unmarked to marked.
253 MOZ_ALWAYS_INLINE bool markIfUnmarked(
254 MarkColor color = MarkColor::Black) const;
255 MOZ_ALWAYS_INLINE bool markIfUnmarkedThreadSafe(MarkColor color) const;
256 MOZ_ALWAYS_INLINE void markBlack() const;
257 MOZ_ALWAYS_INLINE void markBlackAtomic() const;
258 MOZ_ALWAYS_INLINE void copyMarkBitsFrom(const TenuredCell* src);
259 MOZ_ALWAYS_INLINE void unmark();
260
261 // Access to the arena.
262 inline Arena* arena() const;
263 inline AllocKind getAllocKind() const;
264 inline JS::TraceKind getTraceKind() const;
265 inline JS::Zone* zone() const;
266 inline JS::Zone* zoneFromAnyThread() const;
267 inline bool isInsideZone(JS::Zone* zone) const;
268
269 MOZ_ALWAYS_INLINE JS::shadow::Zone* shadowZone() const {
270 return JS::shadow::Zone::from(zone());
271 }
272 MOZ_ALWAYS_INLINE JS::shadow::Zone* shadowZoneFromAnyThread() const {
273 return JS::shadow::Zone::from(zoneFromAnyThread());
274 }
275
276 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
277 inline bool is() const {
278 return getTraceKind() == JS::MapTypeToTraceKind<T>::kind;
279 }
280
281 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
282 inline T* as() {
283 // |this|-qualify the |is| call below to avoid compile errors with even
284 // fairly recent versions of gcc, e.g. 7.1.1 according to bz.
285 MOZ_ASSERT(this->is<T>());
286 return static_cast<T*>(this);
287 }
288
289 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
290 inline const T* as() const {
291 // |this|-qualify the |is| call below to avoid compile errors with even
292 // fairly recent versions of gcc, e.g. 7.1.1 according to bz.
293 MOZ_ASSERT(this->is<T>());
294 return static_cast<const T*>(this);
295 }
296
297 // Default implementation for kinds that don't require fixup.
298 void fixupAfterMovingGC() {}
299
300 static inline CellColor getColor(ChunkMarkBitmap* bitmap,
301 const TenuredCell* cell);
302
303 #ifdef DEBUG
304 inline bool isAligned() const;
305 #endif
306 };
307
308 MOZ_ALWAYS_INLINE const TenuredCell& Cell::asTenured() const {
309 MOZ_ASSERT(isTenured());
310 return *static_cast<const TenuredCell*>(this);
311 }
312
313 MOZ_ALWAYS_INLINE TenuredCell& Cell::asTenured() {
314 MOZ_ASSERT(isTenured());
315 return *static_cast<TenuredCell*>(this);
316 }
317
318 MOZ_ALWAYS_INLINE bool Cell::isMarkedAny() const {
319 return !isTenured() || asTenured().isMarkedAny();
320 }
321
322 MOZ_ALWAYS_INLINE bool Cell::isMarkedBlack() const {
323 return !isTenured() || asTenured().isMarkedBlack();
324 }
325
326 MOZ_ALWAYS_INLINE bool Cell::isMarkedGray() const {
327 return isTenured() && asTenured().isMarkedGray();
328 }
329
330 MOZ_ALWAYS_INLINE bool Cell::isMarked(gc::MarkColor color) const {
331 return color == MarkColor::Gray ? isMarkedGray() : isMarkedBlack();
332 }
333
334 MOZ_ALWAYS_INLINE bool Cell::isMarkedAtLeast(gc::MarkColor color) const {
335 return color == MarkColor::Gray ? isMarkedAny() : isMarkedBlack();
336 }
337
338 MOZ_ALWAYS_INLINE CellColor Cell::color() const {
339 return isTenured() ? asTenured().color() : CellColor::Black;
340 }
341
342 inline JSRuntime* Cell::runtimeFromMainThread() const {
343 JSRuntime* rt = chunk()->runtime;
344 MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
345 return rt;
346 }
347
348 inline JSRuntime* Cell::runtimeFromAnyThread() const {
349 return chunk()->runtime;
350 }
351
352 inline uintptr_t Cell::address() const {
353 uintptr_t addr = uintptr_t(this);
354 MOZ_ASSERT(addr % CellAlignBytes == 0);
355 MOZ_ASSERT(ArenaChunk::withinValidRange(addr));
356 return addr;
357 }
358
359 ChunkBase* Cell::chunk() const {
360 uintptr_t addr = uintptr_t(this);
361 MOZ_ASSERT(addr % CellAlignBytes == 0);
362 addr &= ~ChunkMask;
363 return reinterpret_cast<ChunkBase*>(addr);
364 }
365
366 inline StoreBuffer* Cell::storeBuffer() const { return chunk()->storeBuffer; }
367
368 JS::Zone* Cell::zone() const {
369 if (isTenured()) {
370 return asTenured().zone();
371 }
372
373 return nurseryZone();
374 }
375
376 JS::Zone* Cell::zoneFromAnyThread() const {
377 if (isTenured()) {
378 return asTenured().zoneFromAnyThread();
379 }
380
381 return nurseryZoneFromAnyThread();
382 }
383
384 JS::Zone* Cell::nurseryZone() const {
385 JS::Zone* zone = nurseryZoneFromAnyThread();
386 MOZ_ASSERT(CurrentThreadIsGCMarking() || CurrentThreadCanAccessZone(zone));
387 return zone;
388 }
389
390 JS::Zone* Cell::nurseryZoneFromAnyThread() const {
391 return NurseryCellHeader::from(this)->zone();
392 }
393
394 #ifdef DEBUG
395 extern Cell* UninlinedForwarded(const Cell* cell);
396 #endif
397
398 inline JS::TraceKind Cell::getTraceKind() const {
399 if (isTenured()) {
400 MOZ_ASSERT_IF(isForwarded(), UninlinedForwarded(this)->getTraceKind() ==
401 asTenured().getTraceKind());
402 return asTenured().getTraceKind();
403 }
404
405 return NurseryCellHeader::from(this)->traceKind();
406 }
407
408 /* static */ MOZ_ALWAYS_INLINE bool Cell::needPreWriteBarrier(JS::Zone* zone) {
409 return JS::shadow::Zone::from(zone)->needsIncrementalBarrier();
410 }
411
412 MOZ_ALWAYS_INLINE bool TenuredCell::isMarkedAny() const {
413 MOZ_ASSERT(arena()->allocated());
414 return chunk()->markBits.isMarkedAny(this);
415 }
416
417 MOZ_ALWAYS_INLINE bool TenuredCell::isMarkedBlack() const {
418 MOZ_ASSERT(arena()->allocated());
419 return chunk()->markBits.isMarkedBlack(this);
420 }
421
422 MOZ_ALWAYS_INLINE bool TenuredCell::isMarkedGray() const {
423 MOZ_ASSERT(arena()->allocated());
424 return chunk()->markBits.isMarkedGray(this);
425 }
426
427 MOZ_ALWAYS_INLINE CellColor TenuredCell::color() const {
428 return getColor(&chunk()->markBits, this);
429 }
430
431 /* static */
432 inline CellColor TenuredCell::getColor(ChunkMarkBitmap* bitmap,
433 const TenuredCell* cell) {
434 // Note that this method isn't synchronised so may give surprising results if
435 // the mark bitmap is being modified concurrently.
436
437 if (bitmap->isMarkedBlack(cell)) {
438 return CellColor::Black;
439 }
440
441 if (bitmap->isMarkedGray(cell)) {
442 return CellColor::Gray;
443 }
444
445 return CellColor::White;
446 }
447
448 inline Arena* TenuredCell::arena() const {
449 MOZ_ASSERT(isTenured());
450 uintptr_t addr = address();
451 addr &= ~ArenaMask;
452 return reinterpret_cast<Arena*>(addr);
453 }
454
455 AllocKind TenuredCell::getAllocKind() const { return arena()->getAllocKind(); }
456
457 JS::TraceKind TenuredCell::getTraceKind() const {
458 return MapAllocToTraceKind(getAllocKind());
459 }
460
461 JS::Zone* TenuredCell::zone() const {
462 JS::Zone* zone = zoneFromAnyThread();
463 MOZ_ASSERT(CurrentThreadIsGCMarking() || CurrentThreadCanAccessZone(zone));
464 return zone;
465 }
466
467 JS::Zone* TenuredCell::zoneFromAnyThread() const { return arena()->zone(); }
468
469 bool TenuredCell::isInsideZone(JS::Zone* zone) const {
470 return zone == zoneFromAnyThread();
471 }
472
473 // Read barrier and pre-write barrier implementation for GC cells.
474
475 template <typename T>
476 MOZ_ALWAYS_INLINE void ReadBarrier(T* thing) {
477 static_assert(std::is_base_of_v<Cell, T>);
478 static_assert(!std::is_same_v<Cell, T> && !std::is_same_v<TenuredCell, T>);
479
480 if (thing) {
481 ReadBarrierImpl(thing);
482 }
483 }
484
485 MOZ_ALWAYS_INLINE void ReadBarrierImpl(TenuredCell* thing) {
486 MOZ_ASSERT(CurrentThreadIsMainThread());
487 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
488 MOZ_ASSERT(thing);
489
490 JS::shadow::Zone* shadowZone = thing->shadowZoneFromAnyThread();
491 if (shadowZone->needsIncrementalBarrier()) {
492 PerformIncrementalReadBarrier(thing);
493 return;
494 }
495
496 if (thing->isMarkedGray()) {
497 UnmarkGrayGCThingRecursively(thing);
498 }
499 }
500
501 MOZ_ALWAYS_INLINE void ReadBarrierImpl(Cell* thing) {
502 MOZ_ASSERT(!CurrentThreadIsGCMarking());
503 MOZ_ASSERT(thing);
504
505 if (thing->isTenured()) {
506 ReadBarrierImpl(&thing->asTenured());
507 }
508 }
509
510 #ifdef DEBUG
511 static bool PreWriteBarrierAllowed() {
512 JS::GCContext* gcx = MaybeGetGCContext();
513 if (!gcx || !gcx->isPreWriteBarrierAllowed()) {
514 return false;
515 }
516
517 return gcx->onMainThread() || gcx->gcUse() == gc::GCUse::Sweeping ||
518 gcx->gcUse() == gc::GCUse::Finalizing;
519 }
520 #endif
521
522 MOZ_ALWAYS_INLINE void PreWriteBarrierImpl(TenuredCell* thing) {
523 MOZ_ASSERT(PreWriteBarrierAllowed());
524 MOZ_ASSERT(thing);
525
526 // Barriers can be triggered on the main thread while collecting, but are
527 // disabled. For example, this happens when sweeping HeapPtr wrappers. See
528 // AutoDisableBarriers.
529
530 JS::shadow::Zone* zone = thing->shadowZoneFromAnyThread();
531 if (zone->needsIncrementalBarrier()) {
532 PerformIncrementalPreWriteBarrier(thing);
533 }
534 }
535
536 MOZ_ALWAYS_INLINE void PreWriteBarrierImpl(Cell* thing) {
537 MOZ_ASSERT(!CurrentThreadIsGCMarking());
538 MOZ_ASSERT(thing);
539
540 if (thing->isTenured()) {
541 PreWriteBarrierImpl(&thing->asTenured());
542 }
543 }
544
545 template <typename T>
546 MOZ_ALWAYS_INLINE void PreWriteBarrier(T* thing) {
547 static_assert(std::is_base_of_v<Cell, T>);
548 static_assert(!std::is_same_v<Cell, T> && !std::is_same_v<TenuredCell, T>);
549
550 if (thing) {
551 PreWriteBarrierImpl(thing);
552 }
553 }
554
555 // Pre-write barrier implementation for structures containing GC cells, taking a
556 // functor to trace the structure.
557 template <typename T, typename F>
558 MOZ_ALWAYS_INLINE void PreWriteBarrier(JS::Zone* zone, T* data,
559 const F& traceFn) {
560 MOZ_ASSERT(data);
561 MOZ_ASSERT(!CurrentThreadIsOffThreadCompiling());
562 MOZ_ASSERT(!CurrentThreadIsGCMarking());
563
564 auto* shadowZone = JS::shadow::Zone::from(zone);
565 if (!shadowZone->needsIncrementalBarrier()) {
566 return;
567 }
568
569 MOZ_ASSERT(CurrentThreadCanAccessRuntime(shadowZone->runtimeFromAnyThread()));
570 MOZ_ASSERT(!RuntimeFromMainThreadIsHeapMajorCollecting(shadowZone));
571
572 traceFn(shadowZone->barrierTracer(), data);
573 }
574
575 // Pre-write barrier implementation for structures containing GC cells. T must
576 // support a |trace| method.
577 template <typename T>
578 MOZ_ALWAYS_INLINE void PreWriteBarrier(JS::Zone* zone, T* data) {
579 MOZ_ASSERT(data);
580 PreWriteBarrier(zone, data, [](JSTracer* trc, T* data) { data->trace(trc); });
581 }
582
583 #ifdef DEBUG
584
585 /* static */ void Cell::assertThingIsNotGray(Cell* cell) {
586 JS::AssertCellIsNotGray(cell);
587 }
588
589 bool Cell::isAligned() const {
590 if (!isTenured()) {
591 return true;
592 }
593 return asTenured().isAligned();
594 }
595
596 bool TenuredCell::isAligned() const {
597 return Arena::isAligned(address(), arena()->getThingSize());
598 }
599
600 #endif
601
602 // Base class for nusery-allocatable GC things that have 32-bit length and
603 // 32-bit flags (currently JSString and BigInt).
604 //
605 // This tries to store both in Cell::header_, but if that isn't large enough the
606 // length is stored separately.
607 //
608 // 32 0
609 // ------------------
610 // | Length | Flags |
611 // ------------------
612 //
613 // The low bits of the flags word (see CellFlagBitsReservedForGC) are reserved
614 // for GC. Derived classes must ensure they don't use these flags for non-GC
615 // purposes.
616 class alignas(gc::CellAlignBytes) CellWithLengthAndFlags : public Cell {
617 #if JS_BITS_PER_WORD == 32
618 // Additional storage for length if |header_| is too small to fit both.
619 uint32_t length_;
620 #endif
621
622 protected:
623 uint32_t headerLengthField() const {
624 #if JS_BITS_PER_WORD == 32
625 return length_;
626 #else
627 return uint32_t(header_.get() >> 32);
628 #endif
629 }
630
631 uint32_t headerFlagsField() const { return uint32_t(header_.get()); }
632
633 void setHeaderFlagBit(uint32_t flag) {
634 header_.set(header_.get() | uintptr_t(flag));
635 }
636 void clearHeaderFlagBit(uint32_t flag) {
637 header_.set(header_.get() & ~uintptr_t(flag));
638 }
639 void toggleHeaderFlagBit(uint32_t flag) {
640 header_.set(header_.get() ^ uintptr_t(flag));
641 }
642
643 void setHeaderLengthAndFlags(uint32_t len, uint32_t flags) {
644 #if JS_BITS_PER_WORD == 32
645 header_.set(flags);
646 length_ = len;
647 #else
648 header_.set((uint64_t(len) << 32) | uint64_t(flags));
649 #endif
650 }
651
652 public:
653 // Returns the offset of header_. JIT code should use offsetOfFlags
654 // below.
655 static constexpr size_t offsetOfRawHeaderFlagsField() {
656 return offsetof(CellWithLengthAndFlags, header_);
657 }
658
659 // Offsets for direct field from jit code. A number of places directly
660 // access 32-bit length and flags fields so do endian trickery here.
661 #if JS_BITS_PER_WORD == 32
662 static constexpr size_t offsetOfHeaderFlags() {
663 return offsetof(CellWithLengthAndFlags, header_);
664 }
665 static constexpr size_t offsetOfHeaderLength() {
666 return offsetof(CellWithLengthAndFlags, length_);
667 }
668 #elif MOZ_LITTLE_ENDIAN()
669 static constexpr size_t offsetOfHeaderFlags() {
670 return offsetof(CellWithLengthAndFlags, header_);
671 }
672 static constexpr size_t offsetOfHeaderLength() {
673 return offsetof(CellWithLengthAndFlags, header_) + sizeof(uint32_t);
674 }
675 #else
676 static constexpr size_t offsetOfHeaderFlags() {
677 return offsetof(CellWithLengthAndFlags, header_) + sizeof(uint32_t);
678 }
679 static constexpr size_t offsetOfHeaderLength() {
680 return offsetof(CellWithLengthAndFlags, header_);
681 }
682 #endif
683 };
684
685 // Base class for non-nursery-allocatable GC things that allows storing a non-GC
686 // thing pointer in the first word.
687 //
688 // The low bits of the word (see CellFlagBitsReservedForGC) are reserved for GC.
689 template <class PtrT>
690 class alignas(gc::CellAlignBytes) TenuredCellWithNonGCPointer
691 : public TenuredCell {
692 static_assert(!std::is_pointer_v<PtrT>,
693 "PtrT should be the type of the referent, not of the pointer");
694 static_assert(
695 !std::is_base_of_v<Cell, PtrT>,
696 "Don't use TenuredCellWithNonGCPointer for pointers to GC things");
697
698 protected:
699 TenuredCellWithNonGCPointer() = default;
700 explicit TenuredCellWithNonGCPointer(PtrT* initial) {
701 uintptr_t data = uintptr_t(initial);
702 header_.set(data);
703 }
704
705 PtrT* headerPtr() const {
706 MOZ_ASSERT(flags() == 0);
707 return reinterpret_cast<PtrT*>(uintptr_t(header_.get()));
708 }
709
710 void setHeaderPtr(PtrT* newValue) {
711 // As above, no flags are expected to be set here.
712 uintptr_t data = uintptr_t(newValue);
713 MOZ_ASSERT(flags() == 0);
714 header_.set(data);
715 }
716
717 public:
718 static constexpr size_t offsetOfHeaderPtr() {
719 return offsetof(TenuredCellWithNonGCPointer, header_);
720 }
721 };
722
723 // Base class for non-nursery-allocatable GC things that allows storing flags
724 // in the first word.
725 //
726 // The low bits of the flags word (see CellFlagBitsReservedForGC) are reserved
727 // for GC.
728 class alignas(gc::CellAlignBytes) TenuredCellWithFlags : public TenuredCell {
729 protected:
730 TenuredCellWithFlags() { header_.set(0); }
731 explicit TenuredCellWithFlags(uintptr_t initial) { header_.set(initial); }
732
733 uintptr_t headerFlagsField() const {
734 MOZ_ASSERT(flags() == 0);
735 return header_.get();
736 }
737
738 void setHeaderFlagBits(uintptr_t flags) {
739 header_.set(header_.get() | flags);
740 }
741 void clearHeaderFlagBits(uintptr_t flags) {
742 header_.set(header_.get() & ~flags);
743 }
744 };
745
746 // Base class for GC things that have a tenured GC pointer as their first word.
747 //
748 // The low bits of the first word (see CellFlagBitsReservedForGC) are reserved
749 // for GC.
750 //
751 // This includes a pre write barrier when the pointer is update. No post barrier
752 // is necessary as the pointer is always tenured.
753 template <class BaseCell, class PtrT>
754 class alignas(gc::CellAlignBytes) CellWithTenuredGCPointer : public BaseCell {
755 static void staticAsserts() {
756 // These static asserts are not in class scope because the PtrT may not be
757 // defined when this class template is instantiated.
758 static_assert(
759 std::is_same_v<BaseCell, Cell> || std::is_same_v<BaseCell, TenuredCell>,
760 "BaseCell must be either Cell or TenuredCell");
761 static_assert(
762 !std::is_pointer_v<PtrT>,
763 "PtrT should be the type of the referent, not of the pointer");
764 static_assert(
765 std::is_base_of_v<Cell, PtrT>,
766 "Only use CellWithTenuredGCPointer for pointers to GC things");
767 }
768
769 protected:
770 CellWithTenuredGCPointer() = default;
771 explicit CellWithTenuredGCPointer(PtrT* initial) { initHeaderPtr(initial); }
772
773 void initHeaderPtr(PtrT* initial) {
774 MOZ_ASSERT_IF(initial, !IsInsideNursery(initial));
775 uintptr_t data = uintptr_t(initial);
776 this->header_.set(data);
777 }
778
779 void setHeaderPtr(PtrT* newValue) {
780 // As above, no flags are expected to be set here.
781 MOZ_ASSERT_IF(newValue, !IsInsideNursery(newValue));
782 PreWriteBarrier(headerPtr());
783 unbarrieredSetHeaderPtr(newValue);
784 }
785
786 public:
787 PtrT* headerPtr() const {
788 staticAsserts();
789 MOZ_ASSERT(this->flags() == 0);
790 return reinterpret_cast<PtrT*>(uintptr_t(this->header_.get()));
791 }
792 PtrT* headerPtrAtomic() const {
793 staticAsserts();
794 MOZ_ASSERT(this->flags() == 0);
795 return reinterpret_cast<PtrT*>(uintptr_t(this->header_.getAtomic()));
796 }
797
798 void unbarrieredSetHeaderPtr(PtrT* newValue) {
799 uintptr_t data = uintptr_t(newValue);
800 MOZ_ASSERT(this->flags() == 0);
801 this->header_.set(data);
802 }
803
804 static constexpr size_t offsetOfHeaderPtr() {
805 return offsetof(CellWithTenuredGCPointer, header_);
806 }
807 };
808
809 void CellHeaderPostWriteBarrier(JSObject** ptr, JSObject* prev, JSObject* next);
810
811 template <typename T>
812 constexpr inline bool GCTypeIsTenured() {
813 static_assert(std::is_base_of_v<Cell, T>);
814 static_assert(!std::is_same_v<Cell, T> && !std::is_same_v<TenuredCell, T>);
815
816 return std::is_base_of_v<TenuredCell, T> || std::is_base_of_v<JSAtom, T>;
817 }
818
819 template <class PtrT>
820 class alignas(gc::CellAlignBytes) TenuredCellWithGCPointer
821 : public TenuredCell {
822 static void staticAsserts() {
823 // These static asserts are not in class scope because the PtrT may not be
824 // defined when this class template is instantiated.
825 static_assert(
826 !std::is_pointer_v<PtrT>,
827 "PtrT should be the type of the referent, not of the pointer");
828 static_assert(
829 std::is_base_of_v<Cell, PtrT>,
830 "Only use TenuredCellWithGCPointer for pointers to GC things");
831 static_assert(
832 !GCTypeIsTenured<PtrT>,
833 "Don't use TenuredCellWithGCPointer for always-tenured GC things");
834 }
835
836 protected:
837 TenuredCellWithGCPointer() = default;
838 explicit TenuredCellWithGCPointer(PtrT* initial) { initHeaderPtr(initial); }
839
840 void initHeaderPtr(PtrT* initial) {
841 uintptr_t data = uintptr_t(initial);
842 this->header_.set(data);
843 if (initial && IsInsideNursery(initial)) {
844 CellHeaderPostWriteBarrier(headerPtrAddress(), nullptr, initial);
845 }
846 }
847
848 PtrT** headerPtrAddress() {
849 MOZ_ASSERT(this->flags() == 0);
850 return reinterpret_cast<PtrT**>(&this->header_);
851 }
852
853 public:
854 PtrT* headerPtr() const {
855 MOZ_ASSERT(this->flags() == 0);
856 return reinterpret_cast<PtrT*>(uintptr_t(this->header_.get()));
857 }
858
859 void unbarrieredSetHeaderPtr(PtrT* newValue) {
860 uintptr_t data = uintptr_t(newValue);
861 MOZ_ASSERT(this->flags() == 0);
862 this->header_.set(data);
863 }
864
865 static constexpr size_t offsetOfHeaderPtr() {
866 return offsetof(TenuredCellWithGCPointer, header_);
867 }
868 };
869
870 // Check whether a typed GC thing is marked at all. Doesn't check gray bits for
871 // kinds that can't be marked gray.
872 template <typename T>
873 static inline bool TenuredThingIsMarkedAny(T* thing) {
874 using BaseT = typename BaseGCType<T>::type;
875 TenuredCell* cell = &thing->asTenured();
876 if constexpr (TraceKindCanBeGray<BaseT>::value) {
877 return cell->isMarkedAny();
878 } else {
879 MOZ_ASSERT(!cell->isMarkedGray());
880 return cell->isMarkedBlack();
881 }
882 }
883
884 template <>
885 inline bool TenuredThingIsMarkedAny<Cell>(Cell* thing) {
886 return thing->asTenured().isMarkedAny();
887 }
888
889 class alignas(gc::CellAlignBytes) SmallBuffer : public TenuredCell {
890 public:
891 static constexpr uintptr_t NURSERY_OWNED_BIT = Bit(3);
892
893 void check() const {} // No check value.
894
895 bool isNurseryOwned() const;
896 void setNurseryOwned(bool value);
897
898 static const JS::TraceKind TraceKind = JS::TraceKind::SmallBuffer;
899 void traceChildren(JSTracer* trc) {
900 // TODO: Generic tracing not supported for sized allocations.
901 // GCRuntime::checkForCompartmentMismatches ends up calling this because it
902 // iterates all GC cells.
903 }
904
905 size_t allocBytes() const;
906 void* data() { return this + 1; }
907 };
908 template <size_t bytes>
909 struct SmallBufferN : public SmallBuffer {
910 uint8_t data[bytes];
911 };
912 static_assert(sizeof(SmallBufferN<16>) == 16 + sizeof(SmallBuffer));
913 static_assert(sizeof(SmallBufferN<128>) == 128 + sizeof(SmallBuffer));
914
915 } /* namespace gc */
916 } /* namespace js */
917
918 #endif /* gc_Cell_h */