forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjs-call-reducer.cc
More file actions
8815 lines (7661 loc) · 350 KB
/
js-call-reducer.cc
File metadata and controls
8815 lines (7661 loc) · 350 KB
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 2015 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/compiler/js-call-reducer.h"
#include <functional>
#include "src/base/container-utils.h"
#include "src/base/small-vector.h"
#include "src/builtins/builtins-promise.h"
#include "src/builtins/builtins-utils.h"
#include "src/codegen/code-factory.h"
#include "src/codegen/tnode.h"
#include "src/compiler/access-builder.h"
#include "src/compiler/access-info.h"
#include "src/compiler/allocation-builder-inl.h"
#include "src/compiler/allocation-builder.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/compilation-dependencies.h"
#include "src/compiler/fast-api-calls.h"
#include "src/compiler/feedback-source.h"
#include "src/compiler/graph-assembler.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/linkage.h"
#include "src/compiler/map-inference.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/opcodes.h"
#include "src/compiler/simplified-operator.h"
#include "src/compiler/state-values-utils.h"
#include "src/compiler/type-cache.h"
#include "src/compiler/use-info.h"
#include "src/flags/flags.h"
#include "src/ic/call-optimization.h"
#include "src/objects/elements-kind.h"
#include "src/objects/instance-type.h"
#include "src/objects/js-function.h"
#include "src/objects/objects-inl.h"
#include "src/objects/ordered-hash-table.h"
#include "src/utils/utils.h"
#ifdef V8_INTL_SUPPORT
#include "src/objects/intl-objects.h"
#endif
namespace v8 {
namespace internal {
namespace compiler {
// Shorter lambda declarations with less visual clutter.
#define _ [&]()
class JSCallReducerAssembler : public JSGraphAssembler {
static constexpr bool kMarkLoopExits = true;
public:
JSCallReducerAssembler(JSCallReducer* reducer, Node* node,
Node* effect = nullptr, Node* control = nullptr)
: JSGraphAssembler(
reducer->broker(), reducer->JSGraphForGraphAssembler(),
reducer->ZoneForGraphAssembler(), BranchSemantics::kJS,
[reducer](Node* n) { reducer->RevisitForGraphAssembler(n); },
kMarkLoopExits),
dependencies_(reducer->dependencies()),
node_(node) {
InitializeEffectControl(
effect ? effect : NodeProperties::GetEffectInput(node),
control ? control : NodeProperties::GetControlInput(node));
// Finish initializing the outermost catch scope.
bool has_handler =
NodeProperties::IsExceptionalCall(node, &outermost_handler_);
outermost_catch_scope_.set_has_handler(has_handler);
}
TNode<Object> ReduceJSCallWithArrayLikeOrSpreadOfEmpty(
std::unordered_set<Node*>* generated_calls_with_array_like_or_spread);
TNode<Object> ReduceMathUnary(const Operator* op);
TNode<Object> ReduceMathBinary(const Operator* op);
TNode<String> ReduceStringPrototypeSubstring();
TNode<Boolean> ReduceStringPrototypeStartsWith();
TNode<Boolean> ReduceStringPrototypeStartsWith(
StringRef search_element_string);
TNode<Boolean> ReduceStringPrototypeEndsWith();
TNode<Boolean> ReduceStringPrototypeEndsWith(StringRef search_element_string);
TNode<String> ReduceStringPrototypeCharAt();
TNode<String> ReduceStringPrototypeCharAt(StringRef s, uint32_t index);
TNode<String> ReduceStringPrototypeSlice();
TNode<Object> ReduceJSCallMathMinMaxWithArrayLike(Builtin builtin);
TNode<Object> TargetInput() const { return JSCallNode{node_ptr()}.target(); }
template <typename T>
TNode<T> ReceiverInputAs() const {
return TNode<T>::UncheckedCast(JSCallNode{node_ptr()}.receiver());
}
TNode<Object> ReceiverInput() const { return ReceiverInputAs<Object>(); }
Node* node_ptr() const { return node_; }
// Simplified operators.
TNode<Number> SpeculativeToNumber(
TNode<Object> value,
NumberOperationHint hint = NumberOperationHint::kNumberOrOddball);
TNode<Smi> CheckSmi(TNode<Object> value);
TNode<Number> CheckNumber(TNode<Object> value);
TNode<String> CheckString(TNode<Object> value);
TNode<Number> CheckBounds(TNode<Number> value, TNode<Number> limit,
CheckBoundsFlags flags = {});
// Common operators.
TNode<Smi> TypeGuardUnsignedSmall(TNode<Object> value);
TNode<Object> TypeGuardNonInternal(TNode<Object> value);
TNode<Number> TypeGuardFixedArrayLength(TNode<Object> value);
TNode<Object> Call4(const Callable& callable, TNode<Context> context,
TNode<Object> arg0, TNode<Object> arg1,
TNode<Object> arg2, TNode<Object> arg3);
// Javascript operators.
TNode<Object> JSCall3(TNode<Object> function, TNode<Object> this_arg,
TNode<Object> arg0, TNode<Object> arg1,
TNode<Object> arg2, FrameState frame_state);
TNode<Object> JSCall4(TNode<Object> function, TNode<Object> this_arg,
TNode<Object> arg0, TNode<Object> arg1,
TNode<Object> arg2, TNode<Object> arg3,
FrameState frame_state);
// Emplace a copy of the call node into the graph at current effect/control.
TNode<Object> CopyNode();
// Used in special cases in which we are certain CreateArray does not throw.
TNode<JSArray> CreateArrayNoThrow(TNode<Object> ctor, TNode<Number> size,
FrameState frame_state);
TNode<JSArray> AllocateEmptyJSArray(ElementsKind kind,
NativeContextRef native_context);
TNode<Number> NumberInc(TNode<Number> value) {
return NumberAdd(value, OneConstant());
}
TNode<Number> LoadMapElementsKind(TNode<Map> map);
template <typename T, typename U>
TNode<T> EnterMachineGraph(TNode<U> input, UseInfo use_info) {
return AddNode<T>(
graph()->NewNode(common()->EnterMachineGraph(use_info), input));
}
template <typename T, typename U>
TNode<T> ExitMachineGraph(TNode<U> input,
MachineRepresentation output_representation,
Type output_type) {
return AddNode<T>(graph()->NewNode(
common()->ExitMachineGraph(output_representation, output_type), input));
}
void MaybeInsertMapChecks(MapInference* inference,
bool has_stability_dependency) {
// TODO(jgruber): Implement MapInference::InsertMapChecks in graph
// assembler.
if (!has_stability_dependency) {
Effect e = effect();
inference->InsertMapChecks(jsgraph(), &e, Control{control()}, feedback());
InitializeEffectControl(e, control());
}
}
TNode<Object> ConvertHoleToUndefined(TNode<Object> value, ElementsKind kind) {
DCHECK(IsHoleyElementsKind(kind));
if (kind == HOLEY_DOUBLE_ELEMENTS) {
return AddNode<Number>(
graph()->NewNode(simplified()->ChangeFloat64HoleToTagged(), value));
}
return ConvertTaggedHoleToUndefined(value);
}
class TryCatchBuilder0 {
public:
using TryFunction = VoidGenerator0;
using CatchFunction = std::function<void(TNode<Object>)>;
TryCatchBuilder0(JSCallReducerAssembler* gasm, const TryFunction& try_body)
: gasm_(gasm), try_body_(try_body) {}
void Catch(const CatchFunction& catch_body) {
TNode<Object> handler_exception;
Effect handler_effect{nullptr};
Control handler_control{nullptr};
auto continuation = gasm_->MakeLabel();
// Try.
{
CatchScope catch_scope = CatchScope::Inner(gasm_->temp_zone(), gasm_);
try_body_();
gasm_->Goto(&continuation);
catch_scope.MergeExceptionalPaths(&handler_exception, &handler_effect,
&handler_control);
}
// Catch.
{
gasm_->InitializeEffectControl(handler_effect, handler_control);
catch_body(handler_exception);
gasm_->Goto(&continuation);
}
gasm_->Bind(&continuation);
}
private:
JSCallReducerAssembler* const gasm_;
const VoidGenerator0 try_body_;
};
TryCatchBuilder0 Try(const VoidGenerator0& try_body) {
return {this, try_body};
}
using ConditionFunction1 = std::function<TNode<Boolean>(TNode<Number>)>;
using StepFunction1 = std::function<TNode<Number>(TNode<Number>)>;
class ForBuilder0 {
using For0BodyFunction = std::function<void(TNode<Number>)>;
public:
ForBuilder0(JSGraphAssembler* gasm, TNode<Number> initial_value,
const ConditionFunction1& cond, const StepFunction1& step)
: gasm_(gasm),
initial_value_(initial_value),
cond_(cond),
step_(step) {}
void Do(const For0BodyFunction& body) {
auto loop_exit = gasm_->MakeLabel();
{
GraphAssembler::LoopScope<kPhiRepresentation> loop_scope(gasm_);
auto loop_header = loop_scope.loop_header_label();
auto loop_body = gasm_->MakeLabel();
gasm_->Goto(loop_header, initial_value_);
gasm_->Bind(loop_header);
TNode<Number> i = loop_header->PhiAt<Number>(0);
gasm_->BranchWithHint(cond_(i), &loop_body, &loop_exit,
BranchHint::kTrue);
gasm_->Bind(&loop_body);
body(i);
gasm_->Goto(loop_header, step_(i));
}
gasm_->Bind(&loop_exit);
}
private:
static constexpr MachineRepresentation kPhiRepresentation =
MachineRepresentation::kTagged;
JSGraphAssembler* const gasm_;
const TNode<Number> initial_value_;
const ConditionFunction1 cond_;
const StepFunction1 step_;
};
ForBuilder0 ForZeroUntil(TNode<Number> excluded_limit) {
TNode<Number> initial_value = ZeroConstant();
auto cond = [=](TNode<Number> i) {
return NumberLessThan(i, excluded_limit);
};
auto step = [=](TNode<Number> i) { return NumberAdd(i, OneConstant()); };
return {this, initial_value, cond, step};
}
ForBuilder0 Forever(TNode<Number> initial_value, const StepFunction1& step) {
return {this, initial_value, [=](TNode<Number>) { return TrueConstant(); },
step};
}
using For1BodyFunction = std::function<void(TNode<Number>, TNode<Object>*)>;
class ForBuilder1 {
public:
ForBuilder1(JSGraphAssembler* gasm, TNode<Number> initial_value,
const ConditionFunction1& cond, const StepFunction1& step,
TNode<Object> initial_arg0)
: gasm_(gasm),
initial_value_(initial_value),
cond_(cond),
step_(step),
initial_arg0_(initial_arg0) {}
V8_WARN_UNUSED_RESULT ForBuilder1& Do(const For1BodyFunction& body) {
body_ = body;
return *this;
}
V8_WARN_UNUSED_RESULT TNode<Object> Value() {
DCHECK(body_);
TNode<Object> arg0 = initial_arg0_;
auto loop_exit = gasm_->MakeDeferredLabel(kPhiRepresentation);
{
GraphAssembler::LoopScope<kPhiRepresentation, kPhiRepresentation>
loop_scope(gasm_);
auto loop_header = loop_scope.loop_header_label();
auto loop_body = gasm_->MakeDeferredLabel(kPhiRepresentation);
gasm_->Goto(loop_header, initial_value_, initial_arg0_);
gasm_->Bind(loop_header);
TNode<Number> i = loop_header->PhiAt<Number>(0);
arg0 = loop_header->PhiAt<Object>(1);
gasm_->BranchWithHint(cond_(i), &loop_body, &loop_exit,
BranchHint::kTrue, arg0);
gasm_->Bind(&loop_body);
body_(i, &arg0);
gasm_->Goto(loop_header, step_(i), arg0);
}
gasm_->Bind(&loop_exit);
return TNode<Object>::UncheckedCast(loop_exit.PhiAt<Object>(0));
}
void ValueIsUnused() { USE(Value()); }
private:
static constexpr MachineRepresentation kPhiRepresentation =
MachineRepresentation::kTagged;
JSGraphAssembler* const gasm_;
const TNode<Number> initial_value_;
const ConditionFunction1 cond_;
const StepFunction1 step_;
For1BodyFunction body_;
const TNode<Object> initial_arg0_;
};
ForBuilder1 For1(TNode<Number> initial_value, const ConditionFunction1& cond,
const StepFunction1& step, TNode<Object> initial_arg0) {
return {this, initial_value, cond, step, initial_arg0};
}
ForBuilder1 For1ZeroUntil(TNode<Number> excluded_limit,
TNode<Object> initial_arg0) {
TNode<Number> initial_value = ZeroConstant();
auto cond = [=](TNode<Number> i) {
return NumberLessThan(i, excluded_limit);
};
auto step = [=](TNode<Number> i) { return NumberAdd(i, OneConstant()); };
return {this, initial_value, cond, step, initial_arg0};
}
void ThrowIfNotCallable(TNode<Object> maybe_callable,
FrameState frame_state) {
IfNot(ObjectIsCallable(maybe_callable))
.Then(_ {
JSCallRuntime1(Runtime::kThrowCalledNonCallable, maybe_callable,
ContextInput(), frame_state);
Unreachable(); // The runtime call throws unconditionally.
})
.ExpectTrue();
}
const FeedbackSource& feedback() const {
CallParameters const& p = CallParametersOf(node_ptr()->op());
return p.feedback();
}
int ArgumentCount() const { return JSCallNode{node_ptr()}.ArgumentCount(); }
TNode<Object> Argument(int index) const {
return TNode<Object>::UncheckedCast(JSCallNode{node_ptr()}.Argument(index));
}
template <typename T>
TNode<T> ArgumentAs(int index) const {
return TNode<T>::UncheckedCast(Argument(index));
}
TNode<Object> ArgumentOrNaN(int index) {
return TNode<Object>::UncheckedCast(
ArgumentCount() > index ? Argument(index) : NaNConstant());
}
TNode<Object> ArgumentOrUndefined(int index) {
return TNode<Object>::UncheckedCast(
ArgumentCount() > index ? Argument(index) : UndefinedConstant());
}
TNode<Number> ArgumentOrZero(int index) {
return TNode<Number>::UncheckedCast(
ArgumentCount() > index ? Argument(index) : ZeroConstant());
}
TNode<Context> ContextInput() const {
return TNode<Context>::UncheckedCast(
NodeProperties::GetContextInput(node_));
}
FrameState FrameStateInput() const {
return FrameState(NodeProperties::GetFrameStateInput(node_));
}
CompilationDependencies* dependencies() const { return dependencies_; }
private:
CompilationDependencies* const dependencies_;
Node* const node_;
};
enum class ArrayReduceDirection { kLeft, kRight };
enum class ArrayFindVariant { kFind, kFindIndex };
enum class ArrayEverySomeVariant { kEvery, kSome };
enum class ArrayIndexOfIncludesVariant { kIncludes, kIndexOf };
// This subclass bundles functionality specific to reducing iterating array
// builtins.
class IteratingArrayBuiltinReducerAssembler : public JSCallReducerAssembler {
public:
IteratingArrayBuiltinReducerAssembler(JSCallReducer* reducer, Node* node)
: JSCallReducerAssembler(reducer, node) {
DCHECK(v8_flags.turbo_inline_array_builtins);
}
TNode<Object> ReduceArrayPrototypeForEach(MapInference* inference,
const bool has_stability_dependency,
ElementsKind kind,
SharedFunctionInfoRef shared);
TNode<Object> ReduceArrayPrototypeReduce(MapInference* inference,
const bool has_stability_dependency,
ElementsKind kind,
ArrayReduceDirection direction,
SharedFunctionInfoRef shared);
TNode<JSArray> ReduceArrayPrototypeMap(MapInference* inference,
const bool has_stability_dependency,
ElementsKind kind,
SharedFunctionInfoRef shared,
NativeContextRef native_context);
TNode<JSArray> ReduceArrayPrototypeFilter(MapInference* inference,
const bool has_stability_dependency,
ElementsKind kind,
SharedFunctionInfoRef shared,
NativeContextRef native_context);
TNode<Object> ReduceArrayPrototypeFind(MapInference* inference,
const bool has_stability_dependency,
ElementsKind kind,
SharedFunctionInfoRef shared,
NativeContextRef native_context,
ArrayFindVariant variant);
TNode<Boolean> ReduceArrayPrototypeEverySome(
MapInference* inference, const bool has_stability_dependency,
ElementsKind kind, SharedFunctionInfoRef shared,
NativeContextRef native_context, ArrayEverySomeVariant variant);
TNode<Object> ReduceArrayPrototypeAt(ZoneVector<MapRef> kinds,
bool needs_fallback_builtin_call);
TNode<Object> ReduceArrayPrototypeIndexOfIncludes(
ElementsKind kind, ArrayIndexOfIncludesVariant variant);
TNode<Number> ReduceArrayPrototypePush(MapInference* inference);
private:
// Returns {index,value}. Assumes that the map has not changed, but possibly
// the length and backing store.
std::pair<TNode<Number>, TNode<Object>> SafeLoadElement(ElementsKind kind,
TNode<JSArray> o,
TNode<Number> index) {
// Make sure that the access is still in bounds, since the callback could
// have changed the array's size.
TNode<Number> length = LoadJSArrayLength(o, kind);
index = CheckBounds(index, length);
// Reload the elements pointer before calling the callback, since the
// previous callback might have resized the array causing the elements
// buffer to be re-allocated.
TNode<HeapObject> elements =
LoadField<HeapObject>(AccessBuilder::ForJSObjectElements(), o);
TNode<Object> value = LoadElement<Object>(
AccessBuilder::ForFixedArrayElement(kind), elements, index);
return std::make_pair(index, value);
}
template <typename... Vars>
TNode<Object> MaybeSkipHole(
TNode<Object> o, ElementsKind kind,
GraphAssemblerLabel<sizeof...(Vars)>* continue_label,
TNode<Vars>... vars) {
if (!IsHoleyElementsKind(kind)) return o;
auto if_not_hole = MakeLabel(MachineRepresentationOf<Vars>::value...);
BranchWithHint(HoleCheck(kind, o), continue_label, &if_not_hole,
BranchHint::kFalse, vars...);
// The contract is that we don't leak "the hole" into "user JavaScript",
// so we must rename the {element} here to explicitly exclude "the hole"
// from the type of {element}.
Bind(&if_not_hole);
return TypeGuardNonInternal(o);
}
TNode<Smi> LoadJSArrayLength(TNode<JSArray> array, ElementsKind kind) {
return LoadField<Smi>(AccessBuilder::ForJSArrayLength(kind), array);
}
void StoreJSArrayLength(TNode<JSArray> array, TNode<Number> value,
ElementsKind kind) {
StoreField(AccessBuilder::ForJSArrayLength(kind), array, value);
}
void StoreFixedArrayBaseElement(TNode<FixedArrayBase> o, TNode<Number> index,
TNode<Object> v, ElementsKind kind) {
StoreElement(AccessBuilder::ForFixedArrayElement(kind), o, index, v);
}
TNode<FixedArrayBase> LoadElements(TNode<JSObject> o) {
return LoadField<FixedArrayBase>(AccessBuilder::ForJSObjectElements(), o);
}
TNode<Smi> LoadFixedArrayBaseLength(TNode<FixedArrayBase> o) {
return LoadField<Smi>(AccessBuilder::ForFixedArrayLength(), o);
}
TNode<Boolean> HoleCheck(ElementsKind kind, TNode<Object> v) {
return IsDoubleElementsKind(kind)
? NumberIsFloat64Hole(TNode<Number>::UncheckedCast(v))
: IsTheHole(v);
}
};
class PromiseBuiltinReducerAssembler : public JSCallReducerAssembler {
public:
PromiseBuiltinReducerAssembler(JSCallReducer* reducer, Node* node)
: JSCallReducerAssembler(reducer, node) {
DCHECK_EQ(IrOpcode::kJSConstruct, node->opcode());
}
TNode<Object> ReducePromiseConstructor(NativeContextRef native_context);
int ConstructArity() const {
return JSConstructNode{node_ptr()}.ArgumentCount();
}
TNode<Object> TargetInput() const {
return JSConstructNode{node_ptr()}.target();
}
TNode<Object> NewTargetInput() const {
return JSConstructNode{node_ptr()}.new_target();
}
private:
TNode<JSPromise> CreatePromise(TNode<Context> context) {
return AddNode<JSPromise>(
graph()->NewNode(javascript()->CreatePromise(), context, effect()));
}
TNode<Context> CreateFunctionContext(NativeContextRef native_context,
TNode<Context> outer_context,
int slot_count) {
return AddNode<Context>(graph()->NewNode(
javascript()->CreateFunctionContext(
native_context.scope_info(broker()),
slot_count - Context::MIN_CONTEXT_SLOTS, FUNCTION_SCOPE),
outer_context, effect(), control()));
}
void StoreContextSlot(TNode<Context> context, size_t slot_index,
TNode<Object> value) {
StoreField(AccessBuilder::ForContextSlot(slot_index), context, value);
}
TNode<JSFunction> CreateClosureFromBuiltinSharedFunctionInfo(
SharedFunctionInfoRef shared, TNode<Context> context) {
DCHECK(shared.HasBuiltinId());
Handle<FeedbackCell> feedback_cell =
isolate()->factory()->many_closures_cell();
Callable const callable =
Builtins::CallableFor(isolate(), shared.builtin_id());
CodeRef code = MakeRef(broker(), *callable.code());
return AddNode<JSFunction>(graph()->NewNode(
javascript()->CreateClosure(shared, code), HeapConstant(feedback_cell),
context, effect(), control()));
}
void CallPromiseExecutor(TNode<Object> executor, TNode<JSFunction> resolve,
TNode<JSFunction> reject, FrameState frame_state) {
JSConstructNode n(node_ptr());
const ConstructParameters& p = n.Parameters();
FeedbackSource no_feedback_source{};
Node* no_feedback = UndefinedConstant();
MayThrow(_ {
return AddNode<Object>(graph()->NewNode(
javascript()->Call(JSCallNode::ArityForArgc(2), p.frequency(),
no_feedback_source,
ConvertReceiverMode::kNullOrUndefined),
executor, UndefinedConstant(), resolve, reject, no_feedback,
n.context(), frame_state, effect(), control()));
});
}
void CallPromiseReject(TNode<JSFunction> reject, TNode<Object> exception,
FrameState frame_state) {
JSConstructNode n(node_ptr());
const ConstructParameters& p = n.Parameters();
FeedbackSource no_feedback_source{};
Node* no_feedback = UndefinedConstant();
MayThrow(_ {
return AddNode<Object>(graph()->NewNode(
javascript()->Call(JSCallNode::ArityForArgc(1), p.frequency(),
no_feedback_source,
ConvertReceiverMode::kNullOrUndefined),
reject, UndefinedConstant(), exception, no_feedback, n.context(),
frame_state, effect(), control()));
});
}
};
class FastApiCallReducerAssembler : public JSCallReducerAssembler {
public:
FastApiCallReducerAssembler(
JSCallReducer* reducer, Node* node,
const FunctionTemplateInfoRef function_template_info,
const FastApiCallFunctionVector& c_candidate_functions, Node* receiver,
Node* holder, const SharedFunctionInfoRef shared, Node* target,
const int arity, Node* effect)
: JSCallReducerAssembler(reducer, node),
c_candidate_functions_(c_candidate_functions),
function_template_info_(function_template_info),
receiver_(receiver),
holder_(holder),
shared_(shared),
target_(target),
arity_(arity) {
DCHECK_EQ(IrOpcode::kJSCall, node->opcode());
CHECK_GT(c_candidate_functions.size(), 0);
InitializeEffectControl(effect, NodeProperties::GetControlInput(node));
}
TNode<Object> ReduceFastApiCall() {
JSCallNode n(node_ptr());
// C arguments include the receiver at index 0. Thus C index 1 corresponds
// to the JS argument 0, etc.
// All functions in c_candidate_functions_ have the same number of
// arguments, so extract c_argument_count from the first function.
const int c_argument_count =
static_cast<int>(c_candidate_functions_[0].signature->ArgumentCount());
CHECK_GE(c_argument_count, kReceiver);
int cursor = 0;
base::SmallVector<Node*, kInlineSize> inputs(c_argument_count + arity_ +
kExtraInputsCount);
inputs[cursor++] = n.receiver();
// TODO(turbofan): Consider refactoring CFunctionInfo to distinguish
// between receiver and arguments, simplifying this (and related) spots.
int js_args_count = c_argument_count - kReceiver;
for (int i = 0; i < js_args_count; ++i) {
if (i < n.ArgumentCount()) {
inputs[cursor++] = n.Argument(i);
} else {
inputs[cursor++] = UndefinedConstant();
}
}
// Here we add the arguments for the slow call, which will be
// reconstructed at a later phase. Those are effectively the same
// arguments as for the fast call, but we want to have them as
// separate inputs, so that SimplifiedLowering can provide the best
// possible UseInfos for each of them. The inputs to FastApiCall
// look like:
// [fast callee, receiver, ... C arguments,
// call code, external constant for function, argc, call handler info data,
// holder, receiver, ... JS arguments, context, new frame state]
bool no_profiling =
broker()->dependencies()->DependOnNoProfilingProtector();
Callable call_api_callback = Builtins::CallableFor(
isolate(), no_profiling ? Builtin::kCallApiCallbackOptimizedNoProfiling
: Builtin::kCallApiCallbackOptimized);
CallInterfaceDescriptor cid = call_api_callback.descriptor();
CallDescriptor* call_descriptor =
Linkage::GetStubCallDescriptor(graph()->zone(), cid, arity_ + kReceiver,
CallDescriptor::kNeedsFrameState);
ApiFunction api_function(function_template_info_.callback(broker()));
ExternalReference function_reference = ExternalReference::Create(
isolate(), &api_function, ExternalReference::DIRECT_API_CALL,
function_template_info_.c_functions(broker()).data(),
function_template_info_.c_signatures(broker()).data(),
static_cast<unsigned>(
function_template_info_.c_functions(broker()).size()));
Node* continuation_frame_state = CreateInlinedApiFunctionFrameState(
jsgraph(), shared_, target_, ContextInput(), receiver_,
FrameStateInput());
inputs[cursor++] = HeapConstant(call_api_callback.code());
inputs[cursor++] = ExternalConstant(function_reference);
inputs[cursor++] = NumberConstant(arity_);
inputs[cursor++] =
Constant(function_template_info_.callback_data(broker()).value());
inputs[cursor++] = holder_;
inputs[cursor++] = receiver_;
for (int i = 0; i < arity_; ++i) {
inputs[cursor++] = Argument(i);
}
inputs[cursor++] = ContextInput();
inputs[cursor++] = continuation_frame_state;
inputs[cursor++] = effect();
inputs[cursor++] = control();
DCHECK_EQ(cursor, c_argument_count + arity_ + kExtraInputsCount);
return FastApiCall(call_descriptor, inputs.begin(), inputs.size());
}
private:
static constexpr int kSlowTarget = 1;
static constexpr int kEffectAndControl = 2;
static constexpr int kContextAndFrameState = 2;
static constexpr int kCallCodeDataAndArgc = 3;
static constexpr int kHolder = 1, kReceiver = 1;
static constexpr int kExtraInputsCount =
kSlowTarget + kEffectAndControl + kContextAndFrameState +
kCallCodeDataAndArgc + kHolder + kReceiver;
static constexpr int kInlineSize = 12;
TNode<Object> FastApiCall(CallDescriptor* descriptor, Node** inputs,
size_t inputs_size) {
return AddNode<Object>(
graph()->NewNode(simplified()->FastApiCall(c_candidate_functions_,
feedback(), descriptor),
static_cast<int>(inputs_size), inputs));
}
const FastApiCallFunctionVector c_candidate_functions_;
const FunctionTemplateInfoRef function_template_info_;
Node* const receiver_;
Node* const holder_;
const SharedFunctionInfoRef shared_;
Node* const target_;
const int arity_;
};
TNode<Number> JSCallReducerAssembler::SpeculativeToNumber(
TNode<Object> value, NumberOperationHint hint) {
return AddNode<Number>(
graph()->NewNode(simplified()->SpeculativeToNumber(hint, feedback()),
value, effect(), control()));
}
TNode<Smi> JSCallReducerAssembler::CheckSmi(TNode<Object> value) {
return AddNode<Smi>(graph()->NewNode(simplified()->CheckSmi(feedback()),
value, effect(), control()));
}
TNode<Number> JSCallReducerAssembler::CheckNumber(TNode<Object> value) {
return AddNode<Number>(graph()->NewNode(simplified()->CheckNumber(feedback()),
value, effect(), control()));
}
TNode<String> JSCallReducerAssembler::CheckString(TNode<Object> value) {
return AddNode<String>(graph()->NewNode(simplified()->CheckString(feedback()),
value, effect(), control()));
}
TNode<Number> JSCallReducerAssembler::CheckBounds(TNode<Number> value,
TNode<Number> limit,
CheckBoundsFlags flags) {
return AddNode<Number>(
graph()->NewNode(simplified()->CheckBounds(feedback(), flags), value,
limit, effect(), control()));
}
TNode<Smi> JSCallReducerAssembler::TypeGuardUnsignedSmall(TNode<Object> value) {
return TNode<Smi>::UncheckedCast(TypeGuard(Type::UnsignedSmall(), value));
}
TNode<Object> JSCallReducerAssembler::TypeGuardNonInternal(
TNode<Object> value) {
return TNode<Object>::UncheckedCast(TypeGuard(Type::NonInternal(), value));
}
TNode<Number> JSCallReducerAssembler::TypeGuardFixedArrayLength(
TNode<Object> value) {
DCHECK(TypeCache::Get()->kFixedDoubleArrayLengthType.Is(
TypeCache::Get()->kFixedArrayLengthType));
return TNode<Number>::UncheckedCast(
TypeGuard(TypeCache::Get()->kFixedArrayLengthType, value));
}
TNode<Object> JSCallReducerAssembler::Call4(
const Callable& callable, TNode<Context> context, TNode<Object> arg0,
TNode<Object> arg1, TNode<Object> arg2, TNode<Object> arg3) {
// TODO(jgruber): Make this more generic. Currently it's fitted to its single
// callsite.
CallDescriptor* desc = Linkage::GetStubCallDescriptor(
graph()->zone(), callable.descriptor(),
callable.descriptor().GetStackParameterCount(), CallDescriptor::kNoFlags,
Operator::kEliminatable);
return TNode<Object>::UncheckedCast(Call(desc, HeapConstant(callable.code()),
arg0, arg1, arg2, arg3, context));
}
TNode<Object> JSCallReducerAssembler::JSCall3(
TNode<Object> function, TNode<Object> this_arg, TNode<Object> arg0,
TNode<Object> arg1, TNode<Object> arg2, FrameState frame_state) {
JSCallNode n(node_ptr());
CallParameters const& p = n.Parameters();
return MayThrow(_ {
return AddNode<Object>(graph()->NewNode(
javascript()->Call(JSCallNode::ArityForArgc(3), p.frequency(),
p.feedback(), ConvertReceiverMode::kAny,
p.speculation_mode(),
CallFeedbackRelation::kUnrelated),
function, this_arg, arg0, arg1, arg2, n.feedback_vector(),
ContextInput(), frame_state, effect(), control()));
});
}
TNode<Object> JSCallReducerAssembler::JSCall4(
TNode<Object> function, TNode<Object> this_arg, TNode<Object> arg0,
TNode<Object> arg1, TNode<Object> arg2, TNode<Object> arg3,
FrameState frame_state) {
JSCallNode n(node_ptr());
CallParameters const& p = n.Parameters();
return MayThrow(_ {
return AddNode<Object>(graph()->NewNode(
javascript()->Call(JSCallNode::ArityForArgc(4), p.frequency(),
p.feedback(), ConvertReceiverMode::kAny,
p.speculation_mode(),
CallFeedbackRelation::kUnrelated),
function, this_arg, arg0, arg1, arg2, arg3, n.feedback_vector(),
ContextInput(), frame_state, effect(), control()));
});
}
TNode<Object> JSCallReducerAssembler::CopyNode() {
return MayThrow(_ {
Node* copy = graph()->CloneNode(node_ptr());
NodeProperties::ReplaceEffectInput(copy, effect());
NodeProperties::ReplaceControlInput(copy, control());
return AddNode<Object>(copy);
});
}
TNode<JSArray> JSCallReducerAssembler::CreateArrayNoThrow(
TNode<Object> ctor, TNode<Number> size, FrameState frame_state) {
return AddNode<JSArray>(
graph()->NewNode(javascript()->CreateArray(1, base::nullopt), ctor, ctor,
size, ContextInput(), frame_state, effect(), control()));
}
TNode<JSArray> JSCallReducerAssembler::AllocateEmptyJSArray(
ElementsKind kind, NativeContextRef native_context) {
// TODO(jgruber): Port AllocationBuilder to JSGraphAssembler.
MapRef map = native_context.GetInitialJSArrayMap(broker(), kind);
AllocationBuilder ab(jsgraph(), broker(), effect(), control());
ab.Allocate(map.instance_size(), AllocationType::kYoung, Type::Array());
ab.Store(AccessBuilder::ForMap(), map);
Node* empty_fixed_array = jsgraph()->EmptyFixedArrayConstant();
ab.Store(AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer(),
empty_fixed_array);
ab.Store(AccessBuilder::ForJSObjectElements(), empty_fixed_array);
ab.Store(AccessBuilder::ForJSArrayLength(kind), jsgraph()->ZeroConstant());
for (int i = 0; i < map.GetInObjectProperties(); ++i) {
ab.Store(AccessBuilder::ForJSObjectInObjectProperty(map, i),
jsgraph()->UndefinedConstant());
}
Node* result = ab.Finish();
InitializeEffectControl(result, control());
return TNode<JSArray>::UncheckedCast(result);
}
TNode<Number> JSCallReducerAssembler::LoadMapElementsKind(TNode<Map> map) {
TNode<Number> bit_field2 =
LoadField<Number>(AccessBuilder::ForMapBitField2(), map);
return NumberShiftRightLogical(
NumberBitwiseAnd(bit_field2,
NumberConstant(Map::Bits2::ElementsKindBits::kMask)),
NumberConstant(Map::Bits2::ElementsKindBits::kShift));
}
TNode<Object> JSCallReducerAssembler::ReduceMathUnary(const Operator* op) {
TNode<Object> input = Argument(0);
TNode<Number> input_as_number = SpeculativeToNumber(input);
return TNode<Object>::UncheckedCast(graph()->NewNode(op, input_as_number));
}
TNode<Object> JSCallReducerAssembler::ReduceMathBinary(const Operator* op) {
TNode<Object> left = Argument(0);
TNode<Object> right = ArgumentOrNaN(1);
TNode<Number> left_number = SpeculativeToNumber(left);
TNode<Number> right_number = SpeculativeToNumber(right);
return TNode<Object>::UncheckedCast(
graph()->NewNode(op, left_number, right_number));
}
TNode<String> JSCallReducerAssembler::ReduceStringPrototypeSubstring() {
TNode<Object> receiver = ReceiverInput();
TNode<Object> start = Argument(0);
TNode<Object> end = ArgumentOrUndefined(1);
TNode<String> receiver_string = CheckString(receiver);
TNode<Number> start_smi = CheckSmi(start);
TNode<Number> length = StringLength(receiver_string);
TNode<Number> end_smi = SelectIf<Number>(IsUndefined(end))
.Then(_ { return length; })
.Else(_ { return CheckSmi(end); })
.ExpectFalse()
.Value();
TNode<Number> zero = TNode<Number>::UncheckedCast(ZeroConstant());
TNode<Number> finalStart = NumberMin(NumberMax(start_smi, zero), length);
TNode<Number> finalEnd = NumberMin(NumberMax(end_smi, zero), length);
TNode<Number> from = NumberMin(finalStart, finalEnd);
TNode<Number> to = NumberMax(finalStart, finalEnd);
return StringSubstring(receiver_string, from, to);
}
TNode<Boolean> JSCallReducerAssembler::ReduceStringPrototypeStartsWith(
StringRef search_element_string) {
DCHECK(search_element_string.IsContentAccessible());
TNode<Object> receiver = ReceiverInput();
TNode<Object> start = ArgumentOrZero(1);
TNode<String> receiver_string = CheckString(receiver);
TNode<Smi> start_smi = CheckSmi(start);
TNode<Number> length = StringLength(receiver_string);
TNode<Number> zero = ZeroConstant();
TNode<Number> clamped_start = NumberMin(NumberMax(start_smi, zero), length);
int search_string_length = search_element_string.length();
DCHECK(search_string_length <= JSCallReducer::kMaxInlineMatchSequence);
auto out = MakeLabel(MachineRepresentation::kTagged);
auto search_string_too_long =
NumberLessThan(NumberSubtract(length, clamped_start),
NumberConstant(search_string_length));
GotoIf(search_string_too_long, &out, BranchHint::kFalse, FalseConstant());
static_assert(String::kMaxLength <= kSmiMaxValue);
for (int i = 0; i < search_string_length; i++) {
TNode<Number> k = NumberConstant(i);
TNode<Number> receiver_string_position = TNode<Number>::UncheckedCast(
TypeGuard(Type::UnsignedSmall(), NumberAdd(k, clamped_start)));
Node* receiver_string_char =
StringCharCodeAt(receiver_string, receiver_string_position);
Node* search_string_char = jsgraph()->ConstantNoHole(
search_element_string.GetChar(broker(), i).value());
auto is_equal = graph()->NewNode(simplified()->NumberEqual(),
search_string_char, receiver_string_char);
GotoIfNot(is_equal, &out, FalseConstant());
}
Goto(&out, TrueConstant());
Bind(&out);
return out.PhiAt<Boolean>(0);
}
TNode<Boolean> JSCallReducerAssembler::ReduceStringPrototypeStartsWith() {
TNode<Object> receiver = ReceiverInput();
TNode<Object> search_element = ArgumentOrUndefined(0);
TNode<Object> start = ArgumentOrZero(1);
TNode<String> receiver_string = CheckString(receiver);
TNode<String> search_string = CheckString(search_element);
TNode<Smi> start_smi = CheckSmi(start);
TNode<Number> length = StringLength(receiver_string);
TNode<Number> zero = ZeroConstant();
TNode<Number> clamped_start = NumberMin(NumberMax(start_smi, zero), length);
TNode<Number> search_string_length = StringLength(search_string);
auto out = MakeLabel(MachineRepresentation::kTagged);
auto search_string_too_long = NumberLessThan(
NumberSubtract(length, clamped_start), search_string_length);
GotoIf(search_string_too_long, &out, BranchHint::kFalse, FalseConstant());
static_assert(String::kMaxLength <= kSmiMaxValue);
ForZeroUntil(search_string_length).Do([&](TNode<Number> k) {
TNode<Number> receiver_string_position = TNode<Number>::UncheckedCast(