-
Notifications
You must be signed in to change notification settings - Fork 30.2k
/
Copy pathbuiltins-collections-gen.cc
2820 lines (2404 loc) Β· 111 KB
/
builtins-collections-gen.cc
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
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/builtins/builtins-collections-gen.h"
#include "src/builtins/builtins-constructor-gen.h"
#include "src/builtins/builtins-iterator-gen.h"
#include "src/builtins/builtins-utils-gen.h"
#include "src/codegen/code-stub-assembler.h"
#include "src/execution/protectors.h"
#include "src/heap/factory-inl.h"
#include "src/heap/heap-inl.h"
#include "src/objects/hash-table-inl.h"
#include "src/objects/js-collection.h"
#include "src/objects/ordered-hash-table.h"
#include "src/roots/roots.h"
namespace v8 {
namespace internal {
template <class T>
using TVariable = compiler::TypedCodeAssemblerVariable<T>;
void BaseCollectionsAssembler::AddConstructorEntry(
Variant variant, TNode<Context> context, TNode<Object> collection,
TNode<Object> add_function, TNode<Object> key_value,
Label* if_may_have_side_effects, Label* if_exception,
TVariable<Object>* var_exception) {
compiler::ScopedExceptionHandler handler(this, if_exception, var_exception);
CSA_DCHECK(this, Word32BinaryNot(IsTheHole(key_value)));
if (variant == kMap || variant == kWeakMap) {
TorqueStructKeyValuePair pair =
if_may_have_side_effects != nullptr
? LoadKeyValuePairNoSideEffects(context, key_value,
if_may_have_side_effects)
: LoadKeyValuePair(context, key_value);
TNode<Object> key_n = pair.key;
TNode<Object> value_n = pair.value;
Call(context, add_function, collection, key_n, value_n);
} else {
DCHECK(variant == kSet || variant == kWeakSet);
Call(context, add_function, collection, key_value);
}
}
void BaseCollectionsAssembler::AddConstructorEntries(
Variant variant, TNode<Context> context, TNode<Context> native_context,
TNode<HeapObject> collection, TNode<Object> initial_entries) {
TVARIABLE(BoolT, use_fast_loop,
IsFastJSArrayWithNoCustomIteration(context, initial_entries));
TNode<IntPtrT> at_least_space_for =
EstimatedInitialSize(initial_entries, use_fast_loop.value());
Label allocate_table(this, &use_fast_loop), exit(this), fast_loop(this),
slow_loop(this, Label::kDeferred);
TVARIABLE(JSReceiver, var_iterator_object);
TVARIABLE(Object, var_exception);
Label if_exception(this, Label::kDeferred);
Goto(&allocate_table);
BIND(&allocate_table);
{
TNode<HeapObject> table = AllocateTable(variant, at_least_space_for);
StoreObjectField(collection, GetTableOffset(variant), table);
GotoIf(IsNullOrUndefined(initial_entries), &exit);
GotoIfInitialAddFunctionModified(variant, CAST(native_context), collection,
&slow_loop);
Branch(use_fast_loop.value(), &fast_loop, &slow_loop);
}
BIND(&fast_loop);
{
Label if_exception_during_fast_iteration(this, Label::kDeferred);
TVARIABLE(IntPtrT, var_index, IntPtrConstant(0));
TNode<JSArray> initial_entries_jsarray =
UncheckedCast<JSArray>(initial_entries);
#if DEBUG
CSA_DCHECK(this, IsFastJSArrayWithNoCustomIteration(
context, initial_entries_jsarray));
TNode<Map> original_initial_entries_map = LoadMap(initial_entries_jsarray);
#endif
Label if_may_have_side_effects(this, Label::kDeferred);
{
compiler::ScopedExceptionHandler handler(
this, &if_exception_during_fast_iteration, &var_exception);
AddConstructorEntriesFromFastJSArray(
variant, context, native_context, collection, initial_entries_jsarray,
&if_may_have_side_effects, var_index);
}
Goto(&exit);
if (variant == kMap || variant == kWeakMap) {
BIND(&if_may_have_side_effects);
#if DEBUG
{
// Check that add/set function has not been modified.
Label if_not_modified(this), if_modified(this);
GotoIfInitialAddFunctionModified(variant, CAST(native_context),
collection, &if_modified);
Goto(&if_not_modified);
BIND(&if_modified);
Unreachable();
BIND(&if_not_modified);
}
CSA_DCHECK(this, TaggedEqual(original_initial_entries_map,
LoadMap(initial_entries_jsarray)));
#endif
use_fast_loop = Int32FalseConstant();
Goto(&allocate_table);
}
BIND(&if_exception_during_fast_iteration);
{
// In case exception is thrown during collection population, materialize
// the iteator and execute iterator closing protocol. It might be
// non-trivial in case "return" callback is added somewhere in the
// iterator's prototype chain.
TNode<NativeContext> native_context = LoadNativeContext(context);
TNode<IntPtrT> next_index =
IntPtrAdd(var_index.value(), IntPtrConstant(1));
var_iterator_object = CreateArrayIterator(
native_context, UncheckedCast<JSArray>(initial_entries),
IterationKind::kValues, SmiTag(next_index));
Goto(&if_exception);
}
}
BIND(&slow_loop);
{
AddConstructorEntriesFromIterable(
variant, context, native_context, collection, initial_entries,
&if_exception, &var_iterator_object, &var_exception);
Goto(&exit);
}
BIND(&if_exception);
{
TNode<HeapObject> message = GetPendingMessage();
SetPendingMessage(TheHoleConstant());
// iterator.next field is not used by IteratorCloseOnException.
TorqueStructIteratorRecord iterator = {var_iterator_object.value(), {}};
IteratorCloseOnException(context, iterator);
CallRuntime(Runtime::kReThrowWithMessage, context, var_exception.value(),
message);
Unreachable();
}
BIND(&exit);
}
void BaseCollectionsAssembler::AddConstructorEntriesFromFastJSArray(
Variant variant, TNode<Context> context, TNode<Context> native_context,
TNode<Object> collection, TNode<JSArray> fast_jsarray,
Label* if_may_have_side_effects, TVariable<IntPtrT>& var_current_index) {
TNode<FixedArrayBase> elements = LoadElements(fast_jsarray);
TNode<Int32T> elements_kind = LoadElementsKind(fast_jsarray);
TNode<JSFunction> add_func = GetInitialAddFunction(variant, native_context);
CSA_DCHECK(this,
TaggedEqual(GetAddFunction(variant, native_context, collection),
add_func));
CSA_DCHECK(this, IsFastJSArrayWithNoCustomIteration(context, fast_jsarray));
TNode<IntPtrT> length = SmiUntag(LoadFastJSArrayLength(fast_jsarray));
CSA_DCHECK(this, IntPtrGreaterThanOrEqual(length, IntPtrConstant(0)));
CSA_DCHECK(
this, HasInitialCollectionPrototype(variant, native_context, collection));
#if DEBUG
TNode<Map> original_collection_map = LoadMap(CAST(collection));
TNode<Map> original_fast_js_array_map = LoadMap(fast_jsarray);
#endif
Label exit(this), if_doubles(this), if_smiorobjects(this);
GotoIf(IntPtrEqual(length, IntPtrConstant(0)), &exit);
Branch(IsFastSmiOrTaggedElementsKind(elements_kind), &if_smiorobjects,
&if_doubles);
BIND(&if_smiorobjects);
{
auto set_entry = [&](TNode<IntPtrT> index) {
TNode<Object> element =
LoadAndNormalizeFixedArrayElement(CAST(elements), index);
AddConstructorEntry(variant, context, collection, add_func, element,
if_may_have_side_effects);
};
// Instead of using the slower iteration protocol to iterate over the
// elements, a fast loop is used. This assumes that adding an element
// to the collection does not call user code that could mutate the elements
// or collection.
BuildFastLoop<IntPtrT>(var_current_index, IntPtrConstant(0), length,
set_entry, 1, LoopUnrollingMode::kNo,
IndexAdvanceMode::kPost);
Goto(&exit);
}
BIND(&if_doubles);
{
// A Map constructor requires entries to be arrays (ex. [key, value]),
// so a FixedDoubleArray can never succeed.
if (variant == kMap || variant == kWeakMap) {
CSA_DCHECK(this, IntPtrGreaterThan(length, IntPtrConstant(0)));
TNode<Object> element =
LoadAndNormalizeFixedDoubleArrayElement(elements, IntPtrConstant(0));
ThrowTypeError(context, MessageTemplate::kIteratorValueNotAnObject,
element);
} else {
DCHECK(variant == kSet || variant == kWeakSet);
auto set_entry = [&](TNode<IntPtrT> index) {
TNode<Object> entry = LoadAndNormalizeFixedDoubleArrayElement(
elements, UncheckedCast<IntPtrT>(index));
AddConstructorEntry(variant, context, collection, add_func, entry);
};
BuildFastLoop<IntPtrT>(var_current_index, IntPtrConstant(0), length,
set_entry, 1, LoopUnrollingMode::kNo,
IndexAdvanceMode::kPost);
Goto(&exit);
}
}
BIND(&exit);
#if DEBUG
CSA_DCHECK(this,
TaggedEqual(original_collection_map, LoadMap(CAST(collection))));
CSA_DCHECK(this,
TaggedEqual(original_fast_js_array_map, LoadMap(fast_jsarray)));
#endif
}
void BaseCollectionsAssembler::AddConstructorEntriesFromIterable(
Variant variant, TNode<Context> context, TNode<Context> native_context,
TNode<Object> collection, TNode<Object> iterable, Label* if_exception,
TVariable<JSReceiver>* var_iterator_object,
TVariable<Object>* var_exception) {
Label exit(this), loop(this);
CSA_DCHECK(this, Word32BinaryNot(IsNullOrUndefined(iterable)));
TNode<Object> add_func = GetAddFunction(variant, context, collection);
IteratorBuiltinsAssembler iterator_assembler(this->state());
TorqueStructIteratorRecord iterator =
iterator_assembler.GetIterator(context, iterable);
*var_iterator_object = iterator.object;
CSA_DCHECK(this, Word32BinaryNot(IsUndefined(iterator.object)));
TNode<Map> fast_iterator_result_map = CAST(
LoadContextElement(native_context, Context::ITERATOR_RESULT_MAP_INDEX));
Goto(&loop);
BIND(&loop);
{
TNode<JSReceiver> next = iterator_assembler.IteratorStep(
context, iterator, &exit, fast_iterator_result_map);
TNode<Object> next_value = iterator_assembler.IteratorValue(
context, next, fast_iterator_result_map);
AddConstructorEntry(variant, context, collection, add_func, next_value,
nullptr, if_exception, var_exception);
Goto(&loop);
}
BIND(&exit);
}
RootIndex BaseCollectionsAssembler::GetAddFunctionNameIndex(Variant variant) {
switch (variant) {
case kMap:
case kWeakMap:
return RootIndex::kset_string;
case kSet:
case kWeakSet:
return RootIndex::kadd_string;
}
UNREACHABLE();
}
void BaseCollectionsAssembler::GotoIfInitialAddFunctionModified(
Variant variant, TNode<NativeContext> native_context,
TNode<HeapObject> collection, Label* if_modified) {
static_assert(JSCollection::kAddFunctionDescriptorIndex ==
JSWeakCollection::kAddFunctionDescriptorIndex);
// TODO(jgruber): Investigate if this should also fall back to full prototype
// verification.
static constexpr PrototypeCheckAssembler::Flags flags{
PrototypeCheckAssembler::kCheckPrototypePropertyConstness};
static constexpr int kNoContextIndex = -1;
static_assert(
(flags & PrototypeCheckAssembler::kCheckPrototypePropertyIdentity) == 0);
using DescriptorIndexNameValue =
PrototypeCheckAssembler::DescriptorIndexNameValue;
DescriptorIndexNameValue property_to_check{
JSCollection::kAddFunctionDescriptorIndex,
GetAddFunctionNameIndex(variant), kNoContextIndex};
PrototypeCheckAssembler prototype_check_assembler(
state(), flags, native_context,
GetInitialCollectionPrototype(variant, native_context),
base::Vector<DescriptorIndexNameValue>(&property_to_check, 1));
TNode<HeapObject> prototype = LoadMapPrototype(LoadMap(collection));
Label if_unmodified(this);
prototype_check_assembler.CheckAndBranch(prototype, &if_unmodified,
if_modified);
BIND(&if_unmodified);
}
TNode<JSObject> BaseCollectionsAssembler::AllocateJSCollection(
TNode<Context> context, TNode<JSFunction> constructor,
TNode<JSReceiver> new_target) {
TNode<BoolT> is_target_unmodified = TaggedEqual(constructor, new_target);
return Select<JSObject>(
is_target_unmodified,
[=] { return AllocateJSCollectionFast(constructor); },
[=] {
return AllocateJSCollectionSlow(context, constructor, new_target);
});
}
TNode<JSObject> BaseCollectionsAssembler::AllocateJSCollectionFast(
TNode<JSFunction> constructor) {
CSA_DCHECK(this, IsConstructorMap(LoadMap(constructor)));
TNode<Map> initial_map =
CAST(LoadJSFunctionPrototypeOrInitialMap(constructor));
return AllocateJSObjectFromMap(initial_map);
}
TNode<JSObject> BaseCollectionsAssembler::AllocateJSCollectionSlow(
TNode<Context> context, TNode<JSFunction> constructor,
TNode<JSReceiver> new_target) {
ConstructorBuiltinsAssembler constructor_assembler(this->state());
return constructor_assembler.FastNewObject(context, constructor, new_target);
}
void BaseCollectionsAssembler::GenerateConstructor(
Variant variant, Handle<String> constructor_function_name,
TNode<Object> new_target, TNode<IntPtrT> argc, TNode<Context> context) {
const int kIterableArg = 0;
CodeStubArguments args(this, argc);
TNode<Object> iterable = args.GetOptionalArgumentValue(kIterableArg);
Label if_undefined(this, Label::kDeferred);
GotoIf(IsUndefined(new_target), &if_undefined);
TNode<NativeContext> native_context = LoadNativeContext(context);
TNode<JSObject> collection = AllocateJSCollection(
context, GetConstructor(variant, native_context), CAST(new_target));
AddConstructorEntries(variant, context, native_context, collection, iterable);
Return(collection);
BIND(&if_undefined);
ThrowTypeError(context, MessageTemplate::kConstructorNotFunction,
HeapConstant(constructor_function_name));
}
TNode<Object> BaseCollectionsAssembler::GetAddFunction(
Variant variant, TNode<Context> context, TNode<Object> collection) {
Handle<String> add_func_name = (variant == kMap || variant == kWeakMap)
? isolate()->factory()->set_string()
: isolate()->factory()->add_string();
TNode<Object> add_func = GetProperty(context, collection, add_func_name);
Label exit(this), if_notcallable(this, Label::kDeferred);
GotoIf(TaggedIsSmi(add_func), &if_notcallable);
GotoIfNot(IsCallable(CAST(add_func)), &if_notcallable);
Goto(&exit);
BIND(&if_notcallable);
ThrowTypeError(context, MessageTemplate::kPropertyNotFunction, add_func,
HeapConstant(add_func_name), collection);
BIND(&exit);
return add_func;
}
TNode<JSFunction> BaseCollectionsAssembler::GetConstructor(
Variant variant, TNode<Context> native_context) {
int index;
switch (variant) {
case kMap:
index = Context::JS_MAP_FUN_INDEX;
break;
case kSet:
index = Context::JS_SET_FUN_INDEX;
break;
case kWeakMap:
index = Context::JS_WEAK_MAP_FUN_INDEX;
break;
case kWeakSet:
index = Context::JS_WEAK_SET_FUN_INDEX;
break;
}
return CAST(LoadContextElement(native_context, index));
}
TNode<JSFunction> BaseCollectionsAssembler::GetInitialAddFunction(
Variant variant, TNode<Context> native_context) {
int index;
switch (variant) {
case kMap:
index = Context::MAP_SET_INDEX;
break;
case kSet:
index = Context::SET_ADD_INDEX;
break;
case kWeakMap:
index = Context::WEAKMAP_SET_INDEX;
break;
case kWeakSet:
index = Context::WEAKSET_ADD_INDEX;
break;
}
return CAST(LoadContextElement(native_context, index));
}
int BaseCollectionsAssembler::GetTableOffset(Variant variant) {
switch (variant) {
case kMap:
return JSMap::kTableOffset;
case kSet:
return JSSet::kTableOffset;
case kWeakMap:
return JSWeakMap::kTableOffset;
case kWeakSet:
return JSWeakSet::kTableOffset;
}
UNREACHABLE();
}
TNode<IntPtrT> BaseCollectionsAssembler::EstimatedInitialSize(
TNode<Object> initial_entries, TNode<BoolT> is_fast_jsarray) {
return Select<IntPtrT>(
is_fast_jsarray,
[=] { return SmiUntag(LoadFastJSArrayLength(CAST(initial_entries))); },
[=] { return IntPtrConstant(0); });
}
// https://tc39.es/proposal-symbols-as-weakmap-keys/#sec-canbeheldweakly-abstract-operation
void BaseCollectionsAssembler::GotoIfCannotBeHeldWeakly(
const TNode<Object> obj, Label* if_cannot_be_held_weakly) {
Label check_symbol_key(this);
Label end(this);
GotoIf(TaggedIsSmi(obj), if_cannot_be_held_weakly);
TNode<Uint16T> instance_type = LoadMapInstanceType(LoadMap(CAST(obj)));
GotoIfNot(IsJSReceiverInstanceType(instance_type), &check_symbol_key);
// TODO(v8:12547) Shared structs and arrays should only be able to point
// to shared values in weak collections. For now, disallow them as weak
// collection keys.
GotoIf(IsAlwaysSharedSpaceJSObjectInstanceType(instance_type),
if_cannot_be_held_weakly);
Goto(&end);
Bind(&check_symbol_key);
GotoIfNot(HasHarmonySymbolAsWeakmapKeyFlag(), if_cannot_be_held_weakly);
GotoIfNot(IsSymbolInstanceType(instance_type), if_cannot_be_held_weakly);
TNode<Uint32T> flags = LoadSymbolFlags(CAST(obj));
GotoIf(Word32And(flags, Symbol::IsInPublicSymbolTableBit::kMask),
if_cannot_be_held_weakly);
Goto(&end);
Bind(&end);
}
TNode<Map> BaseCollectionsAssembler::GetInitialCollectionPrototype(
Variant variant, TNode<Context> native_context) {
int initial_prototype_index;
switch (variant) {
case kMap:
initial_prototype_index = Context::INITIAL_MAP_PROTOTYPE_MAP_INDEX;
break;
case kSet:
initial_prototype_index = Context::INITIAL_SET_PROTOTYPE_MAP_INDEX;
break;
case kWeakMap:
initial_prototype_index = Context::INITIAL_WEAKMAP_PROTOTYPE_MAP_INDEX;
break;
case kWeakSet:
initial_prototype_index = Context::INITIAL_WEAKSET_PROTOTYPE_MAP_INDEX;
break;
}
return CAST(LoadContextElement(native_context, initial_prototype_index));
}
TNode<BoolT> BaseCollectionsAssembler::HasInitialCollectionPrototype(
Variant variant, TNode<Context> native_context, TNode<Object> collection) {
TNode<Map> collection_proto_map =
LoadMap(LoadMapPrototype(LoadMap(CAST(collection))));
return TaggedEqual(collection_proto_map,
GetInitialCollectionPrototype(variant, native_context));
}
TNode<Object> BaseCollectionsAssembler::LoadAndNormalizeFixedArrayElement(
TNode<FixedArray> elements, TNode<IntPtrT> index) {
TNode<Object> element = UnsafeLoadFixedArrayElement(elements, index);
return Select<Object>(IsTheHole(element), [=] { return UndefinedConstant(); },
[=] { return element; });
}
TNode<Object> BaseCollectionsAssembler::LoadAndNormalizeFixedDoubleArrayElement(
TNode<HeapObject> elements, TNode<IntPtrT> index) {
TVARIABLE(Object, entry);
Label if_hole(this, Label::kDeferred), next(this);
TNode<Float64T> element =
LoadFixedDoubleArrayElement(CAST(elements), index, &if_hole);
{ // not hole
entry = AllocateHeapNumberWithValue(element);
Goto(&next);
}
BIND(&if_hole);
{
entry = UndefinedConstant();
Goto(&next);
}
BIND(&next);
return entry.value();
}
class CollectionsBuiltinsAssembler : public BaseCollectionsAssembler {
public:
explicit CollectionsBuiltinsAssembler(compiler::CodeAssemblerState* state)
: BaseCollectionsAssembler(state) {}
// Check whether |iterable| is a JS_MAP_KEY_ITERATOR_TYPE or
// JS_MAP_VALUE_ITERATOR_TYPE object that is not partially consumed and still
// has original iteration behavior.
void BranchIfIterableWithOriginalKeyOrValueMapIterator(TNode<Object> iterable,
TNode<Context> context,
Label* if_true,
Label* if_false);
// Check whether |iterable| is a JS_SET_TYPE or JS_SET_VALUE_ITERATOR_TYPE
// object that still has original iteration behavior. In case of the iterator,
// the iterator also must not have been partially consumed.
void BranchIfIterableWithOriginalValueSetIterator(TNode<Object> iterable,
TNode<Context> context,
Label* if_true,
Label* if_false);
protected:
template <typename IteratorType>
TNode<HeapObject> AllocateJSCollectionIterator(
const TNode<Context> context, int map_index,
const TNode<HeapObject> collection);
TNode<HeapObject> AllocateTable(Variant variant,
TNode<IntPtrT> at_least_space_for) override;
TNode<IntPtrT> GetHash(const TNode<HeapObject> key);
TNode<IntPtrT> CallGetHashRaw(const TNode<HeapObject> key);
TNode<Smi> CallGetOrCreateHashRaw(const TNode<HeapObject> key);
// Transitions the iterator to the non obsolete backing store.
// This is a NOP if the [table] is not obsolete.
template <typename TableType>
using UpdateInTransition = std::function<void(const TNode<TableType> table,
const TNode<IntPtrT> index)>;
template <typename TableType>
std::pair<TNode<TableType>, TNode<IntPtrT>> Transition(
const TNode<TableType> table, const TNode<IntPtrT> index,
UpdateInTransition<TableType> const& update_in_transition);
template <typename IteratorType, typename TableType>
std::pair<TNode<TableType>, TNode<IntPtrT>> TransitionAndUpdate(
const TNode<IteratorType> iterator);
template <typename TableType>
std::tuple<TNode<Object>, TNode<IntPtrT>, TNode<IntPtrT>> NextSkipHoles(
TNode<TableType> table, TNode<IntPtrT> index, Label* if_end);
// Specialization for Smi.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
template <typename CollectionType>
void FindOrderedHashTableEntryForSmiKey(TNode<CollectionType> table,
TNode<Smi> key_tagged,
TVariable<IntPtrT>* result,
Label* entry_found, Label* not_found);
void SameValueZeroSmi(TNode<Smi> key_smi, TNode<Object> candidate_key,
Label* if_same, Label* if_not_same);
// Specialization for heap numbers.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
void SameValueZeroHeapNumber(TNode<Float64T> key_float,
TNode<Object> candidate_key, Label* if_same,
Label* if_not_same);
template <typename CollectionType>
void FindOrderedHashTableEntryForHeapNumberKey(
TNode<CollectionType> table, TNode<HeapNumber> key_heap_number,
TVariable<IntPtrT>* result, Label* entry_found, Label* not_found);
// Specialization for bigints.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
void SameValueZeroBigInt(TNode<BigInt> key, TNode<Object> candidate_key,
Label* if_same, Label* if_not_same);
template <typename CollectionType>
void FindOrderedHashTableEntryForBigIntKey(TNode<CollectionType> table,
TNode<BigInt> key_big_int,
TVariable<IntPtrT>* result,
Label* entry_found,
Label* not_found);
// Specialization for string.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
template <typename CollectionType>
void FindOrderedHashTableEntryForStringKey(TNode<CollectionType> table,
TNode<String> key_tagged,
TVariable<IntPtrT>* result,
Label* entry_found,
Label* not_found);
TNode<IntPtrT> ComputeStringHash(TNode<String> string_key);
void SameValueZeroString(TNode<String> key_string,
TNode<Object> candidate_key, Label* if_same,
Label* if_not_same);
// Specialization for non-strings, non-numbers. For those we only need
// reference equality to compare the keys.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise. If the hash-code has not been computed, it
// should be Smi -1.
template <typename CollectionType>
void FindOrderedHashTableEntryForOtherKey(TNode<CollectionType> table,
TNode<HeapObject> key_heap_object,
TVariable<IntPtrT>* result,
Label* entry_found,
Label* not_found);
template <typename CollectionType>
void TryLookupOrderedHashTableIndex(const TNode<CollectionType> table,
const TNode<Object> key,
TVariable<IntPtrT>* result,
Label* if_entry_found,
Label* if_not_found);
const TNode<Object> NormalizeNumberKey(const TNode<Object> key);
void StoreOrderedHashMapNewEntry(const TNode<OrderedHashMap> table,
const TNode<Object> key,
const TNode<Object> value,
const TNode<IntPtrT> hash,
const TNode<IntPtrT> number_of_buckets,
const TNode<IntPtrT> occupancy);
void StoreOrderedHashSetNewEntry(const TNode<OrderedHashSet> table,
const TNode<Object> key,
const TNode<IntPtrT> hash,
const TNode<IntPtrT> number_of_buckets,
const TNode<IntPtrT> occupancy);
// Create a JSArray with PACKED_ELEMENTS kind from a Map.prototype.keys() or
// Map.prototype.values() iterator. The iterator is assumed to satisfy
// IterableWithOriginalKeyOrValueMapIterator. This function will skip the
// iterator and iterate directly on the underlying hash table. In the end it
// will update the state of the iterator to 'exhausted'.
TNode<JSArray> MapIteratorToList(TNode<Context> context,
TNode<JSMapIterator> iterator);
// Create a JSArray with PACKED_ELEMENTS kind from a Set.prototype.keys() or
// Set.prototype.values() iterator, or a Set. The |iterable| is assumed to
// satisfy IterableWithOriginalValueSetIterator. This function will skip the
// iterator and iterate directly on the underlying hash table. In the end, if
// |iterable| is an iterator, it will update the state of the iterator to
// 'exhausted'.
TNode<JSArray> SetOrSetIteratorToList(TNode<Context> context,
TNode<HeapObject> iterable);
void BranchIfMapIteratorProtectorValid(Label* if_true, Label* if_false);
void BranchIfSetIteratorProtectorValid(Label* if_true, Label* if_false);
// Builds code that finds OrderedHashTable entry for a key with hash code
// {hash} with using the comparison code generated by {key_compare}. The code
// jumps to {entry_found} if the key is found, or to {not_found} if the key
// was not found. In the {entry_found} branch, the variable
// entry_start_position will be bound to the index of the entry (relative to
// OrderedHashTable::kHashTableStartIndex).
//
// The {CollectionType} template parameter stands for the particular instance
// of OrderedHashTable, it should be OrderedHashMap or OrderedHashSet.
template <typename CollectionType>
void FindOrderedHashTableEntry(
const TNode<CollectionType> table, const TNode<IntPtrT> hash,
const std::function<void(TNode<Object>, Label*, Label*)>& key_compare,
TVariable<IntPtrT>* entry_start_position, Label* entry_found,
Label* not_found);
TNode<Word32T> ComputeUnseededHash(TNode<IntPtrT> key);
};
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntry(
const TNode<CollectionType> table, const TNode<IntPtrT> hash,
const std::function<void(TNode<Object>, Label*, Label*)>& key_compare,
TVariable<IntPtrT>* entry_start_position, Label* entry_found,
Label* not_found) {
// Get the index of the bucket.
const TNode<IntPtrT> number_of_buckets =
SmiUntag(CAST(UnsafeLoadFixedArrayElement(
table, CollectionType::NumberOfBucketsIndex())));
const TNode<IntPtrT> bucket =
WordAnd(hash, IntPtrSub(number_of_buckets, IntPtrConstant(1)));
const TNode<IntPtrT> first_entry = SmiUntag(CAST(UnsafeLoadFixedArrayElement(
table, bucket, CollectionType::HashTableStartIndex() * kTaggedSize)));
// Walk the bucket chain.
TNode<IntPtrT> entry_start;
Label if_key_found(this);
{
TVARIABLE(IntPtrT, var_entry, first_entry);
Label loop(this, {&var_entry, entry_start_position}),
continue_next_entry(this);
Goto(&loop);
BIND(&loop);
// If the entry index is the not-found sentinel, we are done.
GotoIf(IntPtrEqual(var_entry.value(),
IntPtrConstant(CollectionType::kNotFound)),
not_found);
// Make sure the entry index is within range.
CSA_DCHECK(
this,
UintPtrLessThan(
var_entry.value(),
SmiUntag(SmiAdd(
CAST(UnsafeLoadFixedArrayElement(
table, CollectionType::NumberOfElementsIndex())),
CAST(UnsafeLoadFixedArrayElement(
table, CollectionType::NumberOfDeletedElementsIndex()))))));
// Compute the index of the entry relative to kHashTableStartIndex.
entry_start =
IntPtrAdd(IntPtrMul(var_entry.value(),
IntPtrConstant(CollectionType::kEntrySize)),
number_of_buckets);
// Load the key from the entry.
const TNode<Object> candidate_key = UnsafeLoadFixedArrayElement(
table, entry_start,
CollectionType::HashTableStartIndex() * kTaggedSize);
key_compare(candidate_key, &if_key_found, &continue_next_entry);
BIND(&continue_next_entry);
// Load the index of the next entry in the bucket chain.
var_entry = SmiUntag(CAST(UnsafeLoadFixedArrayElement(
table, entry_start,
(CollectionType::HashTableStartIndex() + CollectionType::kChainOffset) *
kTaggedSize)));
Goto(&loop);
}
BIND(&if_key_found);
*entry_start_position = entry_start;
Goto(entry_found);
}
template <typename IteratorType>
TNode<HeapObject> CollectionsBuiltinsAssembler::AllocateJSCollectionIterator(
const TNode<Context> context, int map_index,
const TNode<HeapObject> collection) {
const TNode<Object> table =
LoadObjectField(collection, JSCollection::kTableOffset);
const TNode<NativeContext> native_context = LoadNativeContext(context);
const TNode<Map> iterator_map =
CAST(LoadContextElement(native_context, map_index));
const TNode<HeapObject> iterator =
AllocateInNewSpace(IteratorType::kHeaderSize);
StoreMapNoWriteBarrier(iterator, iterator_map);
StoreObjectFieldRoot(iterator, IteratorType::kPropertiesOrHashOffset,
RootIndex::kEmptyFixedArray);
StoreObjectFieldRoot(iterator, IteratorType::kElementsOffset,
RootIndex::kEmptyFixedArray);
StoreObjectFieldNoWriteBarrier(iterator, IteratorType::kTableOffset, table);
StoreObjectFieldNoWriteBarrier(iterator, IteratorType::kIndexOffset,
SmiConstant(0));
return iterator;
}
TNode<HeapObject> CollectionsBuiltinsAssembler::AllocateTable(
Variant variant, TNode<IntPtrT> at_least_space_for) {
if (variant == kMap || variant == kWeakMap) {
return AllocateOrderedHashMap();
} else {
return AllocateOrderedHashSet();
}
}
TF_BUILTIN(MapConstructor, CollectionsBuiltinsAssembler) {
auto new_target = Parameter<Object>(Descriptor::kJSNewTarget);
TNode<IntPtrT> argc = ChangeInt32ToIntPtr(
UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount));
auto context = Parameter<Context>(Descriptor::kContext);
GenerateConstructor(kMap, isolate()->factory()->Map_string(), new_target,
argc, context);
}
TF_BUILTIN(SetConstructor, CollectionsBuiltinsAssembler) {
auto new_target = Parameter<Object>(Descriptor::kJSNewTarget);
TNode<IntPtrT> argc = ChangeInt32ToIntPtr(
UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount));
auto context = Parameter<Context>(Descriptor::kContext);
GenerateConstructor(kSet, isolate()->factory()->Set_string(), new_target,
argc, context);
}
TNode<Smi> CollectionsBuiltinsAssembler::CallGetOrCreateHashRaw(
const TNode<HeapObject> key) {
const TNode<ExternalReference> function_addr =
ExternalConstant(ExternalReference::get_or_create_hash_raw());
const TNode<ExternalReference> isolate_ptr =
ExternalConstant(ExternalReference::isolate_address(isolate()));
MachineType type_ptr = MachineType::Pointer();
MachineType type_tagged = MachineType::AnyTagged();
TNode<Smi> result = CAST(CallCFunction(function_addr, type_tagged,
std::make_pair(type_ptr, isolate_ptr),
std::make_pair(type_tagged, key)));
return result;
}
TNode<IntPtrT> CollectionsBuiltinsAssembler::CallGetHashRaw(
const TNode<HeapObject> key) {
const TNode<ExternalReference> function_addr =
ExternalConstant(ExternalReference::orderedhashmap_gethash_raw());
const TNode<ExternalReference> isolate_ptr =
ExternalConstant(ExternalReference::isolate_address(isolate()));
MachineType type_ptr = MachineType::Pointer();
MachineType type_tagged = MachineType::AnyTagged();
TNode<Smi> result = CAST(CallCFunction(function_addr, type_tagged,
std::make_pair(type_ptr, isolate_ptr),
std::make_pair(type_tagged, key)));
return SmiUntag(result);
}
TNode<IntPtrT> CollectionsBuiltinsAssembler::GetHash(
const TNode<HeapObject> key) {
TVARIABLE(IntPtrT, var_hash);
Label if_receiver(this), if_other(this), done(this);
Branch(IsJSReceiver(key), &if_receiver, &if_other);
BIND(&if_receiver);
{
var_hash = LoadJSReceiverIdentityHash(CAST(key));
Goto(&done);
}
BIND(&if_other);
{
var_hash = CallGetHashRaw(key);
Goto(&done);
}
BIND(&done);
return var_hash.value();
}
void CollectionsBuiltinsAssembler::SameValueZeroSmi(TNode<Smi> key_smi,
TNode<Object> candidate_key,
Label* if_same,
Label* if_not_same) {
// If the key is the same, we are done.
GotoIf(TaggedEqual(candidate_key, key_smi), if_same);
// If the candidate key is smi, then it must be different (because
// we already checked for equality above).
GotoIf(TaggedIsSmi(candidate_key), if_not_same);
// If the candidate key is not smi, we still have to check if it is a
// heap number with the same value.
GotoIfNot(IsHeapNumber(CAST(candidate_key)), if_not_same);
const TNode<Float64T> candidate_key_number =
LoadHeapNumberValue(CAST(candidate_key));
const TNode<Float64T> key_number = SmiToFloat64(key_smi);
GotoIf(Float64Equal(candidate_key_number, key_number), if_same);
Goto(if_not_same);
}
void CollectionsBuiltinsAssembler::BranchIfMapIteratorProtectorValid(
Label* if_true, Label* if_false) {
TNode<PropertyCell> protector_cell = MapIteratorProtectorConstant();
DCHECK(isolate()->heap()->map_iterator_protector().IsPropertyCell());
Branch(
TaggedEqual(LoadObjectField(protector_cell, PropertyCell::kValueOffset),
SmiConstant(Protectors::kProtectorValid)),
if_true, if_false);
}
void CollectionsBuiltinsAssembler::
BranchIfIterableWithOriginalKeyOrValueMapIterator(TNode<Object> iterator,
TNode<Context> context,
Label* if_true,
Label* if_false) {
Label if_key_or_value_iterator(this), extra_checks(this);
// Check if iterator is a keys or values JSMapIterator.
GotoIf(TaggedIsSmi(iterator), if_false);
TNode<Map> iter_map = LoadMap(CAST(iterator));
const TNode<Uint16T> instance_type = LoadMapInstanceType(iter_map);
GotoIf(InstanceTypeEqual(instance_type, JS_MAP_KEY_ITERATOR_TYPE),
&if_key_or_value_iterator);
Branch(InstanceTypeEqual(instance_type, JS_MAP_VALUE_ITERATOR_TYPE),
&if_key_or_value_iterator, if_false);
BIND(&if_key_or_value_iterator);
// Check that the iterator is not partially consumed.
const TNode<Object> index =
LoadObjectField(CAST(iterator), JSMapIterator::kIndexOffset);
GotoIfNot(TaggedEqual(index, SmiConstant(0)), if_false);
BranchIfMapIteratorProtectorValid(&extra_checks, if_false);
BIND(&extra_checks);
// Check if the iterator object has the original %MapIteratorPrototype%.
const TNode<NativeContext> native_context = LoadNativeContext(context);
const TNode<Object> initial_map_iter_proto = LoadContextElement(
native_context, Context::INITIAL_MAP_ITERATOR_PROTOTYPE_INDEX);
const TNode<HeapObject> map_iter_proto = LoadMapPrototype(iter_map);
GotoIfNot(TaggedEqual(map_iter_proto, initial_map_iter_proto), if_false);
// Check if the original MapIterator prototype has the original
// %IteratorPrototype%.
const TNode<Object> initial_iter_proto = LoadContextElement(
native_context, Context::INITIAL_ITERATOR_PROTOTYPE_INDEX);
const TNode<HeapObject> iter_proto =
LoadMapPrototype(LoadMap(map_iter_proto));
Branch(TaggedEqual(iter_proto, initial_iter_proto), if_true, if_false);
}
void BranchIfIterableWithOriginalKeyOrValueMapIterator(
compiler::CodeAssemblerState* state, TNode<Object> iterable,
TNode<Context> context, compiler::CodeAssemblerLabel* if_true,
compiler::CodeAssemblerLabel* if_false) {
CollectionsBuiltinsAssembler assembler(state);
assembler.BranchIfIterableWithOriginalKeyOrValueMapIterator(
iterable, context, if_true, if_false);
}
void CollectionsBuiltinsAssembler::BranchIfSetIteratorProtectorValid(
Label* if_true, Label* if_false) {
const TNode<PropertyCell> protector_cell = SetIteratorProtectorConstant();
DCHECK(isolate()->heap()->set_iterator_protector().IsPropertyCell());
Branch(
TaggedEqual(LoadObjectField(protector_cell, PropertyCell::kValueOffset),
SmiConstant(Protectors::kProtectorValid)),
if_true, if_false);
}
void CollectionsBuiltinsAssembler::BranchIfIterableWithOriginalValueSetIterator(
TNode<Object> iterable, TNode<Context> context, Label* if_true,
Label* if_false) {
Label if_set(this), if_value_iterator(this), check_protector(this);
TVARIABLE(BoolT, var_result);
GotoIf(TaggedIsSmi(iterable), if_false);
TNode<Map> iterable_map = LoadMap(CAST(iterable));
const TNode<Uint16T> instance_type = LoadMapInstanceType(iterable_map);
GotoIf(InstanceTypeEqual(instance_type, JS_SET_TYPE), &if_set);
Branch(InstanceTypeEqual(instance_type, JS_SET_VALUE_ITERATOR_TYPE),
&if_value_iterator, if_false);
BIND(&if_set);
// Check if the set object has the original Set prototype.
const TNode<Object> initial_set_proto = LoadContextElement(
LoadNativeContext(context), Context::INITIAL_SET_PROTOTYPE_INDEX);
const TNode<HeapObject> set_proto = LoadMapPrototype(iterable_map);
GotoIfNot(TaggedEqual(set_proto, initial_set_proto), if_false);
Goto(&check_protector);
BIND(&if_value_iterator);
// Check that the iterator is not partially consumed.
const TNode<Object> index =
LoadObjectField(CAST(iterable), JSSetIterator::kIndexOffset);
GotoIfNot(TaggedEqual(index, SmiConstant(0)), if_false);
// Check if the iterator object has the original SetIterator prototype.
const TNode<NativeContext> native_context = LoadNativeContext(context);
const TNode<Object> initial_set_iter_proto = LoadContextElement(
native_context, Context::INITIAL_SET_ITERATOR_PROTOTYPE_INDEX);
const TNode<HeapObject> set_iter_proto = LoadMapPrototype(iterable_map);
GotoIfNot(TaggedEqual(set_iter_proto, initial_set_iter_proto), if_false);
// Check if the original SetIterator prototype has the original
// %IteratorPrototype%.
const TNode<Object> initial_iter_proto = LoadContextElement(
native_context, Context::INITIAL_ITERATOR_PROTOTYPE_INDEX);
const TNode<HeapObject> iter_proto =
LoadMapPrototype(LoadMap(set_iter_proto));
GotoIfNot(TaggedEqual(iter_proto, initial_iter_proto), if_false);
Goto(&check_protector);
BIND(&check_protector);
BranchIfSetIteratorProtectorValid(if_true, if_false);
}
void BranchIfIterableWithOriginalValueSetIterator(
compiler::CodeAssemblerState* state, TNode<Object> iterable,
TNode<Context> context, compiler::CodeAssemblerLabel* if_true,
compiler::CodeAssemblerLabel* if_false) {
CollectionsBuiltinsAssembler assembler(state);