-
Notifications
You must be signed in to change notification settings - Fork 54
/
TypeInference-inl.h
1455 lines (1220 loc) · 45 KB
/
TypeInference-inl.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/. */
/* Inline members for javascript type inference. */
#ifndef vm_TypeInference_inl_h
#define vm_TypeInference_inl_h
#include "vm/TypeInference.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/Casting.h"
#include "mozilla/PodOperations.h"
#include <utility> // for ::std::swap
#include "builtin/Symbol.h"
#include "gc/GC.h"
#include "jit/BaselineJIT.h"
#include "js/HeapAPI.h"
#include "vm/ArrayObject.h"
#include "vm/BooleanObject.h"
#include "vm/JSFunction.h"
#include "vm/NativeObject.h"
#include "vm/NumberObject.h"
#include "vm/ObjectGroup.h"
#include "vm/Shape.h"
#include "vm/SharedArrayObject.h"
#include "vm/StringObject.h"
#include "vm/TypedArrayObject.h"
#include "vm/UnboxedObject.h"
#include "vm/JSContext-inl.h"
#include "vm/ObjectGroup-inl.h"
namespace js {
/////////////////////////////////////////////////////////////////////
// RecompileInfo
/////////////////////////////////////////////////////////////////////
jit::IonScript* RecompileInfo::maybeIonScriptToInvalidate(
const TypeZone& zone) const {
MOZ_ASSERT(script_->zone() == zone.zone());
// Make sure this is not called under CodeGenerator::link (before the
// IonScript is created).
MOZ_ASSERT_IF(zone.currentCompilationId(),
zone.currentCompilationId().ref() != id_);
if (!script_->hasIonScript() ||
script_->ionScript()->compilationId() != id_) {
return nullptr;
}
return script_->ionScript();
}
inline bool RecompileInfo::shouldSweep(const TypeZone& zone) {
if (IsAboutToBeFinalizedUnbarriered(&script_)) {
return true;
}
MOZ_ASSERT(script_->zone() == zone.zone());
// Don't sweep if we're called under CodeGenerator::link, before the
// IonScript is created.
if (zone.currentCompilationId() && zone.currentCompilationId().ref() == id_) {
return false;
}
return maybeIonScriptToInvalidate(zone) == nullptr;
}
/////////////////////////////////////////////////////////////////////
// Types
/////////////////////////////////////////////////////////////////////
/* static */ inline TypeSet::ObjectKey* TypeSet::ObjectKey::get(JSObject* obj) {
MOZ_ASSERT(obj);
if (obj->isSingleton()) {
return (ObjectKey*)(uintptr_t(obj) | 1);
}
return (ObjectKey*)obj->group();
}
/* static */ inline TypeSet::ObjectKey* TypeSet::ObjectKey::get(
ObjectGroup* group) {
MOZ_ASSERT(group);
if (group->singleton()) {
return (ObjectKey*)(uintptr_t(group->singleton()) | 1);
}
return (ObjectKey*)group;
}
inline ObjectGroup* TypeSet::ObjectKey::groupNoBarrier() {
MOZ_ASSERT(isGroup());
return (ObjectGroup*)this;
}
inline JSObject* TypeSet::ObjectKey::singletonNoBarrier() {
MOZ_ASSERT(isSingleton());
return (JSObject*)(uintptr_t(this) & ~1);
}
inline ObjectGroup* TypeSet::ObjectKey::group() {
ObjectGroup* res = groupNoBarrier();
ObjectGroup::readBarrier(res);
return res;
}
inline JSObject* TypeSet::ObjectKey::singleton() {
JSObject* res = singletonNoBarrier();
JSObject::readBarrier(res);
return res;
}
inline JS::Compartment* TypeSet::ObjectKey::maybeCompartment() {
if (isSingleton()) {
return singletonNoBarrier()->compartment();
}
return groupNoBarrier()->compartment();
}
/* static */ inline TypeSet::Type TypeSet::ObjectType(const JSObject* obj) {
if (obj->isSingleton()) {
return Type(uintptr_t(obj) | 1);
}
return Type(uintptr_t(obj->group()));
}
/* static */ inline TypeSet::Type TypeSet::ObjectType(
const ObjectGroup* group) {
if (group->singleton()) {
return Type(uintptr_t(group->singleton()) | 1);
}
return Type(uintptr_t(group));
}
/* static */ inline TypeSet::Type TypeSet::ObjectType(const ObjectKey* obj) {
return Type(uintptr_t(obj));
}
inline TypeSet::Type TypeSet::GetValueType(const Value& val) {
if (val.isDouble()) {
return TypeSet::DoubleType();
}
if (val.isObject()) {
return TypeSet::ObjectType(&val.toObject());
}
return TypeSet::PrimitiveType(val.extractNonDoubleType());
}
inline bool TypeSet::IsUntrackedValue(const Value& val) {
return val.isMagic() && (val.whyMagic() == JS_OPTIMIZED_OUT ||
val.whyMagic() == JS_UNINITIALIZED_LEXICAL);
}
inline TypeSet::Type TypeSet::GetMaybeUntrackedValueType(const Value& val) {
return IsUntrackedValue(val) ? UnknownType() : GetValueType(val);
}
inline TypeFlags PrimitiveTypeFlag(ValueType type) {
switch (type) {
case ValueType::Undefined:
return TYPE_FLAG_UNDEFINED;
case ValueType::Null:
return TYPE_FLAG_NULL;
case ValueType::Boolean:
return TYPE_FLAG_BOOLEAN;
case ValueType::Int32:
return TYPE_FLAG_INT32;
case ValueType::Double:
return TYPE_FLAG_DOUBLE;
case ValueType::String:
return TYPE_FLAG_STRING;
case ValueType::Symbol:
return TYPE_FLAG_SYMBOL;
case ValueType::BigInt:
return TYPE_FLAG_BIGINT;
case ValueType::Magic:
return TYPE_FLAG_LAZYARGS;
case ValueType::PrivateGCThing:
case ValueType::Object:
break;
}
MOZ_CRASH("Bad ValueType");
}
inline JSValueType TypeFlagPrimitive(TypeFlags flags) {
switch (flags) {
case TYPE_FLAG_UNDEFINED:
return JSVAL_TYPE_UNDEFINED;
case TYPE_FLAG_NULL:
return JSVAL_TYPE_NULL;
case TYPE_FLAG_BOOLEAN:
return JSVAL_TYPE_BOOLEAN;
case TYPE_FLAG_INT32:
return JSVAL_TYPE_INT32;
case TYPE_FLAG_DOUBLE:
return JSVAL_TYPE_DOUBLE;
case TYPE_FLAG_STRING:
return JSVAL_TYPE_STRING;
case TYPE_FLAG_SYMBOL:
return JSVAL_TYPE_SYMBOL;
case TYPE_FLAG_BIGINT:
return JSVAL_TYPE_BIGINT;
case TYPE_FLAG_LAZYARGS:
return JSVAL_TYPE_MAGIC;
default:
MOZ_CRASH("Bad TypeFlags");
}
}
/*
* Get the canonical representation of an id to use when doing inference. This
* maintains the constraint that if two different jsids map to the same property
* in JS (e.g. 3 and "3"), they have the same type representation.
*/
inline jsid IdToTypeId(jsid id) {
MOZ_ASSERT(!JSID_IS_EMPTY(id));
// All properties which can be stored in an object's dense elements must
// map to the aggregate property for index types.
return JSID_IS_INT(id) ? JSID_VOID : id;
}
const char* TypeIdStringImpl(jsid id);
/* Convert an id for printing during debug. */
static inline const char* TypeIdString(jsid id) {
#ifdef DEBUG
return TypeIdStringImpl(id);
#else
return "(missing)";
#endif
}
// New script properties analyses overview.
//
// When constructing objects using 'new' on a script, we attempt to determine
// the properties which that object will eventually have. This is done via two
// analyses. One of these, the definite properties analysis, is static, and the
// other, the acquired properties analysis, is dynamic. As objects are
// constructed using 'new' on some script to create objects of group G, our
// analysis strategy is as follows:
//
// - When the first objects are created, no analysis is immediately performed.
// Instead, all objects of group G are accumulated in an array.
//
// - After a certain number of such objects have been created, the definite
// properties analysis is performed. This analyzes the body of the
// constructor script and any other functions it calls to look for properties
// which will definitely be added by the constructor in a particular order,
// creating an object with shape S.
//
// - The properties in S are compared with the greatest common prefix P of the
// shapes of the objects that have been created. If P has more properties
// than S, the acquired properties analysis is performed.
//
// - The acquired properties analysis marks all properties in P as definite
// in G, and creates a new group IG for objects which are partially
// initialized. Objects of group IG are initially created with shape S, and if
// they are later given shape P, their group can be changed to G.
//
// For objects which are rarely created, the definite properties analysis can
// be triggered after only one or a few objects have been allocated, when code
// being Ion compiled might access them. In this case type information in the
// constructor might not be good enough for the definite properties analysis to
// compute useful information, but the acquired properties analysis will still
// be able to identify definite properties in this case.
//
// This layered approach is designed to maximize performance on easily
// analyzable code, while still allowing us to determine definite properties
// robustly when code consistently adds the same properties to objects, but in
// complex ways which can't be understood statically.
class TypeNewScript {
private:
// Scripted function which this information was computed for.
HeapPtr<JSFunction*> function_ = {};
// Any preliminary objects with the type. The analyses are not performed
// until this array is cleared.
PreliminaryObjectArray* preliminaryObjects = nullptr;
// After the new script properties analyses have been performed, a template
// object to use for newly constructed objects. The shape of this object
// reflects all definite properties the object will have, and the
// allocation kind to use. This is null if the new objects have an unboxed
// layout, in which case the UnboxedLayout provides the initial structure
// of the object.
HeapPtr<PlainObject*> templateObject_ = {};
// Order in which definite properties become initialized. We need this in
// case the definite properties are invalidated (such as by adding a setter
// to an object on the prototype chain) while an object is in the middle of
// being initialized, so we can walk the stack and fixup any objects which
// look for in-progress objects which were prematurely set with an incorrect
// shape. Property assignments in inner frames are preceded by a series of
// SETPROP_FRAME entries specifying the stack down to the frame containing
// the write.
TypeNewScriptInitializer* initializerList = nullptr;
// If there are additional properties found by the acquired properties
// analysis which were not found by the definite properties analysis, this
// shape contains all such additional properties (plus the definite
// properties). When an object of this group acquires this shape, it is
// fully initialized and its group can be changed to initializedGroup.
HeapPtr<Shape*> initializedShape_ = {};
// Group with definite properties set for all properties found by
// both the definite and acquired properties analyses.
HeapPtr<ObjectGroup*> initializedGroup_ = {};
public:
TypeNewScript() = default;
~TypeNewScript() {
js_delete(preliminaryObjects);
js_free(initializerList);
}
void clear() {
function_ = nullptr;
templateObject_ = nullptr;
initializedShape_ = nullptr;
initializedGroup_ = nullptr;
}
static void writeBarrierPre(TypeNewScript* newScript);
bool analyzed() const { return preliminaryObjects == nullptr; }
PlainObject* templateObject() const { return templateObject_; }
Shape* initializedShape() const { return initializedShape_; }
ObjectGroup* initializedGroup() const { return initializedGroup_; }
JSFunction* function() const { return function_; }
void trace(JSTracer* trc);
void sweep();
void registerNewObject(PlainObject* res);
bool maybeAnalyze(JSContext* cx, ObjectGroup* group, bool* regenerate,
bool force = false);
bool rollbackPartiallyInitializedObjects(JSContext* cx, ObjectGroup* group);
static bool make(JSContext* cx, ObjectGroup* group, JSFunction* fun);
static TypeNewScript* makeNativeVersion(JSContext* cx,
TypeNewScript* newScript,
PlainObject* templateObject);
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
static size_t offsetOfPreliminaryObjects() {
return offsetof(TypeNewScript, preliminaryObjects);
}
};
inline UnboxedLayout::~UnboxedLayout() {
if (newScript_) {
newScript_->clear();
}
js_delete(newScript_);
js_free(traceList_);
nativeGroup_.init(nullptr);
nativeShape_.init(nullptr);
replacementGroup_.init(nullptr);
constructorCode_.init(nullptr);
}
inline bool ObjectGroup::hasUnanalyzedPreliminaryObjects() {
return (newScriptDontCheckGeneration() &&
!newScriptDontCheckGeneration()->analyzed()) ||
maybePreliminaryObjectsDontCheckGeneration();
}
/*
* Structure for type inference entry point functions. All functions which can
* change type information must use this, and functions which depend on
* intermediate types (i.e. JITs) can use this to ensure that intermediate
* information is not collected and does not change.
*
* Ensures that GC cannot occur. Does additional sanity checking that inference
* is not reentrant and that recompilations occur properly.
*/
struct MOZ_RAII AutoEnterAnalysis {
// For use when initializing an UnboxedLayout. The UniquePtr's destructor
// must run when GC is not suppressed.
UniquePtr<UnboxedLayout> unboxedLayoutToCleanUp;
// Prevent GC activity in the middle of analysis.
gc::AutoSuppressGC suppressGC;
// Allow clearing inference info on OOM during incremental sweeping. This is
// constructed for the outermost AutoEnterAnalysis on the stack.
mozilla::Maybe<AutoClearTypeInferenceStateOnOOM> oom;
// Pending recompilations to perform before execution of JIT code can resume.
RecompileInfoVector pendingRecompiles;
// Prevent us from calling the objectMetadataCallback.
js::AutoSuppressAllocationMetadataBuilder suppressMetadata;
FreeOp* freeOp;
Zone* zone;
explicit AutoEnterAnalysis(JSContext* cx)
: suppressGC(cx), suppressMetadata(cx) {
init(cx->defaultFreeOp(), cx->zone());
}
AutoEnterAnalysis(FreeOp* fop, Zone* zone)
: suppressGC(TlsContext.get()), suppressMetadata(zone) {
init(fop, zone);
}
~AutoEnterAnalysis() {
if (this != zone->types.activeAnalysis) {
return;
}
zone->types.activeAnalysis = nullptr;
if (!pendingRecompiles.empty()) {
zone->types.processPendingRecompiles(freeOp, pendingRecompiles);
}
}
private:
void init(FreeOp* fop, Zone* zone) {
#ifdef JS_CRASH_DIAGNOSTICS
MOZ_RELEASE_ASSERT(CurrentThreadCanAccessZone(zone));
#endif
this->freeOp = fop;
this->zone = zone;
if (!zone->types.activeAnalysis) {
oom.emplace(zone);
zone->types.activeAnalysis = this;
}
}
};
/////////////////////////////////////////////////////////////////////
// Interface functions
/////////////////////////////////////////////////////////////////////
void MarkIteratorUnknownSlow(JSContext* cx);
void TypeMonitorCallSlow(JSContext* cx, JSObject* callee, const CallArgs& args,
bool constructing);
/*
* Monitor a javascript call, either on entry to the interpreter or made
* from within the interpreter.
*/
inline void TypeMonitorCall(JSContext* cx, const js::CallArgs& args,
bool constructing) {
if (args.callee().is<JSFunction>()) {
JSFunction* fun = &args.callee().as<JSFunction>();
if (fun->isInterpreted() && fun->nonLazyScript()->types()) {
TypeMonitorCallSlow(cx, &args.callee(), args, constructing);
}
}
}
MOZ_ALWAYS_INLINE bool TrackPropertyTypes(JSObject* obj, jsid id) {
if (obj->hasLazyGroup() ||
obj->group()->unknownPropertiesDontCheckGeneration()) {
return false;
}
if (obj->isSingleton() &&
!obj->group()->maybeGetPropertyDontCheckGeneration(id)) {
return false;
}
return true;
}
void EnsureTrackPropertyTypes(JSContext* cx, JSObject* obj, jsid id);
inline bool CanHaveEmptyPropertyTypesForOwnProperty(JSObject* obj) {
// Per the comment on TypeSet::propertySet, property type sets for global
// objects may be empty for 'own' properties if the global property still
// has its initial undefined value.
return obj->is<GlobalObject>();
}
inline bool PropertyHasBeenMarkedNonConstant(JSObject* obj, jsid id) {
// Non-constant properties are only relevant for singleton objects.
if (!obj->isSingleton()) {
return true;
}
// EnsureTrackPropertyTypes must have been called on this object.
AutoSweepObjectGroup sweep(obj->group());
if (obj->group()->unknownProperties(sweep)) {
return true;
}
HeapTypeSet* types = obj->group()->maybeGetProperty(sweep, IdToTypeId(id));
return types->nonConstantProperty();
}
MOZ_ALWAYS_INLINE bool HasTrackedPropertyType(JSObject* obj, jsid id,
TypeSet::Type type) {
MOZ_ASSERT(id == IdToTypeId(id));
MOZ_ASSERT(TrackPropertyTypes(obj, id));
if (HeapTypeSet* types =
obj->group()->maybeGetPropertyDontCheckGeneration(id)) {
if (!types->hasType(type)) {
return false;
}
// Non-constant properties are only relevant for singleton objects.
if (obj->isSingleton() && !types->nonConstantProperty()) {
return false;
}
return true;
}
return false;
}
MOZ_ALWAYS_INLINE bool HasTypePropertyId(JSObject* obj, jsid id,
TypeSet::Type type) {
id = IdToTypeId(id);
if (!TrackPropertyTypes(obj, id)) {
return true;
}
return HasTrackedPropertyType(obj, id, type);
}
MOZ_ALWAYS_INLINE bool HasTypePropertyId(JSObject* obj, jsid id,
const Value& value) {
return HasTypePropertyId(obj, id, TypeSet::GetValueType(value));
}
void AddTypePropertyId(JSContext* cx, ObjectGroup* group, JSObject* obj,
jsid id, TypeSet::Type type);
void AddTypePropertyId(JSContext* cx, ObjectGroup* group, JSObject* obj,
jsid id, const Value& value);
/* Add a possible type for a property of obj. */
MOZ_ALWAYS_INLINE void AddTypePropertyId(JSContext* cx, JSObject* obj, jsid id,
TypeSet::Type type) {
id = IdToTypeId(id);
if (TrackPropertyTypes(obj, id) && !HasTrackedPropertyType(obj, id, type)) {
AddTypePropertyId(cx, obj->group(), obj, id, type);
}
}
MOZ_ALWAYS_INLINE void AddTypePropertyId(JSContext* cx, JSObject* obj, jsid id,
const Value& value) {
return AddTypePropertyId(cx, obj, id, TypeSet::GetValueType(value));
}
inline void MarkObjectGroupFlags(JSContext* cx, JSObject* obj,
ObjectGroupFlags flags) {
if (obj->hasLazyGroup()) {
return;
}
AutoSweepObjectGroup sweep(obj->group());
if (!obj->group()->hasAllFlags(sweep, flags)) {
obj->group()->setFlags(sweep, cx, flags);
}
}
inline void MarkObjectGroupUnknownProperties(JSContext* cx, ObjectGroup* obj) {
AutoSweepObjectGroup sweep(obj);
if (!obj->unknownProperties(sweep)) {
obj->markUnknown(sweep, cx);
}
}
inline void MarkTypePropertyNonData(JSContext* cx, JSObject* obj, jsid id) {
id = IdToTypeId(id);
if (TrackPropertyTypes(obj, id)) {
obj->group()->markPropertyNonData(cx, obj, id);
}
}
inline void MarkTypePropertyNonWritable(JSContext* cx, JSObject* obj, jsid id) {
id = IdToTypeId(id);
if (TrackPropertyTypes(obj, id)) {
obj->group()->markPropertyNonWritable(cx, obj, id);
}
}
/* Mark a state change on a particular object. */
inline void MarkObjectStateChange(JSContext* cx, JSObject* obj) {
if (obj->hasLazyGroup()) {
return;
}
AutoSweepObjectGroup sweep(obj->group());
if (!obj->group()->unknownProperties(sweep)) {
obj->group()->markStateChange(sweep, cx);
}
}
/* Interface helpers for JSScript*. */
extern void TypeMonitorResult(JSContext* cx, JSScript* script, jsbytecode* pc,
TypeSet::Type type);
extern void TypeMonitorResult(JSContext* cx, JSScript* script, jsbytecode* pc,
StackTypeSet* types, TypeSet::Type type);
extern void TypeMonitorResult(JSContext* cx, JSScript* script, jsbytecode* pc,
const Value& rval);
/////////////////////////////////////////////////////////////////////
// Script interface functions
/////////////////////////////////////////////////////////////////////
/* static */ inline StackTypeSet* TypeScript::ThisTypes(JSScript* script) {
if (TypeScript* types = script->types()) {
AutoSweepTypeScript sweep(script);
return types->typeArray(sweep) + script->numBytecodeTypeSets();
}
return nullptr;
}
/*
* Note: for non-escaping arguments, argTypes reflect only the initial type of
* the variable (e.g. passed values for argTypes, or undefined for localTypes)
* and not types from subsequent assignments.
*/
/* static */ inline StackTypeSet* TypeScript::ArgTypes(JSScript* script,
unsigned i) {
MOZ_ASSERT(i < script->functionNonDelazifying()->nargs());
if (TypeScript* types = script->types()) {
AutoSweepTypeScript sweep(script);
return types->typeArray(sweep) + script->numBytecodeTypeSets() + 1 + i;
}
return nullptr;
}
template <typename TYPESET>
/* static */ inline TYPESET* TypeScript::BytecodeTypes(JSScript* script,
jsbytecode* pc,
uint32_t* bytecodeMap,
uint32_t* hint,
TYPESET* typeArray) {
MOZ_ASSERT(CodeSpec[*pc].format & JOF_TYPESET);
uint32_t offset = script->pcToOffset(pc);
// See if this pc is the next typeset opcode after the last one looked up.
size_t numBytecodeTypeSets = script->numBytecodeTypeSets();
if ((*hint + 1) < numBytecodeTypeSets && bytecodeMap[*hint + 1] == offset) {
(*hint)++;
return typeArray + *hint;
}
// See if this pc is the same as the last one looked up.
if (bytecodeMap[*hint] == offset) {
return typeArray + *hint;
}
// Fall back to a binary search. We'll either find the exact offset, or
// there are more JOF_TYPESET opcodes than nTypeSets in the script (as can
// happen if the script is very long) and we'll use the last location.
size_t loc;
bool found =
mozilla::BinarySearch(bytecodeMap, 0, numBytecodeTypeSets, offset, &loc);
if (found) {
MOZ_ASSERT(bytecodeMap[loc] == offset);
} else {
MOZ_ASSERT(numBytecodeTypeSets == JSScript::MaxBytecodeTypeSets);
loc = numBytecodeTypeSets - 1;
}
*hint = mozilla::AssertedCast<uint32_t>(loc);
return typeArray + *hint;
}
/* static */ inline StackTypeSet* TypeScript::BytecodeTypes(JSScript* script,
jsbytecode* pc) {
MOZ_ASSERT(CurrentThreadCanAccessZone(script->zone()));
TypeScript* types = script->types();
if (!types) {
return nullptr;
}
AutoSweepTypeScript sweep(script);
uint32_t* hint = types->bytecodeTypeMapHint();
return BytecodeTypes(script, pc, types->bytecodeTypeMap(), hint,
types->typeArray(sweep));
}
/* static */ inline void TypeScript::Monitor(JSContext* cx, JSScript* script,
jsbytecode* pc,
const js::Value& rval) {
TypeMonitorResult(cx, script, pc, rval);
}
/* static */ inline void TypeScript::Monitor(JSContext* cx, JSScript* script,
jsbytecode* pc,
TypeSet::Type type) {
TypeMonitorResult(cx, script, pc, type);
}
/* static */ inline void TypeScript::Monitor(JSContext* cx,
const js::Value& rval) {
jsbytecode* pc;
RootedScript script(cx, cx->currentScript(&pc));
Monitor(cx, script, pc, rval);
}
/* static */ inline void TypeScript::Monitor(JSContext* cx, JSScript* script,
jsbytecode* pc,
StackTypeSet* types,
const js::Value& rval) {
TypeSet::Type type = TypeSet::GetValueType(rval);
if (!types->hasType(type)) {
TypeMonitorResult(cx, script, pc, types, type);
}
}
/* static */ inline void TypeScript::MonitorAssign(JSContext* cx,
HandleObject obj, jsid id) {
if (!obj->isSingleton()) {
/*
* Mark as unknown any object which has had dynamic assignments to
* non-integer properties at SETELEM opcodes. This avoids making large
* numbers of type properties for hashmap-style objects. We don't need
* to do this for objects with singleton type, because type properties
* are only constructed for them when analyzed scripts depend on those
* specific properties.
*/
uint32_t i;
if (IdIsIndex(id, &i)) {
return;
}
// But if we don't have too many properties yet, don't do anything. The
// idea here is that normal object initialization should not trigger
// deoptimization in most cases, while actual usage as a hashmap should.
ObjectGroup* group = obj->group();
if (group->basePropertyCountDontCheckGeneration() < 128) {
return;
}
MarkObjectGroupUnknownProperties(cx, group);
}
}
/* static */ inline void TypeScript::SetThis(JSContext* cx, JSScript* script,
TypeSet::Type type) {
cx->check(script, type);
AutoSweepTypeScript sweep(script);
StackTypeSet* types = ThisTypes(script);
if (!types) {
return;
}
if (!types->hasType(type)) {
AutoEnterAnalysis enter(cx);
InferSpew(ISpewOps, "externalType: setThis %p: %s", script,
TypeSet::TypeString(type).get());
types->addType(sweep, cx, type);
}
}
/* static */ inline void TypeScript::SetThis(JSContext* cx, JSScript* script,
const js::Value& value) {
SetThis(cx, script, TypeSet::GetValueType(value));
}
/* static */ inline void TypeScript::SetArgument(JSContext* cx,
JSScript* script, unsigned arg,
TypeSet::Type type) {
cx->check(script->compartment(), type);
AutoSweepTypeScript sweep(script);
StackTypeSet* types = ArgTypes(script, arg);
if (!types) {
return;
}
if (!types->hasType(type)) {
AutoEnterAnalysis enter(cx);
InferSpew(ISpewOps, "externalType: setArg %p %u: %s", script, arg,
TypeSet::TypeString(type).get());
types->addType(sweep, cx, type);
}
}
/* static */ inline void TypeScript::SetArgument(JSContext* cx,
JSScript* script, unsigned arg,
const js::Value& value) {
SetArgument(cx, script, arg, TypeSet::GetValueType(value));
}
inline AutoKeepTypeScripts::AutoKeepTypeScripts(JSContext* cx)
: zone_(cx->zone()->types), prev_(zone_.keepTypeScripts) {
zone_.keepTypeScripts = true;
}
inline AutoKeepTypeScripts::~AutoKeepTypeScripts() {
MOZ_ASSERT(zone_.keepTypeScripts);
zone_.keepTypeScripts = prev_;
}
/////////////////////////////////////////////////////////////////////
// TypeHashSet
/////////////////////////////////////////////////////////////////////
// Hashing code shared by objects in TypeSets and properties in ObjectGroups.
struct TypeHashSet {
// The sets of objects in a type set grow monotonically, are usually empty,
// almost always small, and sometimes big. For empty or singleton sets, the
// the pointer refers directly to the value. For sets fitting into
// SET_ARRAY_SIZE, an array of this length is used to store the elements.
// For larger sets, a hash table filled to 25%-50% of capacity is used,
// with collisions resolved by linear probing.
static const unsigned SET_ARRAY_SIZE = 8;
static const unsigned SET_CAPACITY_OVERFLOW = 1u << 30;
// Get the capacity of a set with the given element count.
static inline unsigned Capacity(unsigned count) {
MOZ_ASSERT(count >= 2);
MOZ_ASSERT(count < SET_CAPACITY_OVERFLOW);
if (count <= SET_ARRAY_SIZE) {
return SET_ARRAY_SIZE;
}
return 1u << (mozilla::FloorLog2(count) + 2);
}
// Compute the FNV hash for the low 32 bits of v.
template <class T, class KEY>
static inline uint32_t HashKey(T v) {
uint32_t nv = KEY::keyBits(v);
uint32_t hash = 84696351 ^ (nv & 0xff);
hash = (hash * 16777619) ^ ((nv >> 8) & 0xff);
hash = (hash * 16777619) ^ ((nv >> 16) & 0xff);
return (hash * 16777619) ^ ((nv >> 24) & 0xff);
}
// Insert space for an element into the specified set and grow its capacity
// if needed. returned value is an existing or new entry (nullptr if new).
template <class T, class U, class KEY>
static U** InsertTry(LifoAlloc& alloc, U**& values, unsigned& count, T key) {
unsigned capacity = Capacity(count);
unsigned insertpos = HashKey<T, KEY>(key) & (capacity - 1);
MOZ_RELEASE_ASSERT(uintptr_t(values[-1]) == capacity);
// Whether we are converting from a fixed array to hashtable.
bool converting = (count == SET_ARRAY_SIZE);
if (!converting) {
while (values[insertpos] != nullptr) {
if (KEY::getKey(values[insertpos]) == key) {
return &values[insertpos];
}
insertpos = (insertpos + 1) & (capacity - 1);
}
}
if (count >= SET_CAPACITY_OVERFLOW) {
return nullptr;
}
count++;
unsigned newCapacity = Capacity(count);
if (newCapacity == capacity) {
MOZ_ASSERT(!converting);
return &values[insertpos];
}
// Allocate an extra word right before the array storing the capacity,
// for sanity checks.
U** newValues = alloc.newArray<U*>(newCapacity + 1);
if (!newValues) {
return nullptr;
}
mozilla::PodZero(newValues, newCapacity + 1);
newValues[0] = (U*)uintptr_t(newCapacity);
newValues++;
for (unsigned i = 0; i < capacity; i++) {
if (values[i]) {
unsigned pos =
HashKey<T, KEY>(KEY::getKey(values[i])) & (newCapacity - 1);
while (newValues[pos] != nullptr) {
pos = (pos + 1) & (newCapacity - 1);
}
newValues[pos] = values[i];
}
}
values = newValues;
insertpos = HashKey<T, KEY>(key) & (newCapacity - 1);
while (values[insertpos] != nullptr) {
insertpos = (insertpos + 1) & (newCapacity - 1);
}
return &values[insertpos];
}
// Insert an element into the specified set if it is not already there,
// returning an entry which is nullptr if the element was not there.
template <class T, class U, class KEY>
static inline U** Insert(LifoAlloc& alloc, U**& values, unsigned& count,
T key) {
if (count == 0) {
MOZ_ASSERT(values == nullptr);
count++;
return (U**)&values;
}
if (count == 1) {
U* oldData = (U*)values;
if (KEY::getKey(oldData) == key) {
return (U**)&values;
}
// Allocate an extra word right before the array storing the
// capacity, for sanity checks.
values = alloc.newArray<U*>(SET_ARRAY_SIZE + 1);
if (!values) {
values = (U**)oldData;
return nullptr;
}
mozilla::PodZero(values, SET_ARRAY_SIZE + 1);
values[0] = (U*)uintptr_t(SET_ARRAY_SIZE);
values++;
count++;
values[0] = oldData;
return &values[1];
}
if (count <= SET_ARRAY_SIZE) {
MOZ_RELEASE_ASSERT(uintptr_t(values[-1]) == SET_ARRAY_SIZE);
for (unsigned i = 0; i < count; i++) {
if (KEY::getKey(values[i]) == key) {
return &values[i];
}
}
if (count < SET_ARRAY_SIZE) {
count++;
return &values[count - 1];
}
}
return InsertTry<T, U, KEY>(alloc, values, count, key);
}
// Lookup an entry in a hash set, return nullptr if it does not exist.
template <class T, class U, class KEY>
static MOZ_ALWAYS_INLINE U* Lookup(U** values, unsigned count, T key) {
if (count == 0) {
return nullptr;
}
if (count == 1) {
return (KEY::getKey((U*)values) == key) ? (U*)values : nullptr;
}
if (count <= SET_ARRAY_SIZE) {
MOZ_RELEASE_ASSERT(uintptr_t(values[-1]) == SET_ARRAY_SIZE);
for (unsigned i = 0; i < count; i++) {
if (KEY::getKey(values[i]) == key) {
return values[i];
}
}
return nullptr;
}
unsigned capacity = Capacity(count);
unsigned pos = HashKey<T, KEY>(key) & (capacity - 1);
MOZ_RELEASE_ASSERT(uintptr_t(values[-1]) == capacity);
while (values[pos] != nullptr) {
if (KEY::getKey(values[pos]) == key) {
return values[pos];