forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjs-native-context-specialization.cc
More file actions
4147 lines (3739 loc) · 176 KB
/
js-native-context-specialization.cc
File metadata and controls
4147 lines (3739 loc) · 176 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-native-context-specialization.h"
#include "src/base/logging.h"
#include "src/base/optional.h"
#include "src/builtins/accessors.h"
#include "src/codegen/code-factory.h"
#include "src/common/globals.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/const-tracking-let-helpers.h"
#include "src/compiler/frame-states.h"
#include "src/compiler/graph-assembler.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/js-heap-broker.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/node-properties.h"
#include "src/compiler/property-access-builder.h"
#include "src/compiler/simplified-operator.h"
#include "src/compiler/type-cache.h"
#include "src/flags/flags.h"
#include "src/handles/handles.h"
#include "src/heap/factory.h"
#include "src/heap/heap-write-barrier-inl.h"
#include "src/objects/elements-kind.h"
#include "src/objects/feedback-vector.h"
#include "src/objects/heap-number.h"
#include "src/objects/string.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
bool HasNumberMaps(JSHeapBroker* broker, ZoneVector<MapRef> const& maps) {
for (MapRef map : maps) {
if (map.IsHeapNumberMap()) return true;
}
return false;
}
bool HasOnlyJSArrayMaps(JSHeapBroker* broker, ZoneVector<MapRef> const& maps) {
for (MapRef map : maps) {
if (!map.IsJSArrayMap()) return false;
}
return true;
}
} // namespace
JSNativeContextSpecialization::JSNativeContextSpecialization(
Editor* editor, JSGraph* jsgraph, JSHeapBroker* broker, Flags flags,
Zone* zone, Zone* shared_zone)
: AdvancedReducer(editor),
jsgraph_(jsgraph),
broker_(broker),
flags_(flags),
global_object_(
broker->target_native_context().global_object(broker).object()),
global_proxy_(
broker->target_native_context().global_proxy_object(broker).object()),
zone_(zone),
shared_zone_(shared_zone),
type_cache_(TypeCache::Get()),
created_strings_(zone) {}
Reduction JSNativeContextSpecialization::Reduce(Node* node) {
switch (node->opcode()) {
case IrOpcode::kJSAdd:
return ReduceJSAdd(node);
case IrOpcode::kJSAsyncFunctionEnter:
return ReduceJSAsyncFunctionEnter(node);
case IrOpcode::kJSAsyncFunctionReject:
return ReduceJSAsyncFunctionReject(node);
case IrOpcode::kJSAsyncFunctionResolve:
return ReduceJSAsyncFunctionResolve(node);
case IrOpcode::kJSGetSuperConstructor:
return ReduceJSGetSuperConstructor(node);
case IrOpcode::kJSFindNonDefaultConstructorOrConstruct:
return ReduceJSFindNonDefaultConstructorOrConstruct(node);
case IrOpcode::kJSInstanceOf:
return ReduceJSInstanceOf(node);
case IrOpcode::kJSHasInPrototypeChain:
return ReduceJSHasInPrototypeChain(node);
case IrOpcode::kJSOrdinaryHasInstance:
return ReduceJSOrdinaryHasInstance(node);
case IrOpcode::kJSPromiseResolve:
return ReduceJSPromiseResolve(node);
case IrOpcode::kJSResolvePromise:
return ReduceJSResolvePromise(node);
case IrOpcode::kJSLoadGlobal:
return ReduceJSLoadGlobal(node);
case IrOpcode::kJSStoreGlobal:
return ReduceJSStoreGlobal(node);
case IrOpcode::kJSLoadNamed:
return ReduceJSLoadNamed(node);
case IrOpcode::kJSLoadNamedFromSuper:
return ReduceJSLoadNamedFromSuper(node);
case IrOpcode::kJSSetNamedProperty:
return ReduceJSSetNamedProperty(node);
case IrOpcode::kJSHasProperty:
return ReduceJSHasProperty(node);
case IrOpcode::kJSLoadProperty:
return ReduceJSLoadProperty(node);
case IrOpcode::kJSSetKeyedProperty:
return ReduceJSSetKeyedProperty(node);
case IrOpcode::kJSDefineKeyedOwnProperty:
return ReduceJSDefineKeyedOwnProperty(node);
case IrOpcode::kJSDefineNamedOwnProperty:
return ReduceJSDefineNamedOwnProperty(node);
case IrOpcode::kJSDefineKeyedOwnPropertyInLiteral:
return ReduceJSDefineKeyedOwnPropertyInLiteral(node);
case IrOpcode::kJSStoreInArrayLiteral:
return ReduceJSStoreInArrayLiteral(node);
case IrOpcode::kJSToObject:
return ReduceJSToObject(node);
case IrOpcode::kJSToString:
return ReduceJSToString(node);
case IrOpcode::kJSGetIterator:
return ReduceJSGetIterator(node);
default:
break;
}
return NoChange();
}
// If {node} is a HeapConstant<String>, return the String's length. If {node} is
// a number, return the maximum size that a stringified number can have.
// Otherwise, we can't easily convert {node} into a String, and we return
// nullopt.
// static
base::Optional<size_t> JSNativeContextSpecialization::GetMaxStringLength(
JSHeapBroker* broker, Node* node) {
HeapObjectMatcher matcher(node);
if (matcher.HasResolvedValue() && matcher.Ref(broker).IsString()) {
StringRef input = matcher.Ref(broker).AsString();
return input.length();
}
NumberMatcher number_matcher(node);
if (number_matcher.HasResolvedValue()) {
return kMaxDoubleStringLength;
}
// We don't support objects with possibly monkey-patched prototype.toString
// as it might have side-effects, so we shouldn't attempt lowering them.
return base::nullopt;
}
Reduction JSNativeContextSpecialization::ReduceJSToString(Node* node) {
DCHECK_EQ(IrOpcode::kJSToString, node->opcode());
Node* const input = node->InputAt(0);
HeapObjectMatcher matcher(input);
if (matcher.HasResolvedValue() && matcher.Ref(broker()).IsString()) {
Reduction reduction = Changed(input); // JSToString(x:string) => x
ReplaceWithValue(node, reduction.replacement());
return reduction;
}
// TODO(turbofan): This optimization is weaker than what we used to have
// in js-typed-lowering for OrderedNumbers. We don't have types here though,
// so alternative approach should be designed if this causes performance
// regressions and the stronger optimization should be re-implemented.
NumberMatcher number_matcher(input);
if (number_matcher.HasResolvedValue()) {
Handle<Object> num_obj =
broker()
->local_isolate_or_isolate()
->factory()
->NewNumber<AllocationType::kOld>(number_matcher.ResolvedValue());
Handle<String> num_str =
broker()->local_isolate_or_isolate()->factory()->NumberToString(
num_obj);
Node* reduced = graph()->NewNode(
common()->HeapConstant(broker()->CanonicalPersistentHandle(num_str)));
ReplaceWithValue(node, reduced);
return Replace(reduced);
}
return NoChange();
}
// Return a String from {node}, which should be either a HeapConstant<String>
// (in which case we return the String), or a number (in which case we convert
// it to a String).
Handle<String> JSNativeContextSpecialization::CreateStringConstant(Node* node) {
DCHECK(IrOpcode::IsConstantOpcode(node->opcode()));
NumberMatcher number_matcher(node);
if (number_matcher.HasResolvedValue()) {
Handle<Object> num_obj =
broker()
->local_isolate_or_isolate()
->factory()
->NewNumber<AllocationType::kOld>(number_matcher.ResolvedValue());
// Note that we do not store the result of NumberToString in
// {created_strings_}, because the latter is used to know if strings are
// safe to be used in the background, but we always have as additional
// information the node from which the string was created ({node} is that
// case), and if this node is a kHeapNumber, then we know that we must have
// created the string, and that there it is safe to read. So, we don't need
// {created_strings_} in that case.
return broker()->local_isolate_or_isolate()->factory()->NumberToString(
num_obj);
} else {
HeapObjectMatcher matcher(node);
if (matcher.HasResolvedValue() && matcher.Ref(broker()).IsString()) {
return matcher.Ref(broker()).AsString().object();
} else {
UNREACHABLE();
}
}
}
namespace {
bool IsStringConstant(JSHeapBroker* broker, Node* node) {
HeapObjectMatcher matcher(node);
return matcher.HasResolvedValue() && matcher.Ref(broker).IsString();
}
bool IsStringWithNonAccessibleContent(JSHeapBroker* broker, Node* node) {
HeapObjectMatcher matcher(node);
if (matcher.HasResolvedValue() && matcher.Ref(broker).IsString()) {
StringRef input = matcher.Ref(broker).AsString();
return !input.IsContentAccessible();
}
return false;
}
} // namespace
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionEnter(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionEnter, node->opcode());
Node* closure = NodeProperties::GetValueInput(node, 0);
Node* receiver = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Create the promise for the async function.
Node* promise = effect =
graph()->NewNode(javascript()->CreatePromise(), context, effect);
// Create the JSAsyncFunctionObject based on the SharedFunctionInfo
// extracted from the top-most frame in {frame_state}.
SharedFunctionInfoRef shared = MakeRef(
broker(),
FrameStateInfoOf(frame_state->op()).shared_info().ToHandleChecked());
DCHECK(shared.is_compiled());
int register_count =
shared.internal_formal_parameter_count_without_receiver() +
shared.GetBytecodeArray(broker()).register_count();
MapRef fixed_array_map = broker()->fixed_array_map();
AllocationBuilder ab(jsgraph(), broker(), effect, control);
if (!ab.CanAllocateArray(register_count, fixed_array_map)) {
return NoChange();
}
Node* value = effect =
graph()->NewNode(javascript()->CreateAsyncFunctionObject(register_count),
closure, receiver, promise, context, effect, control);
ReplaceWithValue(node, value, effect, control);
return Replace(value);
}
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionReject(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionReject, node->opcode());
Node* async_function_object = NodeProperties::GetValueInput(node, 0);
Node* reason = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Load the promise from the {async_function_object}.
Node* promise = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
async_function_object, effect, control);
// Create a nested frame state inside the current method's most-recent
// {frame_state} that will ensure that lazy deoptimizations at this
// point will still return the {promise} instead of the result of the
// JSRejectPromise operation (which yields undefined).
Node* parameters[] = {promise};
frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kAsyncFunctionLazyDeoptContinuation, context,
parameters, arraysize(parameters), frame_state,
ContinuationFrameStateMode::LAZY);
// Disable the additional debug event for the rejection since a
// debug event already happend for the exception that got us here.
Node* debug_event = jsgraph()->FalseConstant();
effect = graph()->NewNode(javascript()->RejectPromise(), promise, reason,
debug_event, context, frame_state, effect, control);
ReplaceWithValue(node, promise, effect, control);
return Replace(promise);
}
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionResolve(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionResolve, node->opcode());
Node* async_function_object = NodeProperties::GetValueInput(node, 0);
Node* value = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Load the promise from the {async_function_object}.
Node* promise = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
async_function_object, effect, control);
// Create a nested frame state inside the current method's most-recent
// {frame_state} that will ensure that lazy deoptimizations at this
// point will still return the {promise} instead of the result of the
// JSResolvePromise operation (which yields undefined).
Node* parameters[] = {promise};
frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kAsyncFunctionLazyDeoptContinuation, context,
parameters, arraysize(parameters), frame_state,
ContinuationFrameStateMode::LAZY);
effect = graph()->NewNode(javascript()->ResolvePromise(), promise, value,
context, frame_state, effect, control);
ReplaceWithValue(node, promise, effect, control);
return Replace(promise);
}
// Concatenates {left} and {right}. The result is fairly similar to creating a
// new ConsString with {left} and {right} and then flattening it, which we don't
// do because String::Flatten does not support background threads. Rather than
// implementing a full String::Flatten for background threads, we prefered to
// implement this Concatenate function, which, unlike String::Flatten, doesn't
// need to replace ConsStrings by ThinStrings.
Handle<String> JSNativeContextSpecialization::Concatenate(
Handle<String> left, Handle<String> right) {
if (left->length() == 0) return right;
if (right->length() == 0) return left;
// Repeated concatenations have a quadratic cost (eg, "s+=a;s+=b;s+=c;...").
// Rather than doing static analysis to determine how many concatenations we
// there are and how many uses the result of each concatenation have, we
// generate ConsString when the result of the concatenation would have more
// than {kConstantStringFlattenMaxSize} characters, and flattened SeqString
// otherwise.
// TODO(dmercadier): ideally, we would like to get rid of this constant, and
// always flatten. This requires some care to avoid the quadratic worst-case.
constexpr int32_t kConstantStringFlattenMaxSize = 100;
int32_t length = left->length() + right->length();
if (length > kConstantStringFlattenMaxSize) {
// The generational write-barrier doesn't work in background threads, so,
// if {left} or {right} are in the young generation, we would have to copy
// them to the local heap (which is old) before creating the (old)
// ConsString. But, copying a ConsString instead of flattening it to a
// SeqString makes no sense here (since flattening would be faster and use
// less memory). Thus, if one of {left} or {right} is a young string, we'll
// build a SeqString rather than a ConsString, regardless of {length}.
// TODO(dmercadier, dinfuehr): always build a ConsString here once the
// generational write-barrier supports background threads.
if (!LocalHeap::Current() ||
(!ObjectInYoungGeneration(*left) && !ObjectInYoungGeneration(*right))) {
return broker()
->local_isolate_or_isolate()
->factory()
->NewConsString(left, right, AllocationType::kOld)
.ToHandleChecked();
}
}
// If one of the string is not in readonly space, then we need a
// SharedStringAccessGuardIfNeeded before accessing its content.
bool require_guard = SharedStringAccessGuardIfNeeded::IsNeeded(
*left, broker()->local_isolate_or_isolate()) ||
SharedStringAccessGuardIfNeeded::IsNeeded(
*right, broker()->local_isolate_or_isolate());
SharedStringAccessGuardIfNeeded access_guard(
require_guard ? broker()->local_isolate_or_isolate() : nullptr);
if (left->IsOneByteRepresentation() && right->IsOneByteRepresentation()) {
// {left} and {right} are 1-byte ==> the result will be 1-byte.
// Note that we need a canonical handle, because we insert in
// {created_strings_} the handle's address, which is kinda meaningless if
// the handle isn't canonical.
Handle<SeqOneByteString> flat = broker()->CanonicalPersistentHandle(
broker()
->local_isolate_or_isolate()
->factory()
->NewRawOneByteString(length, AllocationType::kOld)
.ToHandleChecked());
created_strings_.insert(flat);
DisallowGarbageCollection no_gc;
String::WriteToFlat(*left, flat->GetChars(no_gc, access_guard), 0,
left->length(), access_guard);
String::WriteToFlat(*right,
flat->GetChars(no_gc, access_guard) + left->length(), 0,
right->length(), access_guard);
return flat;
} else {
// One (or both) of {left} and {right} is 2-byte ==> the result will be
// 2-byte.
Handle<SeqTwoByteString> flat = broker()->CanonicalPersistentHandle(
broker()
->local_isolate_or_isolate()
->factory()
->NewRawTwoByteString(length, AllocationType::kOld)
.ToHandleChecked());
created_strings_.insert(flat);
DisallowGarbageCollection no_gc;
String::WriteToFlat(*left, flat->GetChars(no_gc, access_guard), 0,
left->length(), access_guard);
String::WriteToFlat(*right,
flat->GetChars(no_gc, access_guard) + left->length(), 0,
right->length(), access_guard);
return flat;
}
}
bool JSNativeContextSpecialization::StringCanSafelyBeRead(Node* const node,
Handle<String> str) {
DCHECK(node->opcode() == IrOpcode::kHeapConstant ||
node->opcode() == IrOpcode::kNumberConstant);
if (broker()->IsMainThread()) {
// All strings are safe to be read on the main thread.
return true;
}
if (node->opcode() == IrOpcode::kNumberConstant) {
// If {node} is a number constant, then {str} is the stringification of this
// number which we must have created ourselves.
return true;
}
return !IsStringWithNonAccessibleContent(broker(), node) ||
created_strings_.find(str) != created_strings_.end();
}
Reduction JSNativeContextSpecialization::ReduceJSAdd(Node* node) {
// TODO(turbofan): This has to run together with the inlining and
// native context specialization to be able to leverage the string
// constant-folding for optimizing property access, but we should
// nevertheless find a better home for this at some point.
DCHECK_EQ(IrOpcode::kJSAdd, node->opcode());
Node* const lhs = node->InputAt(0);
Node* const rhs = node->InputAt(1);
base::Optional<size_t> lhs_len = GetMaxStringLength(broker(), lhs);
base::Optional<size_t> rhs_len = GetMaxStringLength(broker(), rhs);
if (!lhs_len || !rhs_len) return NoChange();
// Fold if at least one of the parameters is a string constant and the
// addition won't throw due to too long result.
if (*lhs_len + *rhs_len <= String::kMaxLength &&
(IsStringConstant(broker(), lhs) || IsStringConstant(broker(), rhs))) {
// We need canonical handles for {left} and {right}, in order to be able to
// search {created_strings_} if needed.
Handle<String> left =
broker()->CanonicalPersistentHandle(CreateStringConstant(lhs));
Handle<String> right =
broker()->CanonicalPersistentHandle(CreateStringConstant(rhs));
if (!(StringCanSafelyBeRead(lhs, left) &&
StringCanSafelyBeRead(rhs, right))) {
// One of {lhs} or {rhs} is not safe to be read in the background.
if (left->length() + right->length() > ConsString::kMinLength &&
(!LocalHeap::Current() || (!ObjectInYoungGeneration(*left) &&
!ObjectInYoungGeneration(*right)))) {
// We can create a ConsString with {left} and {right}, without needing
// to read their content (and this ConsString will not introduce
// old-to-new pointers from the background).
Handle<String> concatenated =
broker()
->local_isolate_or_isolate()
->factory()
->NewConsString(left, right, AllocationType::kOld)
.ToHandleChecked();
Node* reduced = graph()->NewNode(common()->HeapConstant(
broker()->CanonicalPersistentHandle(concatenated)));
ReplaceWithValue(node, reduced);
return Replace(reduced);
} else {
// Concatenating those strings would not produce a ConsString but rather
// a flat string (because the result is small). And, since the strings
// are not safe to be read in the background, this wouldn't be safe.
// Or, one of the string is in the young generation, and since the
// generational barrier doesn't support background threads, we cannot
// create the ConsString.
return NoChange();
}
}
Handle<String> concatenated = Concatenate(left, right);
Node* reduced = graph()->NewNode(common()->HeapConstant(
broker()->CanonicalPersistentHandle(concatenated)));
ReplaceWithValue(node, reduced);
return Replace(reduced);
}
return NoChange();
}
Reduction JSNativeContextSpecialization::ReduceJSGetSuperConstructor(
Node* node) {
DCHECK_EQ(IrOpcode::kJSGetSuperConstructor, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
// Check if the input is a known JSFunction.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue() || !m.Ref(broker()).IsJSFunction()) {
return NoChange();
}
JSFunctionRef function = m.Ref(broker()).AsJSFunction();
MapRef function_map = function.map(broker());
HeapObjectRef function_prototype = function_map.prototype(broker());
// We can constant-fold the super constructor access if the
// {function}s map is stable, i.e. we can use a code dependency
// to guard against [[Prototype]] changes of {function}.
if (function_map.is_stable()) {
dependencies()->DependOnStableMap(function_map);
Node* value = jsgraph()->ConstantNoHole(function_prototype, broker());
ReplaceWithValue(node, value);
return Replace(value);
}
return NoChange();
}
Reduction
JSNativeContextSpecialization::ReduceJSFindNonDefaultConstructorOrConstruct(
Node* node) {
JSFindNonDefaultConstructorOrConstructNode n(node);
Node* this_function = n.this_function();
Node* new_target = n.new_target();
Node* effect = n.effect();
Control control = n.control();
// If the JSFindNonDefaultConstructorOrConstruct operation is inside a try
// catch, wiring up the graph is complex (reason: if
// JSFindNonDefaultConstructorOrConstruct reduces to a constant which is
// something else than a default base ctor, it cannot throw an exception, and
// the try-catch structure has to be rewired). As this use case is rare, give
// up optimizing it here.
if (NodeProperties::IsExceptionalCall(node)) {
return NoChange();
}
// TODO(v8:13091): Don't produce incomplete stack traces when debug is active.
// We already deopt when a breakpoint is set. But it would be even nicer to
// avoid producting incomplete stack traces when when debug is active, even if
// there are no breakpoints - then a user inspecting stack traces via Dev
// Tools would always see the full stack trace.
// Check if the input is a known JSFunction.
HeapObjectMatcher m(this_function);
if (!m.HasResolvedValue() || !m.Ref(broker()).IsJSFunction()) {
return NoChange();
}
JSFunctionRef this_function_ref = m.Ref(broker()).AsJSFunction();
MapRef function_map = this_function_ref.map(broker());
HeapObjectRef current = function_map.prototype(broker());
// The uppermost JSFunction on the class hierarchy (above it, there can be
// other JSObjects, e.g., Proxies).
OptionalJSObjectRef last_function;
Node* return_value;
Node* ctor_or_instance;
// Walk the class inheritance tree until we find a ctor which is not a default
// derived ctor.
while (true) {
if (!current.IsJSFunction()) {
return NoChange();
}
JSFunctionRef current_function = current.AsJSFunction();
// If there are class fields, bail out. TODO(v8:13091): Handle them here.
if (current_function.shared(broker())
.requires_instance_members_initializer()) {
return NoChange();
}
// If there are private methods, bail out. TODO(v8:13091): Handle them here.
if (current_function.context(broker())
.scope_info(broker())
.ClassScopeHasPrivateBrand()) {
return NoChange();
}
FunctionKind kind = current_function.shared(broker()).kind();
if (kind != FunctionKind::kDefaultDerivedConstructor) {
// The hierarchy walk will end here; this is the last change to bail out
// before creating new nodes.
if (!dependencies()->DependOnArrayIteratorProtector()) {
return NoChange();
}
last_function = current_function;
if (kind == FunctionKind::kDefaultBaseConstructor) {
return_value = jsgraph()->BooleanConstant(true);
// Generate a builtin call for creating the instance.
Node* constructor =
jsgraph()->ConstantNoHole(current_function, broker());
// In the current FrameState setup, the two outputs of this bytecode are
// poked at indices slot(index(reg_2)) (boolean_output) and
// slot(index(reg_2) + 1) (object_output). Now we're reducing this
// bytecode to a builtin call which only has one output (object_output).
// Change where in the FrameState the output is poked at.
// The current poke location points to the location for boolean_ouput.
// We move the poke location by -1, since the poke location decreases
// when the register index increases (see
// BytecodeGraphBuilder::Environment::BindRegistersToProjections).
// The location for boolean_output is already hard-wired to true (which
// is the correct value here) in
// BytecodeGraphBuilder::VisitFindNonDefaultConstructorOrConstruct.
FrameState old_frame_state = n.frame_state();
auto old_poke_offset = old_frame_state.frame_state_info()
.state_combine()
.GetOffsetToPokeAt();
FrameState new_frame_state = CloneFrameState(
jsgraph(), old_frame_state,
OutputFrameStateCombine::PokeAt(old_poke_offset - 1));
effect = ctor_or_instance = graph()->NewNode(
jsgraph()->javascript()->Create(), constructor, new_target,
n.context(), new_frame_state, effect, control);
} else {
return_value = jsgraph()->BooleanConstant(false);
ctor_or_instance =
jsgraph()->ConstantNoHole(current_function, broker());
}
break;
}
// Keep walking up the class tree.
current = current_function.map(broker()).prototype(broker());
}
dependencies()->DependOnStablePrototypeChain(
function_map, WhereToStart::kStartAtReceiver, last_function);
// Update the uses of {node}.
for (Edge edge : node->use_edges()) {
Node* const user = edge.from();
if (NodeProperties::IsEffectEdge(edge)) {
edge.UpdateTo(effect);
} else if (NodeProperties::IsControlEdge(edge)) {
edge.UpdateTo(control);
} else {
DCHECK(NodeProperties::IsValueEdge(edge));
switch (ProjectionIndexOf(user->op())) {
case 0:
Replace(user, return_value);
break;
case 1:
Replace(user, ctor_or_instance);
break;
default:
UNREACHABLE();
}
}
}
node->Kill();
return Replace(return_value);
}
Reduction JSNativeContextSpecialization::ReduceJSInstanceOf(Node* node) {
JSInstanceOfNode n(node);
FeedbackParameter const& p = n.Parameters();
Node* object = n.left();
Node* constructor = n.right();
TNode<Object> context = n.context();
FrameState frame_state = n.frame_state();
Effect effect = n.effect();
Control control = n.control();
// Check if the right hand side is a known {receiver}, or
// we have feedback from the InstanceOfIC.
OptionalJSObjectRef receiver;
HeapObjectMatcher m(constructor);
if (m.HasResolvedValue() && m.Ref(broker()).IsJSObject()) {
receiver = m.Ref(broker()).AsJSObject();
} else if (p.feedback().IsValid()) {
ProcessedFeedback const& feedback =
broker()->GetFeedbackForInstanceOf(FeedbackSource(p.feedback()));
if (feedback.IsInsufficient()) return NoChange();
receiver = feedback.AsInstanceOf().value();
} else {
return NoChange();
}
if (!receiver.has_value()) return NoChange();
MapRef receiver_map = receiver->map(broker());
NameRef name = broker()->has_instance_symbol();
PropertyAccessInfo access_info =
broker()->GetPropertyAccessInfo(receiver_map, name, AccessMode::kLoad);
// TODO(v8:11457) Support dictionary mode holders here.
if (access_info.IsInvalid() || access_info.HasDictionaryHolder()) {
return NoChange();
}
access_info.RecordDependencies(dependencies());
PropertyAccessBuilder access_builder(jsgraph(), broker());
if (access_info.IsNotFound()) {
// If there's no @@hasInstance handler, the OrdinaryHasInstance operation
// takes over, but that requires the constructor to be callable.
if (!receiver_map.is_callable()) return NoChange();
dependencies()->DependOnStablePrototypeChains(
access_info.lookup_start_object_maps(), kStartAtPrototype);
// Monomorphic property access.
access_builder.BuildCheckMaps(constructor, &effect, control,
access_info.lookup_start_object_maps());
// Lower to OrdinaryHasInstance(C, O).
NodeProperties::ReplaceValueInput(node, constructor, 0);
NodeProperties::ReplaceValueInput(node, object, 1);
NodeProperties::ReplaceEffectInput(node, effect);
static_assert(n.FeedbackVectorIndex() == 2);
node->RemoveInput(n.FeedbackVectorIndex());
NodeProperties::ChangeOp(node, javascript()->OrdinaryHasInstance());
return Changed(node).FollowedBy(ReduceJSOrdinaryHasInstance(node));
}
if (access_info.IsFastDataConstant()) {
OptionalJSObjectRef holder = access_info.holder();
bool found_on_proto = holder.has_value();
JSObjectRef holder_ref = found_on_proto ? holder.value() : receiver.value();
if (access_info.field_representation().IsDouble()) return NoChange();
OptionalObjectRef constant = holder_ref.GetOwnFastConstantDataProperty(
broker(), access_info.field_representation(), access_info.field_index(),
dependencies());
if (!constant.has_value() || !constant->IsHeapObject() ||
!constant->AsHeapObject().map(broker()).is_callable()) {
return NoChange();
}
if (found_on_proto) {
dependencies()->DependOnStablePrototypeChains(
access_info.lookup_start_object_maps(), kStartAtPrototype,
holder.value());
}
// Check that {constructor} is actually {receiver}.
constructor = access_builder.BuildCheckValue(constructor, &effect, control,
receiver->object());
// Monomorphic property access.
access_builder.BuildCheckMaps(constructor, &effect, control,
access_info.lookup_start_object_maps());
// Create a nested frame state inside the current method's most-recent frame
// state that will ensure that deopts that happen after this point will not
// fallback to the last Checkpoint--which would completely re-execute the
// instanceof logic--but rather create an activation of a version of the
// ToBoolean stub that finishes the remaining work of instanceof and returns
// to the caller without duplicating side-effects upon a lazy deopt.
Node* continuation_frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kToBooleanLazyDeoptContinuation, context, nullptr,
0, frame_state, ContinuationFrameStateMode::LAZY);
// Call the @@hasInstance handler.
Node* target = jsgraph()->ConstantNoHole(*constant, broker());
Node* feedback = jsgraph()->UndefinedConstant();
// Value inputs plus context, frame state, effect, control.
static_assert(JSCallNode::ArityForArgc(1) + 4 == 8);
node->EnsureInputCount(graph()->zone(), 8);
node->ReplaceInput(JSCallNode::TargetIndex(), target);
node->ReplaceInput(JSCallNode::ReceiverIndex(), constructor);
node->ReplaceInput(JSCallNode::ArgumentIndex(0), object);
node->ReplaceInput(3, feedback);
node->ReplaceInput(4, context);
node->ReplaceInput(5, continuation_frame_state);
node->ReplaceInput(6, effect);
node->ReplaceInput(7, control);
NodeProperties::ChangeOp(
node, javascript()->Call(JSCallNode::ArityForArgc(1), CallFrequency(),
FeedbackSource(),
ConvertReceiverMode::kNotNullOrUndefined));
// Rewire the value uses of {node} to ToBoolean conversion of the result.
Node* value = graph()->NewNode(simplified()->ToBoolean(), node);
for (Edge edge : node->use_edges()) {
if (NodeProperties::IsValueEdge(edge) && edge.from() != value) {
edge.UpdateTo(value);
Revisit(edge.from());
}
}
return Changed(node);
}
return NoChange();
}
JSNativeContextSpecialization::InferHasInPrototypeChainResult
JSNativeContextSpecialization::InferHasInPrototypeChain(
Node* receiver, Effect effect, HeapObjectRef prototype) {
ZoneRefSet<Map> receiver_maps;
NodeProperties::InferMapsResult result = NodeProperties::InferMapsUnsafe(
broker(), receiver, effect, &receiver_maps);
if (result == NodeProperties::kNoMaps) return kMayBeInPrototypeChain;
ZoneVector<MapRef> receiver_map_refs(zone());
// Try to determine either that all of the {receiver_maps} have the given
// {prototype} in their chain, or that none do. If we can't tell, return
// kMayBeInPrototypeChain.
bool all = true;
bool none = true;
for (MapRef map : receiver_maps) {
receiver_map_refs.push_back(map);
if (result == NodeProperties::kUnreliableMaps && !map.is_stable()) {
return kMayBeInPrototypeChain;
}
while (true) {
if (IsSpecialReceiverInstanceType(map.instance_type())) {
return kMayBeInPrototypeChain;
}
if (!map.IsJSObjectMap()) {
all = false;
break;
}
HeapObjectRef map_prototype = map.prototype(broker());
if (map_prototype.equals(prototype)) {
none = false;
break;
}
map = map_prototype.map(broker());
// TODO(v8:11457) Support dictionary mode protoypes here.
if (!map.is_stable() || map.is_dictionary_map()) {
return kMayBeInPrototypeChain;
}
if (map.oddball_type(broker()) == OddballType::kNull) {
all = false;
break;
}
}
}
DCHECK_IMPLIES(all, !none);
if (!all && !none) return kMayBeInPrototypeChain;
{
OptionalJSObjectRef last_prototype;
if (all) {
// We don't need to protect the full chain if we found the prototype, we
// can stop at {prototype}. In fact we could stop at the one before
// {prototype} but since we're dealing with multiple receiver maps this
// might be a different object each time, so it's much simpler to include
// {prototype}. That does, however, mean that we must check {prototype}'s
// map stability.
if (!prototype.map(broker()).is_stable()) return kMayBeInPrototypeChain;
last_prototype = prototype.AsJSObject();
}
WhereToStart start = result == NodeProperties::kUnreliableMaps
? kStartAtReceiver
: kStartAtPrototype;
dependencies()->DependOnStablePrototypeChains(receiver_map_refs, start,
last_prototype);
}
DCHECK_EQ(all, !none);
return all ? kIsInPrototypeChain : kIsNotInPrototypeChain;
}
Reduction JSNativeContextSpecialization::ReduceJSHasInPrototypeChain(
Node* node) {
DCHECK_EQ(IrOpcode::kJSHasInPrototypeChain, node->opcode());
Node* value = NodeProperties::GetValueInput(node, 0);
Node* prototype = NodeProperties::GetValueInput(node, 1);
Effect effect{NodeProperties::GetEffectInput(node)};
// Check if we can constant-fold the prototype chain walk
// for the given {value} and the {prototype}.
HeapObjectMatcher m(prototype);
if (m.HasResolvedValue()) {
InferHasInPrototypeChainResult result =
InferHasInPrototypeChain(value, effect, m.Ref(broker()));
if (result != kMayBeInPrototypeChain) {
Node* result_in_chain =
jsgraph()->BooleanConstant(result == kIsInPrototypeChain);
ReplaceWithValue(node, result_in_chain);
return Replace(result_in_chain);
}
}
return NoChange();
}
Reduction JSNativeContextSpecialization::ReduceJSOrdinaryHasInstance(
Node* node) {
DCHECK_EQ(IrOpcode::kJSOrdinaryHasInstance, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
Node* object = NodeProperties::GetValueInput(node, 1);
// Check if the {constructor} is known at compile time.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue()) return NoChange();
if (m.Ref(broker()).IsJSBoundFunction()) {
// OrdinaryHasInstance on bound functions turns into a recursive invocation
// of the instanceof operator again.
JSBoundFunctionRef function = m.Ref(broker()).AsJSBoundFunction();
Node* feedback = jsgraph()->UndefinedConstant();
NodeProperties::ReplaceValueInput(node, object,
JSInstanceOfNode::LeftIndex());
NodeProperties::ReplaceValueInput(
node,
jsgraph()->ConstantNoHole(function.bound_target_function(broker()),
broker()),
JSInstanceOfNode::RightIndex());
node->InsertInput(zone(), JSInstanceOfNode::FeedbackVectorIndex(),
feedback);
NodeProperties::ChangeOp(node, javascript()->InstanceOf(FeedbackSource()));
return Changed(node).FollowedBy(ReduceJSInstanceOf(node));
}
if (m.Ref(broker()).IsJSFunction()) {
// Optimize if we currently know the "prototype" property.
JSFunctionRef function = m.Ref(broker()).AsJSFunction();
// TODO(neis): Remove the has_prototype_slot condition once the broker is
// always enabled.
if (!function.map(broker()).has_prototype_slot() ||
!function.has_instance_prototype(broker()) ||
function.PrototypeRequiresRuntimeLookup(broker())) {
return NoChange();
}
HeapObjectRef prototype =
dependencies()->DependOnPrototypeProperty(function);
Node* prototype_constant = jsgraph()->ConstantNoHole(prototype, broker());
// Lower the {node} to JSHasInPrototypeChain.
NodeProperties::ReplaceValueInput(node, object, 0);
NodeProperties::ReplaceValueInput(node, prototype_constant, 1);
NodeProperties::ChangeOp(node, javascript()->HasInPrototypeChain());
return Changed(node).FollowedBy(ReduceJSHasInPrototypeChain(node));
}
return NoChange();
}
// ES section #sec-promise-resolve
Reduction JSNativeContextSpecialization::ReduceJSPromiseResolve(Node* node) {
DCHECK_EQ(IrOpcode::kJSPromiseResolve, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
Node* value = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
FrameState frame_state{NodeProperties::GetFrameStateInput(node)};
Effect effect{NodeProperties::GetEffectInput(node)};
Control control{NodeProperties::GetControlInput(node)};
// Check if the {constructor} is the %Promise% function.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue() ||
!m.Ref(broker()).equals(native_context().promise_function(broker()))) {
return NoChange();
}
// Only optimize if {value} cannot be a JSPromise.
MapInference inference(broker(), value, effect);
if (!inference.HaveMaps() ||
inference.AnyOfInstanceTypesAre(JS_PROMISE_TYPE)) {
return NoChange();
}
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();