-
Notifications
You must be signed in to change notification settings - Fork 54
/
Shape.h
1868 lines (1534 loc) · 57.6 KB
/
Shape.h
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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 vm_Shape_h
#define vm_Shape_h
#include "mozilla/Attributes.h"
#include "mozilla/GuardObjects.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/TemplateLib.h"
#include <algorithm>
#include "jsapi.h"
#include "jsfriendapi.h"
#include "jstypes.h"
#include "NamespaceImports.h"
#include "gc/Barrier.h"
#include "gc/FreeOp.h"
#include "gc/MaybeRooted.h"
#include "gc/Rooting.h"
#include "js/HashTable.h"
#include "js/MemoryMetrics.h"
#include "js/RootingAPI.h"
#include "js/UbiNode.h"
#include "vm/JSAtom.h"
#include "vm/ObjectGroup.h"
#include "vm/Printer.h"
#include "vm/StringType.h"
#include "vm/SymbolType.h"
/*
* [SMDOC] Shapes
*
* In isolation, a Shape represents a property that exists in one or more
* objects; it has an id, flags, etc. (But it doesn't represent the property's
* value.) However, Shapes are always stored in linked linear sequence of
* Shapes, called "shape lineages". Each shape lineage represents the layout of
* an entire object.
*
* Every JSObject has a pointer, |shape_|, accessible via lastProperty(), to
* the last Shape in a shape lineage, which identifies the property most
* recently added to the object. This pointer permits fast object layout
* tests. The shape lineage order also dictates the enumeration order for the
* object; ECMA requires no particular order but this implementation has
* promised and delivered property definition order.
*
* Shape lineages occur in two kinds of data structure.
*
* 1. N-ary property trees. Each path from a non-root node to the root node in
* a property tree is a shape lineage. Property trees permit full (or
* partial) sharing of Shapes between objects that have fully (or partly)
* identical layouts. The root is an EmptyShape whose identity is determined
* by the object's class, compartment and prototype. These Shapes are shared
* and immutable.
*
* 2. Dictionary mode lists. Shapes in such lists are said to be "in
* dictionary mode", as are objects that point to such Shapes. These Shapes
* are unshared, private to a single object, and immutable except for their
* links in the dictionary list.
*
* All shape lineages are bi-directionally linked, via the |parent| and
* |children|/|listp| members.
*
* Shape lineages start out life in the property tree. They can be converted
* (by copying) to dictionary mode lists in the following circumstances.
*
* 1. The shape lineage's size reaches MAX_HEIGHT. This reasonable limit avoids
* potential worst cases involving shape lineage mutations.
*
* 2. A property represented by a non-last Shape in a shape lineage is removed
* from an object. (In the last Shape case, obj->shape_ can be easily
* adjusted to point to obj->shape_->parent.) We originally tried lazy
* forking of the property tree, but this blows up for delete/add
* repetitions.
*
* 3. A property represented by a non-last Shape in a shape lineage has its
* attributes modified.
*
* To find the Shape for a particular property of an object initially requires
* a linear search. But if the number of searches starting at any particular
* Shape in the property tree exceeds LINEAR_SEARCHES_MAX and the Shape's
* lineage has (excluding the EmptyShape) at least MIN_ENTRIES, we create an
* auxiliary hash table -- the ShapeTable -- that allows faster lookup.
* Furthermore, a ShapeTable is always created for dictionary mode lists,
* and it is attached to the last Shape in the lineage. Shape tables for
* property tree Shapes never change, but shape tables for dictionary mode
* Shapes can grow and shrink.
*
* To save memory, shape tables can be discarded on GC and recreated when
* needed. AutoKeepShapeCaches can be used to avoid discarding shape tables
* for a particular zone. Methods operating on ShapeTables take either an
* AutoCheckCannotGC or AutoKeepShapeCaches argument, to help ensure tables
* are not purged while we're using them.
*
* There used to be a long, math-heavy comment here explaining why property
* trees are more space-efficient than alternatives. This was removed in bug
* 631138; see that bug for the full details.
*
* For getters/setters, an AccessorShape is allocated. This is a slightly fatter
* type with extra fields for the getter/setter data.
*
* Because many Shapes have similar data, there is actually a secondary type
* called a BaseShape that holds some of a Shape's data. Many shapes can share
* a single BaseShape.
*/
MOZ_ALWAYS_INLINE size_t JSSLOT_FREE(const JSClass* clasp) {
// Proxy classes have reserved slots, but proxies manage their own slot
// layout.
MOZ_ASSERT(!clasp->isProxy());
return JSCLASS_RESERVED_SLOTS(clasp);
}
namespace js {
class Shape;
struct StackShape;
struct ShapeHasher : public DefaultHasher<Shape*> {
using Key = Shape*;
using Lookup = StackShape;
static MOZ_ALWAYS_INLINE HashNumber hash(const Lookup& l);
static MOZ_ALWAYS_INLINE bool match(Key k, const Lookup& l);
};
using ShapeSet = HashSet<Shape*, ShapeHasher, SystemAllocPolicy>;
// A tagged pointer to null, a single child, or a many-children data structure.
class ShapeChildren {
// Tag bits must not overlap with DictionaryShapeLink.
enum { SINGLE_SHAPE = 0, SHAPE_SET = 1, MASK = 3 };
uintptr_t bits = 0;
public:
bool isNone() const { return !bits; }
void setNone() { bits = 0; }
bool isSingleShape() const {
return (bits & MASK) == SINGLE_SHAPE && !isNone();
}
Shape* toSingleShape() const {
MOZ_ASSERT(isSingleShape());
return reinterpret_cast<Shape*>(bits & ~uintptr_t(MASK));
}
void setSingleShape(Shape* shape) {
MOZ_ASSERT(shape);
MOZ_ASSERT((uintptr_t(shape) & MASK) == 0);
bits = uintptr_t(shape) | SINGLE_SHAPE;
}
bool isShapeSet() const { return (bits & MASK) == SHAPE_SET; }
ShapeSet* toShapeSet() const {
MOZ_ASSERT(isShapeSet());
return reinterpret_cast<ShapeSet*>(bits & ~uintptr_t(MASK));
}
void setShapeSet(ShapeSet* hash) {
MOZ_ASSERT(hash);
MOZ_ASSERT((uintptr_t(hash) & MASK) == 0);
bits = uintptr_t(hash) | SHAPE_SET;
}
#ifdef DEBUG
void checkHasChild(Shape* child) const;
#endif
} JS_HAZ_GC_POINTER;
// For dictionary mode shapes, a tagged pointer to the next shape or associated
// object if this is the last shape.
class DictionaryShapeLink {
// Tag bits must not overlap with ShapeChildren.
enum { SHAPE = 2, OBJECT = 3, MASK = 3 };
uintptr_t bits = 0;
public:
// XXX Using = default on the default ctor causes rooting hazards for some
// reason.
DictionaryShapeLink() {}
explicit DictionaryShapeLink(JSObject* obj) { setObject(obj); }
explicit DictionaryShapeLink(Shape* shape) { setShape(shape); }
bool isNone() const { return !bits; }
void setNone() { bits = 0; }
bool isShape() const { return (bits & MASK) == SHAPE; }
Shape* toShape() const {
MOZ_ASSERT(isShape());
return reinterpret_cast<Shape*>(bits & ~uintptr_t(MASK));
}
void setShape(Shape* shape) {
MOZ_ASSERT(shape);
MOZ_ASSERT((uintptr_t(shape) & MASK) == 0);
bits = uintptr_t(shape) | SHAPE;
}
bool isObject() const { return (bits & MASK) == OBJECT; }
JSObject* toObject() const {
MOZ_ASSERT(isObject());
return reinterpret_cast<JSObject*>(bits & ~uintptr_t(MASK));
}
void setObject(JSObject* obj) {
MOZ_ASSERT(obj);
MOZ_ASSERT((uintptr_t(obj) & MASK) == 0);
bits = uintptr_t(obj) | OBJECT;
}
bool operator==(const DictionaryShapeLink& other) const {
return bits == other.bits;
}
bool operator!=(const DictionaryShapeLink& other) const {
return !((*this) == other);
}
GCPtrShape* prevPtr();
} JS_HAZ_GC_POINTER;
class PropertyTree {
friend class ::JSFunction;
#ifdef DEBUG
JS::Zone* zone_;
#endif
bool insertChild(JSContext* cx, Shape* parent, Shape* child);
PropertyTree();
public:
/*
* Use a lower limit for objects that are accessed using SETELEM (o[x] = y).
* These objects are likely used as hashmaps and dictionary mode is more
* efficient in this case.
*/
enum { MAX_HEIGHT = 512, MAX_HEIGHT_WITH_ELEMENTS_ACCESS = 128 };
explicit PropertyTree(JS::Zone* zone)
#ifdef DEBUG
: zone_(zone)
#endif
{
}
MOZ_ALWAYS_INLINE Shape* inlinedGetChild(JSContext* cx, Shape* parent,
JS::Handle<StackShape> childSpec);
Shape* getChild(JSContext* cx, Shape* parent, JS::Handle<StackShape> child);
};
class TenuringTracer;
using GetterOp = JSGetterOp;
using SetterOp = JSSetterOp;
/* Limit on the number of slotful properties in an object. */
static const uint32_t SHAPE_INVALID_SLOT = Bit(24) - 1;
static const uint32_t SHAPE_MAXIMUM_SLOT = Bit(24) - 2;
enum class MaybeAdding { Adding = true, NotAdding = false };
class AutoKeepShapeCaches;
/*
* ShapeIC uses a small array that is linearly searched.
*/
class ShapeIC {
public:
friend class NativeObject;
friend class BaseShape;
friend class Shape;
ShapeIC() : size_(0), nextFreeIndex_(0), entries_(nullptr) {}
~ShapeIC() = default;
bool isFull() const {
MOZ_ASSERT(nextFreeIndex_ <= size_);
return size_ == nextFreeIndex_;
}
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(this) + mallocSizeOf(entries_.get());
}
uint32_t entryCount() { return nextFreeIndex_; }
bool init(JSContext* cx);
void trace(JSTracer* trc);
#ifdef JSGC_HASH_TABLE_CHECKS
void checkAfterMovingGC();
#endif
MOZ_ALWAYS_INLINE bool search(jsid id, Shape** foundShape);
MOZ_ALWAYS_INLINE bool appendEntry(jsid id, Shape* shape) {
MOZ_ASSERT(nextFreeIndex_ <= size_);
if (nextFreeIndex_ == size_) {
return false;
}
entries_[nextFreeIndex_].id_ = id;
entries_[nextFreeIndex_].shape_ = shape;
nextFreeIndex_++;
return true;
}
private:
static const uint32_t MAX_SIZE = 7;
class Entry {
public:
jsid id_;
Shape* shape_;
Entry() = delete;
Entry(const Entry&) = delete;
Entry& operator=(const Entry&) = delete;
};
uint8_t size_;
uint8_t nextFreeIndex_;
/* table of ptrs to {jsid,Shape*} pairs */
UniquePtr<Entry[], JS::FreePolicy> entries_;
};
/*
* ShapeTable uses multiplicative hashing, but specialized to
* minimize footprint.
*/
class ShapeTable {
public:
friend class NativeObject;
friend class BaseShape;
friend class Shape;
friend class ShapeCachePtr;
class Entry {
// js::Shape pointer tag bit indicating a collision.
static const uintptr_t SHAPE_COLLISION = 1;
static Shape* const SHAPE_REMOVED; // = SHAPE_COLLISION
Shape* shape_;
Entry() = delete;
Entry(const Entry&) = delete;
Entry& operator=(const Entry&) = delete;
public:
bool isFree() const { return shape_ == nullptr; }
bool isRemoved() const { return shape_ == SHAPE_REMOVED; }
bool isLive() const { return !isFree() && !isRemoved(); }
bool hadCollision() const { return uintptr_t(shape_) & SHAPE_COLLISION; }
void setFree() { shape_ = nullptr; }
void setRemoved() { shape_ = SHAPE_REMOVED; }
Shape* shape() const {
return reinterpret_cast<Shape*>(uintptr_t(shape_) & ~SHAPE_COLLISION);
}
void setShape(Shape* shape) {
MOZ_ASSERT(isFree());
MOZ_ASSERT(shape);
MOZ_ASSERT(shape != SHAPE_REMOVED);
shape_ = shape;
MOZ_ASSERT(!hadCollision());
}
void flagCollision() {
shape_ = reinterpret_cast<Shape*>(uintptr_t(shape_) | SHAPE_COLLISION);
}
void setPreservingCollision(Shape* shape) {
shape_ = reinterpret_cast<Shape*>(uintptr_t(shape) |
uintptr_t(hadCollision()));
}
};
private:
static const uint32_t HASH_BITS = mozilla::tl::BitSize<HashNumber>::value;
// This value is low because it's common for a ShapeTable to be created
// with an entryCount of zero.
static const uint32_t MIN_SIZE_LOG2 = 2;
static const uint32_t MIN_SIZE = Bit(MIN_SIZE_LOG2);
uint32_t hashShift_; /* multiplicative hash shift */
uint32_t entryCount_; /* number of entries in table */
uint32_t removedCount_; /* removed entry sentinels in table */
uint32_t freeList_; /* SHAPE_INVALID_SLOT or head of slot
freelist in owning dictionary-mode
object */
UniquePtr<Entry[], JS::FreePolicy>
entries_; /* table of ptrs to shared tree nodes */
template <MaybeAdding Adding>
MOZ_ALWAYS_INLINE Entry& searchUnchecked(jsid id);
public:
explicit ShapeTable(uint32_t nentries)
: hashShift_(HASH_BITS - MIN_SIZE_LOG2),
entryCount_(nentries),
removedCount_(0),
freeList_(SHAPE_INVALID_SLOT),
entries_(nullptr) {
/* NB: entries is set by init, which must be called. */
}
~ShapeTable() = default;
uint32_t entryCount() const { return entryCount_; }
uint32_t freeList() const { return freeList_; }
void setFreeList(uint32_t slot) { freeList_ = slot; }
/*
* This counts the ShapeTable object itself (which must be
* heap-allocated) and its |entries| array.
*/
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(this) + mallocSizeOf(entries_.get());
}
// init() is fallible and reports OOM to the context.
bool init(JSContext* cx, Shape* lastProp);
// change() is fallible but does not report OOM.
bool change(JSContext* cx, int log2Delta);
template <MaybeAdding Adding>
MOZ_ALWAYS_INLINE Entry& search(jsid id, const AutoKeepShapeCaches&);
template <MaybeAdding Adding>
MOZ_ALWAYS_INLINE Entry& search(jsid id, const JS::AutoCheckCannotGC&);
void trace(JSTracer* trc);
#ifdef JSGC_HASH_TABLE_CHECKS
void checkAfterMovingGC();
#endif
private:
Entry& getEntry(uint32_t i) const {
MOZ_ASSERT(i < capacity());
return entries_[i];
}
void decEntryCount() {
MOZ_ASSERT(entryCount_ > 0);
entryCount_--;
}
void incEntryCount() {
entryCount_++;
MOZ_ASSERT(entryCount_ + removedCount_ <= capacity());
}
void incRemovedCount() {
removedCount_++;
MOZ_ASSERT(entryCount_ + removedCount_ <= capacity());
}
// By definition, hashShift = HASH_BITS - log2(capacity).
uint32_t capacity() const { return Bit(HASH_BITS - hashShift_); }
// Whether we need to grow. We want to do this if the load factor
// is >= 0.75
bool needsToGrow() const {
uint32_t size = capacity();
return entryCount_ + removedCount_ >= size - (size >> 2);
}
// Try to grow the table. On failure, reports out of memory on cx
// and returns false. This will make any extant pointers into the
// table invalid. Don't call this unless needsToGrow() is true.
bool grow(JSContext* cx);
};
/*
* Wrapper class to either ShapeTable or ShapeIC optimization.
*
* Shapes are initially cached in a linear cache from the ShapeIC class that is
* lazily initialized after LINEAR_SEARCHES_MAX searches have been reached, and
* the Shape has at least MIN_ENTRIES parents in the lineage.
*
* We use the population of the cache as an indicator of whether the ShapeIC is
* working or not. Once it is full, it is destroyed and a ShapeTable is
* created instead.
*
* For dictionaries, the linear cache is skipped entirely and hashify is used
* to generate the ShapeTable immediately.
*/
class ShapeCachePtr {
// To reduce impact on memory usage, p is the only data member for this class.
uintptr_t p;
enum class CacheType {
IC = 0x1,
Table = 0x2,
};
static const uint32_t MASK_BITS = 0x3;
static const uintptr_t CACHETYPE_MASK = 0x3;
void* getPointer() const {
uintptr_t ptrVal = p & ~CACHETYPE_MASK;
return reinterpret_cast<void*>(ptrVal);
}
CacheType getType() const {
return static_cast<CacheType>(p & CACHETYPE_MASK);
}
public:
static const uint32_t MIN_ENTRIES = 3;
ShapeCachePtr() : p(0) {}
template <MaybeAdding Adding>
MOZ_ALWAYS_INLINE bool search(jsid id, Shape* start, Shape** foundShape);
bool isIC() const { return (getType() == CacheType::IC); }
bool isTable() const { return (getType() == CacheType::Table); }
bool isInitialized() const { return isTable() || isIC(); }
ShapeTable* getTablePointer() const {
MOZ_ASSERT(isTable());
return reinterpret_cast<ShapeTable*>(getPointer());
}
ShapeIC* getICPointer() const {
MOZ_ASSERT(isIC());
return reinterpret_cast<ShapeIC*>(getPointer());
}
// Use ShapeTable implementation.
// The caller must have purged any existing IC implementation.
void initializeTable(ShapeTable* table) {
MOZ_ASSERT(!isTable() && !isIC());
uintptr_t tableptr = uintptr_t(table);
// Double check that pointer is 4 byte aligned.
MOZ_ASSERT((tableptr & CACHETYPE_MASK) == 0);
tableptr |= static_cast<uintptr_t>(CacheType::Table);
p = tableptr;
}
// Use ShapeIC implementation.
// This cannot clobber an existing Table implementation.
void initializeIC(ShapeIC* ic) {
MOZ_ASSERT(!isTable() && !isIC());
uintptr_t icptr = uintptr_t(ic);
// Double check that pointer is 4 byte aligned.
MOZ_ASSERT((icptr & CACHETYPE_MASK) == 0);
icptr |= static_cast<uintptr_t>(CacheType::IC);
p = icptr;
}
void destroy(JSFreeOp* fop, BaseShape* base);
void maybePurgeCache(JSFreeOp* fop, BaseShape* base);
void trace(JSTracer* trc);
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
size_t size = 0;
if (isIC()) {
size = getICPointer()->sizeOfIncludingThis(mallocSizeOf);
} else if (isTable()) {
size = getTablePointer()->sizeOfIncludingThis(mallocSizeOf);
}
return size;
}
uint32_t entryCount() {
uint32_t count = 0;
if (isIC()) {
count = getICPointer()->entryCount();
} else if (isTable()) {
count = getTablePointer()->entryCount();
}
return count;
}
#ifdef JSGC_HASH_TABLE_CHECKS
void checkAfterMovingGC();
#endif
};
// Ensures no shape tables are purged in the current zone.
class MOZ_RAII AutoKeepShapeCaches {
JSContext* cx_;
bool prev_;
public:
void operator=(const AutoKeepShapeCaches&) = delete;
AutoKeepShapeCaches(const AutoKeepShapeCaches&) = delete;
explicit inline AutoKeepShapeCaches(JSContext* cx);
inline ~AutoKeepShapeCaches();
};
/*
* Shapes encode information about both a property lineage *and* a particular
* property. This information is split across the Shape and the BaseShape
* at shape->base(). Both Shape and BaseShape can be either owned or unowned
* by, respectively, the Object or Shape referring to them.
*
* Owned Shapes are used in dictionary objects, and form a doubly linked list
* whose entries are all owned by that dictionary. Unowned Shapes are all in
* the property tree.
*
* Owned BaseShapes are used for shapes which have shape tables, including the
* last properties in all dictionaries. Unowned BaseShapes compactly store
* information common to many shapes. In a given zone there is a single
* BaseShape for each combination of BaseShape information. This information is
* cloned in owned BaseShapes so that information can be quickly looked up for a
* given object or shape without regard to whether the base shape is owned or
* not.
*
* All combinations of owned/unowned Shapes/BaseShapes are possible:
*
* Owned Shape, Owned BaseShape:
*
* Last property in a dictionary object. The BaseShape is transferred from
* property to property as the object's last property changes.
*
* Owned Shape, Unowned BaseShape:
*
* Property in a dictionary object other than the last one.
*
* Unowned Shape, Owned BaseShape:
*
* Property in the property tree which has a shape table.
*
* Unowned Shape, Unowned BaseShape:
*
* Property in the property tree which does not have a shape table.
*
* BaseShapes additionally encode some information about the referring object
* itself. This includes the object's class and various flags that may be set
* for the object. Except for the class, this information is mutable and may
* change when the object has an established property lineage. On such changes
* the entire property lineage is not updated, but rather only the last property
* (and its base shape). This works because only the object's last property is
* used to query information about the object. Care must be taken to call
* JSObject::canRemoveLastProperty when unwinding an object to an earlier
* property, however.
*/
class AccessorShape;
class Shape;
class UnownedBaseShape;
struct StackBaseShape;
class BaseShape : public gc::TenuredCell {
public:
friend class Shape;
friend struct StackBaseShape;
friend struct StackShape;
enum Flag {
/* Owned by the referring shape. */
OWNED_SHAPE = 0x1,
/* (0x2 and 0x4 are unused) */
/*
* Flags set which describe the referring object. Once set these cannot
* be unset (except during object densification of sparse indexes), and
* are transferred from shape to shape as the object's last property
* changes.
*
* If you add a new flag here, please add appropriate code to
* JSObject::dump to dump it as part of object representation.
*/
DELEGATE = 0x8,
NOT_EXTENSIBLE = 0x10,
INDEXED = 0x20,
HAS_INTERESTING_SYMBOL = 0x40,
HAD_ELEMENTS_ACCESS = 0x80,
// 0x100 is unused.
ITERATED_SINGLETON = 0x200,
NEW_GROUP_UNKNOWN = 0x400,
UNCACHEABLE_PROTO = 0x800,
IMMUTABLE_PROTOTYPE = 0x1000,
// See JSObject::isQualifiedVarObj().
QUALIFIED_VAROBJ = 0x2000,
// 0x4000 is unused.
// 0x8000 is unused.
OBJECT_FLAG_MASK = 0xfff8
};
private:
const JSClass* clasp_; /* Class of referring object. */
uint32_t flags; /* Vector of above flags. */
uint32_t slotSpan_; /* Object slot span for BaseShapes at
* dictionary last properties. */
/* For owned BaseShapes, the canonical unowned BaseShape. */
GCPtrUnownedBaseShape unowned_;
/* For owned BaseShapes, the shape's shape table. */
ShapeCachePtr cache_;
BaseShape(const BaseShape& base) = delete;
BaseShape& operator=(const BaseShape& other) = delete;
public:
void finalize(JSFreeOp* fop);
explicit inline BaseShape(const StackBaseShape& base);
/* Not defined: BaseShapes must not be stack allocated. */
~BaseShape();
const JSClass* clasp() const { return clasp_; }
bool isOwned() const { return !!(flags & OWNED_SHAPE); }
static void copyFromUnowned(BaseShape& dest, UnownedBaseShape& src);
inline void adoptUnowned(UnownedBaseShape* other);
void setOwned(UnownedBaseShape* unowned) {
flags |= OWNED_SHAPE;
unowned_ = unowned;
}
uint32_t getObjectFlags() const { return flags & OBJECT_FLAG_MASK; }
bool hasTable() const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return cache_.isTable();
}
bool hasIC() const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return cache_.isIC();
}
void setTable(ShapeTable* table) {
MOZ_ASSERT(isOwned());
cache_.initializeTable(table);
}
void setIC(ShapeIC* ic) {
MOZ_ASSERT(isOwned());
cache_.initializeIC(ic);
}
ShapeCachePtr getCache(const AutoKeepShapeCaches&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return cache_;
}
ShapeCachePtr getCache(const JS::AutoCheckCannotGC&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return cache_;
}
ShapeTable* maybeTable(const AutoKeepShapeCaches&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return (cache_.isTable()) ? cache_.getTablePointer() : nullptr;
}
ShapeTable* maybeTable(const JS::AutoCheckCannotGC&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return (cache_.isTable()) ? cache_.getTablePointer() : nullptr;
}
ShapeIC* maybeIC(const AutoKeepShapeCaches&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return (cache_.isIC()) ? cache_.getICPointer() : nullptr;
}
ShapeIC* maybeIC(const JS::AutoCheckCannotGC&) const {
MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
return (cache_.isIC()) ? cache_.getICPointer() : nullptr;
}
void maybePurgeCache(JSFreeOp* fop) { cache_.maybePurgeCache(fop, this); }
uint32_t slotSpan() const {
MOZ_ASSERT(isOwned());
return slotSpan_;
}
void setSlotSpan(uint32_t slotSpan) {
MOZ_ASSERT(isOwned());
slotSpan_ = slotSpan;
}
/*
* Lookup base shapes from the zone's baseShapes table, adding if not
* already found.
*/
static UnownedBaseShape* getUnowned(JSContext* cx, StackBaseShape& base);
/* Get the canonical base shape. */
inline UnownedBaseShape* unowned();
/* Get the canonical base shape for an owned one. */
inline UnownedBaseShape* baseUnowned();
/* Get the canonical base shape for an unowned one (i.e. identity). */
inline UnownedBaseShape* toUnowned();
/* Check that an owned base shape is consistent with its unowned base. */
void assertConsistency();
/* For JIT usage */
static inline size_t offsetOfFlags() { return offsetof(BaseShape, flags); }
static const JS::TraceKind TraceKind = JS::TraceKind::BaseShape;
void traceChildren(JSTracer* trc);
void traceChildrenSkipShapeCache(JSTracer* trc);
#ifdef DEBUG
bool canSkipMarkingShapeCache(Shape* lastShape);
#endif
private:
static void staticAsserts() {
static_assert(offsetof(BaseShape, clasp_) ==
offsetof(js::shadow::BaseShape, clasp_));
static_assert(sizeof(BaseShape) % gc::CellAlignBytes == 0,
"Things inheriting from gc::Cell must have a size that's "
"a multiple of gc::CellAlignBytes");
}
void traceShapeCache(JSTracer* trc);
};
class UnownedBaseShape : public BaseShape {};
UnownedBaseShape* BaseShape::unowned() {
return isOwned() ? baseUnowned() : toUnowned();
}
UnownedBaseShape* BaseShape::toUnowned() {
MOZ_ASSERT(!isOwned() && !unowned_);
return static_cast<UnownedBaseShape*>(this);
}
UnownedBaseShape* BaseShape::baseUnowned() {
MOZ_ASSERT(isOwned() && unowned_);
return unowned_;
}
/* Entries for the per-zone baseShapes set of unowned base shapes. */
struct StackBaseShape : public DefaultHasher<WeakHeapPtr<UnownedBaseShape*>> {
uint32_t flags;
const JSClass* clasp;
explicit StackBaseShape(BaseShape* base)
: flags(base->flags & BaseShape::OBJECT_FLAG_MASK), clasp(base->clasp_) {}
inline StackBaseShape(const JSClass* clasp, uint32_t objectFlags);
explicit inline StackBaseShape(Shape* shape);
struct Lookup {
uint32_t flags;
const JSClass* clasp;
MOZ_IMPLICIT Lookup(const StackBaseShape& base)
: flags(base.flags), clasp(base.clasp) {}
MOZ_IMPLICIT Lookup(UnownedBaseShape* base)
: flags(base->getObjectFlags()), clasp(base->clasp()) {
MOZ_ASSERT(!base->isOwned());
}
explicit Lookup(const WeakHeapPtr<UnownedBaseShape*>& base)
: flags(base.unbarrieredGet()->getObjectFlags()),
clasp(base.unbarrieredGet()->clasp()) {
MOZ_ASSERT(!base.unbarrieredGet()->isOwned());
}
};
static HashNumber hash(const Lookup& lookup) {
return mozilla::HashGeneric(lookup.flags, lookup.clasp);
}
static inline bool match(const WeakHeapPtr<UnownedBaseShape*>& key,
const Lookup& lookup) {
return key.unbarrieredGet()->flags == lookup.flags &&
key.unbarrieredGet()->clasp_ == lookup.clasp;
}
};
static MOZ_ALWAYS_INLINE js::HashNumber HashId(jsid id) {
// HashGeneric alone would work, but bits of atom and symbol addresses
// could then be recovered from the hash code. See bug 1330769.
if (MOZ_LIKELY(JSID_IS_ATOM(id))) {
return JSID_TO_ATOM(id)->hash();
}
if (JSID_IS_SYMBOL(id)) {
return JSID_TO_SYMBOL(id)->hash();
}
return mozilla::HashGeneric(JSID_BITS(id));
}
} // namespace js
namespace mozilla {
template <>
struct DefaultHasher<jsid> {
using Lookup = jsid;
static HashNumber hash(jsid id) { return js::HashId(id); }
static bool match(jsid id1, jsid id2) { return id1 == id2; }
};
} // namespace mozilla
namespace js {
using BaseShapeSet =
JS::WeakCache<JS::GCHashSet<WeakHeapPtr<UnownedBaseShape*>, StackBaseShape,
SystemAllocPolicy>>;
class Shape : public gc::TenuredCell {
friend class ::JSObject;
friend class ::JSFunction;
friend class GCMarker;
friend class NativeObject;
friend class PropertyTree;
friend class TenuringTracer;
friend struct StackBaseShape;
friend struct StackShape;
friend class JS::ubi::Concrete<Shape>;
friend class js::gc::RelocationOverlay;
protected:
GCPtrBaseShape base_;
const GCPtrId propid_;
// Flags that are not modified after the Shape is created. Off-thread Ion
// compilation can access the immutableFlags word, so we don't want any
// mutable state here to avoid (TSan) races.
enum ImmutableFlags : uint32_t {
// Mask to get the index in object slots for isDataProperty() shapes.
// For other shapes in the property tree with a parent, stores the
// parent's slot index (which may be invalid), and invalid for all
// other shapes.
SLOT_MASK = BitMask(24),
// Number of fixed slots in objects with this shape.
// FIXED_SLOTS_MAX is the biggest count of fixed slots a Shape can store.
FIXED_SLOTS_MAX = 0x1f,
FIXED_SLOTS_SHIFT = 24,
FIXED_SLOTS_MASK = uint32_t(FIXED_SLOTS_MAX << FIXED_SLOTS_SHIFT),
// Property stored in per-object dictionary, not shared property tree.
IN_DICTIONARY = 1 << 29,
// This shape is an AccessorShape, a fat Shape that can store
// getter/setter information.
ACCESSOR_SHAPE = 1 << 30,
};
// Flags stored in mutableFlags.
enum MutableFlags : uint8_t {
// numLinearSearches starts at zero and is incremented initially on
// search() calls. Once numLinearSearches reaches LINEAR_SEARCHES_MAX,
// the inline cache is created on the next search() call. Once the
// cache is full, it self transforms into a hash table. The hash table
// can also be created directly when hashifying for dictionary mode.
LINEAR_SEARCHES_MAX = 0x5,
LINEAR_SEARCHES_MASK = 0x7,
// Slotful property was stored to more than once. This is used as a
// hint for type inference.
OVERWRITTEN = 0x08,
// Flags used to speed up isBigEnoughForAShapeTable().
HAS_CACHED_BIG_ENOUGH_FOR_SHAPE_TABLE = 0x10,
CACHED_BIG_ENOUGH_FOR_SHAPE_TABLE = 0x20,
};
uint32_t immutableFlags; /* immutable flags, see above */
uint8_t attrs; /* attributes, see jsapi.h JSPROP_* */
uint8_t mutableFlags; /* mutable flags, see below for defines */
GCPtrShape parent; /* parent node, reverse for..in order */