/
simplified-lowering.cc
4727 lines (4379 loc) Β· 188 KB
/
simplified-lowering.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 2014 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/simplified-lowering.h"
#include <limits>
#include "include/v8-fast-api-calls.h"
#include "src/base/bits.h"
#include "src/base/small-vector.h"
#include "src/codegen/code-factory.h"
#include "src/codegen/machine-type.h"
#include "src/codegen/tick-counter.h"
#include "src/compiler/access-builder.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/compiler-source-position-table.h"
#include "src/compiler/diamond.h"
#include "src/compiler/linkage.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-origin-table.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/operation-typer.h"
#include "src/compiler/operator-properties.h"
#include "src/compiler/representation-change.h"
#include "src/compiler/simplified-operator.h"
#include "src/compiler/type-cache.h"
#include "src/numbers/conversions-inl.h"
#include "src/objects/objects.h"
#include "src/utils/address-map.h"
namespace v8 {
namespace internal {
namespace compiler {
// Macro for outputting trace information from representation inference.
#define TRACE(...) \
do { \
if (FLAG_trace_representation) PrintF(__VA_ARGS__); \
} while (false)
// Representation selection and lowering of {Simplified} operators to machine
// operators are interwined. We use a fixpoint calculation to compute both the
// output representation and the best possible lowering for {Simplified} nodes.
// Representation change insertion ensures that all values are in the correct
// machine representation after this phase, as dictated by the machine
// operators themselves.
enum Phase {
// 1.) PROPAGATE: Traverse the graph from the end, pushing usage information
// backwards from uses to definitions, around cycles in phis, according
// to local rules for each operator.
// During this phase, the usage information for a node determines the best
// possible lowering for each operator so far, and that in turn determines
// the output representation.
// Therefore, to be correct, this phase must iterate to a fixpoint before
// the next phase can begin.
PROPAGATE,
// 2.) RETYPE: Propagate types from type feedback forwards.
RETYPE,
// 3.) LOWER: perform lowering for all {Simplified} nodes by replacing some
// operators for some nodes, expanding some nodes to multiple nodes, or
// removing some (redundant) nodes.
// During this phase, use the {RepresentationChanger} to insert
// representation changes between uses that demand a particular
// representation and nodes that produce a different representation.
LOWER
};
namespace {
MachineRepresentation MachineRepresentationFromArrayType(
ExternalArrayType array_type) {
switch (array_type) {
case kExternalUint8Array:
case kExternalUint8ClampedArray:
case kExternalInt8Array:
return MachineRepresentation::kWord8;
case kExternalUint16Array:
case kExternalInt16Array:
return MachineRepresentation::kWord16;
case kExternalUint32Array:
case kExternalInt32Array:
return MachineRepresentation::kWord32;
case kExternalFloat32Array:
return MachineRepresentation::kFloat32;
case kExternalFloat64Array:
return MachineRepresentation::kFloat64;
case kExternalBigInt64Array:
case kExternalBigUint64Array:
UNIMPLEMENTED();
}
UNREACHABLE();
}
UseInfo CheckedUseInfoAsWord32FromHint(
NumberOperationHint hint, const FeedbackSource& feedback = FeedbackSource(),
IdentifyZeros identify_zeros = kDistinguishZeros) {
switch (hint) {
case NumberOperationHint::kSignedSmall:
case NumberOperationHint::kSignedSmallInputs:
return UseInfo::CheckedSignedSmallAsWord32(identify_zeros, feedback);
case NumberOperationHint::kSigned32:
return UseInfo::CheckedSigned32AsWord32(identify_zeros, feedback);
case NumberOperationHint::kNumber:
return UseInfo::CheckedNumberAsWord32(feedback);
case NumberOperationHint::kNumberOrOddball:
return UseInfo::CheckedNumberOrOddballAsWord32(feedback);
}
UNREACHABLE();
}
UseInfo CheckedUseInfoAsFloat64FromHint(
NumberOperationHint hint, const FeedbackSource& feedback,
IdentifyZeros identify_zeros = kDistinguishZeros) {
switch (hint) {
case NumberOperationHint::kSignedSmall:
case NumberOperationHint::kSignedSmallInputs:
case NumberOperationHint::kSigned32:
// Not used currently.
UNREACHABLE();
case NumberOperationHint::kNumber:
return UseInfo::CheckedNumberAsFloat64(identify_zeros, feedback);
case NumberOperationHint::kNumberOrOddball:
return UseInfo::CheckedNumberOrOddballAsFloat64(identify_zeros, feedback);
}
UNREACHABLE();
}
UseInfo TruncatingUseInfoFromRepresentation(MachineRepresentation rep) {
switch (rep) {
case MachineRepresentation::kTaggedSigned:
return UseInfo::TaggedSigned();
case MachineRepresentation::kTaggedPointer:
case MachineRepresentation::kTagged:
return UseInfo::AnyTagged();
case MachineRepresentation::kFloat64:
return UseInfo::TruncatingFloat64();
case MachineRepresentation::kFloat32:
return UseInfo::Float32();
case MachineRepresentation::kWord8:
case MachineRepresentation::kWord16:
case MachineRepresentation::kWord32:
return UseInfo::TruncatingWord32();
case MachineRepresentation::kWord64:
return UseInfo::Word64();
case MachineRepresentation::kBit:
return UseInfo::Bool();
case MachineRepresentation::kCompressedPointer:
case MachineRepresentation::kCompressed:
case MachineRepresentation::kSimd128:
case MachineRepresentation::kNone:
break;
}
UNREACHABLE();
}
UseInfo UseInfoForBasePointer(const FieldAccess& access) {
return access.tag() != 0 ? UseInfo::AnyTagged() : UseInfo::Word();
}
UseInfo UseInfoForBasePointer(const ElementAccess& access) {
return access.tag() != 0 ? UseInfo::AnyTagged() : UseInfo::Word();
}
void ReplaceEffectControlUses(Node* node, Node* effect, Node* control) {
for (Edge edge : node->use_edges()) {
if (NodeProperties::IsControlEdge(edge)) {
edge.UpdateTo(control);
} else if (NodeProperties::IsEffectEdge(edge)) {
edge.UpdateTo(effect);
} else {
DCHECK(NodeProperties::IsValueEdge(edge) ||
NodeProperties::IsContextEdge(edge));
}
}
}
bool CanOverflowSigned32(const Operator* op, Type left, Type right,
TypeCache const* type_cache, Zone* type_zone) {
// We assume the inputs are checked Signed32 (or known statically to be
// Signed32). Technically, the inputs could also be minus zero, which we treat
// as 0 for the purpose of this function.
if (left.Maybe(Type::MinusZero())) {
left = Type::Union(left, type_cache->kSingletonZero, type_zone);
}
if (right.Maybe(Type::MinusZero())) {
right = Type::Union(right, type_cache->kSingletonZero, type_zone);
}
left = Type::Intersect(left, Type::Signed32(), type_zone);
right = Type::Intersect(right, Type::Signed32(), type_zone);
if (left.IsNone() || right.IsNone()) return false;
switch (op->opcode()) {
case IrOpcode::kSpeculativeSafeIntegerAdd:
return (left.Max() + right.Max() > kMaxInt) ||
(left.Min() + right.Min() < kMinInt);
case IrOpcode::kSpeculativeSafeIntegerSubtract:
return (left.Max() - right.Min() > kMaxInt) ||
(left.Min() - right.Max() < kMinInt);
default:
UNREACHABLE();
}
return true;
}
bool IsSomePositiveOrderedNumber(Type type) {
return type.Is(Type::OrderedNumber()) && !type.IsNone() && type.Min() > 0;
}
} // namespace
#ifdef DEBUG
// Helpers for monotonicity checking.
class InputUseInfos {
public:
explicit InputUseInfos(Zone* zone) : input_use_infos_(zone) {}
void SetAndCheckInput(Node* node, int index, UseInfo use_info) {
if (input_use_infos_.empty()) {
input_use_infos_.resize(node->InputCount(), UseInfo::None());
}
// Check that the new use informatin is a super-type of the old
// one.
DCHECK(IsUseLessGeneral(input_use_infos_[index], use_info));
input_use_infos_[index] = use_info;
}
private:
ZoneVector<UseInfo> input_use_infos_;
static bool IsUseLessGeneral(UseInfo use1, UseInfo use2) {
return use1.truncation().IsLessGeneralThan(use2.truncation());
}
};
#endif // DEBUG
class RepresentationSelector {
public:
// Information for each node tracked during the fixpoint.
class NodeInfo final {
public:
// Adds new use to the node. Returns true if something has changed
// and the node has to be requeued.
bool AddUse(UseInfo info) {
Truncation old_truncation = truncation_;
truncation_ = Truncation::Generalize(truncation_, info.truncation());
return truncation_ != old_truncation;
}
void set_queued() { state_ = kQueued; }
void set_visited() { state_ = kVisited; }
void set_pushed() { state_ = kPushed; }
void reset_state() { state_ = kUnvisited; }
bool visited() const { return state_ == kVisited; }
bool queued() const { return state_ == kQueued; }
bool pushed() const { return state_ == kPushed; }
bool unvisited() const { return state_ == kUnvisited; }
Truncation truncation() const { return truncation_; }
void set_output(MachineRepresentation output) { representation_ = output; }
MachineRepresentation representation() const { return representation_; }
// Helpers for feedback typing.
void set_feedback_type(Type type) { feedback_type_ = type; }
Type feedback_type() const { return feedback_type_; }
void set_weakened() { weakened_ = true; }
bool weakened() const { return weakened_; }
void set_restriction_type(Type type) { restriction_type_ = type; }
Type restriction_type() const { return restriction_type_; }
private:
enum State : uint8_t { kUnvisited, kPushed, kVisited, kQueued };
State state_ = kUnvisited;
MachineRepresentation representation_ =
MachineRepresentation::kNone; // Output representation.
Truncation truncation_ = Truncation::None(); // Information about uses.
Type restriction_type_ = Type::Any();
Type feedback_type_;
bool weakened_ = false;
};
RepresentationSelector(JSGraph* jsgraph, JSHeapBroker* broker, Zone* zone,
RepresentationChanger* changer,
SourcePositionTable* source_positions,
NodeOriginTable* node_origins,
TickCounter* tick_counter)
: jsgraph_(jsgraph),
zone_(zone),
might_need_revisit_(zone),
count_(jsgraph->graph()->NodeCount()),
info_(count_, zone),
#ifdef DEBUG
node_input_use_infos_(count_, InputUseInfos(zone), zone),
#endif
nodes_(zone),
replacements_(zone),
changer_(changer),
queue_(zone),
typing_stack_(zone),
source_positions_(source_positions),
node_origins_(node_origins),
type_cache_(TypeCache::Get()),
op_typer_(broker, graph_zone()),
tick_counter_(tick_counter) {
}
// Forward propagation of types from type feedback.
void RunTypePropagationPhase() {
// Run type propagation.
TRACE("--{Type propagation phase}--\n");
ResetNodeInfoState();
DCHECK(typing_stack_.empty());
typing_stack_.push({graph()->end(), 0});
GetInfo(graph()->end())->set_pushed();
while (!typing_stack_.empty()) {
NodeState& current = typing_stack_.top();
// If there is an unvisited input, push it and continue.
bool pushed_unvisited = false;
while (current.input_index < current.node->InputCount()) {
Node* input = current.node->InputAt(current.input_index);
NodeInfo* input_info = GetInfo(input);
current.input_index++;
if (input_info->unvisited()) {
input_info->set_pushed();
typing_stack_.push({input, 0});
pushed_unvisited = true;
break;
} else if (input_info->pushed()) {
// If we had already pushed (and not visited) an input, it means that
// the current node will be visited before one of its inputs. If this
// happens, the current node might need to be revisited.
MarkAsPossibleRevisit(current.node, input);
}
}
if (pushed_unvisited) continue;
// Process the top of the stack.
Node* node = current.node;
typing_stack_.pop();
NodeInfo* info = GetInfo(node);
info->set_visited();
bool updated = UpdateFeedbackType(node);
TRACE(" visit #%d: %s\n", node->id(), node->op()->mnemonic());
VisitNode<RETYPE>(node, info->truncation(), nullptr);
TRACE(" ==> output ");
PrintOutputInfo(info);
TRACE("\n");
if (updated) {
auto it = might_need_revisit_.find(node);
if (it == might_need_revisit_.end()) continue;
for (Node* const user : it->second) {
if (GetInfo(user)->visited()) {
TRACE(" QUEUEING #%d: %s\n", user->id(), user->op()->mnemonic());
GetInfo(user)->set_queued();
queue_.push(user);
}
}
}
}
// Process the revisit queue.
while (!queue_.empty()) {
Node* node = queue_.front();
queue_.pop();
NodeInfo* info = GetInfo(node);
info->set_visited();
bool updated = UpdateFeedbackType(node);
TRACE(" revisit #%d: %s\n", node->id(), node->op()->mnemonic());
VisitNode<RETYPE>(node, info->truncation(), nullptr);
TRACE(" ==> output ");
PrintOutputInfo(info);
TRACE("\n");
if (updated) {
// Here we need to check all uses since we can't easily know which nodes
// will need to be revisited due to having an input which was a
// revisited node.
for (Node* const user : node->uses()) {
if (GetInfo(user)->visited()) {
TRACE(" QUEUEING #%d: %s\n", user->id(), user->op()->mnemonic());
GetInfo(user)->set_queued();
queue_.push(user);
}
}
}
}
}
void ResetNodeInfoState() {
// Clean up for the next phase.
for (NodeInfo& info : info_) {
info.reset_state();
}
}
Type TypeOf(Node* node) {
Type type = GetInfo(node)->feedback_type();
return type.IsInvalid() ? NodeProperties::GetType(node) : type;
}
Type FeedbackTypeOf(Node* node) {
Type type = GetInfo(node)->feedback_type();
return type.IsInvalid() ? Type::None() : type;
}
Type TypePhi(Node* node) {
int arity = node->op()->ValueInputCount();
Type type = FeedbackTypeOf(node->InputAt(0));
for (int i = 1; i < arity; ++i) {
type = op_typer_.Merge(type, FeedbackTypeOf(node->InputAt(i)));
}
return type;
}
Type TypeSelect(Node* node) {
return op_typer_.Merge(FeedbackTypeOf(node->InputAt(1)),
FeedbackTypeOf(node->InputAt(2)));
}
bool UpdateFeedbackType(Node* node) {
if (node->op()->ValueOutputCount() == 0) return false;
NodeInfo* info = GetInfo(node);
Type type = info->feedback_type();
Type new_type = type;
// For any non-phi node just wait until we get all inputs typed. We only
// allow untyped inputs for phi nodes because phis are the only places
// where cycles need to be broken.
if (node->opcode() != IrOpcode::kPhi) {
for (int i = 0; i < node->op()->ValueInputCount(); i++) {
if (GetInfo(node->InputAt(i))->feedback_type().IsInvalid()) {
return false;
}
}
}
// We preload these values here to avoid increasing the binary size too
// much, which happens if we inline the calls into the macros below.
Type input0_type;
if (node->InputCount() > 0) input0_type = FeedbackTypeOf(node->InputAt(0));
Type input1_type;
if (node->InputCount() > 1) input1_type = FeedbackTypeOf(node->InputAt(1));
switch (node->opcode()) {
#define DECLARE_CASE(Name) \
case IrOpcode::k##Name: { \
new_type = op_typer_.Name(input0_type, input1_type); \
break; \
}
SIMPLIFIED_NUMBER_BINOP_LIST(DECLARE_CASE)
DECLARE_CASE(SameValue)
#undef DECLARE_CASE
#define DECLARE_CASE(Name) \
case IrOpcode::k##Name: { \
new_type = Type::Intersect(op_typer_.Name(input0_type, input1_type), \
info->restriction_type(), graph_zone()); \
break; \
}
SIMPLIFIED_SPECULATIVE_NUMBER_BINOP_LIST(DECLARE_CASE)
SIMPLIFIED_SPECULATIVE_BIGINT_BINOP_LIST(DECLARE_CASE)
#undef DECLARE_CASE
#define DECLARE_CASE(Name) \
case IrOpcode::k##Name: { \
new_type = op_typer_.Name(input0_type); \
break; \
}
SIMPLIFIED_NUMBER_UNOP_LIST(DECLARE_CASE)
#undef DECLARE_CASE
#define DECLARE_CASE(Name) \
case IrOpcode::k##Name: { \
new_type = Type::Intersect(op_typer_.Name(input0_type), \
info->restriction_type(), graph_zone()); \
break; \
}
SIMPLIFIED_SPECULATIVE_NUMBER_UNOP_LIST(DECLARE_CASE)
#undef DECLARE_CASE
case IrOpcode::kConvertReceiver:
new_type = op_typer_.ConvertReceiver(input0_type);
break;
case IrOpcode::kPlainPrimitiveToNumber:
new_type = op_typer_.ToNumber(input0_type);
break;
case IrOpcode::kCheckBounds:
new_type =
Type::Intersect(op_typer_.CheckBounds(input0_type, input1_type),
info->restriction_type(), graph_zone());
break;
case IrOpcode::kCheckFloat64Hole:
new_type = Type::Intersect(op_typer_.CheckFloat64Hole(input0_type),
info->restriction_type(), graph_zone());
break;
case IrOpcode::kCheckNumber:
new_type = Type::Intersect(op_typer_.CheckNumber(input0_type),
info->restriction_type(), graph_zone());
break;
case IrOpcode::kPhi: {
new_type = TypePhi(node);
if (!type.IsInvalid()) {
new_type = Weaken(node, type, new_type);
}
break;
}
case IrOpcode::kConvertTaggedHoleToUndefined:
new_type = op_typer_.ConvertTaggedHoleToUndefined(
FeedbackTypeOf(node->InputAt(0)));
break;
case IrOpcode::kTypeGuard: {
new_type = op_typer_.TypeTypeGuard(node->op(),
FeedbackTypeOf(node->InputAt(0)));
break;
}
case IrOpcode::kSelect: {
new_type = TypeSelect(node);
break;
}
default:
// Shortcut for operations that we do not handle.
if (type.IsInvalid()) {
GetInfo(node)->set_feedback_type(NodeProperties::GetType(node));
return true;
}
return false;
}
// We need to guarantee that the feedback type is a subtype of the upper
// bound. Naively that should hold, but weakening can actually produce
// a bigger type if we are unlucky with ordering of phi typing. To be
// really sure, just intersect the upper bound with the feedback type.
new_type = Type::Intersect(GetUpperBound(node), new_type, graph_zone());
if (!type.IsInvalid() && new_type.Is(type)) return false;
GetInfo(node)->set_feedback_type(new_type);
if (FLAG_trace_representation) {
PrintNodeFeedbackType(node);
}
return true;
}
void PrintNodeFeedbackType(Node* n) {
StdoutStream os;
os << "#" << n->id() << ":" << *n->op() << "(";
int j = 0;
for (Node* const i : n->inputs()) {
if (j++ > 0) os << ", ";
os << "#" << i->id() << ":" << i->op()->mnemonic();
}
os << ")";
if (NodeProperties::IsTyped(n)) {
Type static_type = NodeProperties::GetType(n);
os << " [Static type: " << static_type;
Type feedback_type = GetInfo(n)->feedback_type();
if (!feedback_type.IsInvalid() && feedback_type != static_type) {
os << ", Feedback type: " << feedback_type;
}
os << "]";
}
os << std::endl;
}
Type Weaken(Node* node, Type previous_type, Type current_type) {
// If the types have nothing to do with integers, return the types.
Type const integer = type_cache_->kInteger;
if (!previous_type.Maybe(integer)) {
return current_type;
}
DCHECK(current_type.Maybe(integer));
Type current_integer = Type::Intersect(current_type, integer, graph_zone());
DCHECK(!current_integer.IsNone());
Type previous_integer =
Type::Intersect(previous_type, integer, graph_zone());
DCHECK(!previous_integer.IsNone());
// Once we start weakening a node, we should always weaken.
if (!GetInfo(node)->weakened()) {
// Only weaken if there is range involved; we should converge quickly
// for all other types (the exception is a union of many constants,
// but we currently do not increase the number of constants in unions).
Type previous = previous_integer.GetRange();
Type current = current_integer.GetRange();
if (current.IsInvalid() || previous.IsInvalid()) {
return current_type;
}
// Range is involved => we are weakening.
GetInfo(node)->set_weakened();
}
return Type::Union(current_type,
op_typer_.WeakenRange(previous_integer, current_integer),
graph_zone());
}
// Backward propagation of truncations.
void RunTruncationPropagationPhase() {
// Run propagation phase to a fixpoint.
TRACE("--{Propagation phase}--\n");
EnqueueInitial(jsgraph_->graph()->end());
// Process nodes from the queue until it is empty.
while (!queue_.empty()) {
Node* node = queue_.front();
NodeInfo* info = GetInfo(node);
queue_.pop();
info->set_visited();
TRACE(" visit #%d: %s (trunc: %s)\n", node->id(), node->op()->mnemonic(),
info->truncation().description());
VisitNode<PROPAGATE>(node, info->truncation(), nullptr);
}
}
void Run(SimplifiedLowering* lowering) {
RunTruncationPropagationPhase();
RunTypePropagationPhase();
// Run lowering and change insertion phase.
TRACE("--{Simplified lowering phase}--\n");
// Process nodes from the collected {nodes_} vector.
for (NodeVector::iterator i = nodes_.begin(); i != nodes_.end(); ++i) {
Node* node = *i;
NodeInfo* info = GetInfo(node);
TRACE(" visit #%d: %s\n", node->id(), node->op()->mnemonic());
// Reuse {VisitNode()} so the representation rules are in one place.
SourcePositionTable::Scope scope(
source_positions_, source_positions_->GetSourcePosition(node));
NodeOriginTable::Scope origin_scope(node_origins_, "simplified lowering",
node);
VisitNode<LOWER>(node, info->truncation(), lowering);
}
// Perform the final replacements.
for (NodeVector::iterator i = replacements_.begin();
i != replacements_.end(); ++i) {
Node* node = *i;
Node* replacement = *(++i);
node->ReplaceUses(replacement);
node->Kill();
// We also need to replace the node in the rest of the vector.
for (NodeVector::iterator j = i + 1; j != replacements_.end(); ++j) {
++j;
if (*j == node) *j = replacement;
}
}
}
void EnqueueInitial(Node* node) {
NodeInfo* info = GetInfo(node);
info->set_queued();
nodes_.push_back(node);
queue_.push(node);
}
// Just assert for Retype and Lower. Propagate specialized below.
template <Phase T>
void EnqueueInput(Node* use_node, int index,
UseInfo use_info = UseInfo::None()) {
static_assert(retype<T>() || lower<T>(),
"This version of ProcessRemainingInputs has to be called in "
"the Retype or Lower phase.");
}
template <Phase T>
static constexpr bool propagate() {
return T == PROPAGATE;
}
template <Phase T>
static constexpr bool retype() {
return T == RETYPE;
}
template <Phase T>
static constexpr bool lower() {
return T == LOWER;
}
template <Phase T>
void SetOutput(Node* node, MachineRepresentation representation,
Type restriction_type = Type::Any());
Type GetUpperBound(Node* node) { return NodeProperties::GetType(node); }
bool InputCannotBe(Node* node, Type type) {
DCHECK_EQ(1, node->op()->ValueInputCount());
return !GetUpperBound(node->InputAt(0)).Maybe(type);
}
bool InputIs(Node* node, Type type) {
DCHECK_EQ(1, node->op()->ValueInputCount());
return GetUpperBound(node->InputAt(0)).Is(type);
}
bool BothInputsAreSigned32(Node* node) {
return BothInputsAre(node, Type::Signed32());
}
bool BothInputsAreUnsigned32(Node* node) {
return BothInputsAre(node, Type::Unsigned32());
}
bool BothInputsAre(Node* node, Type type) {
DCHECK_EQ(2, node->op()->ValueInputCount());
return GetUpperBound(node->InputAt(0)).Is(type) &&
GetUpperBound(node->InputAt(1)).Is(type);
}
bool IsNodeRepresentationTagged(Node* node) {
MachineRepresentation representation = GetInfo(node)->representation();
return IsAnyTagged(representation);
}
bool OneInputCannotBe(Node* node, Type type) {
DCHECK_EQ(2, node->op()->ValueInputCount());
return !GetUpperBound(node->InputAt(0)).Maybe(type) ||
!GetUpperBound(node->InputAt(1)).Maybe(type);
}
void ChangeToDeadValue(Node* node, Node* effect, Node* control) {
DCHECK(TypeOf(node).IsNone());
// If the node is unreachable, insert an Unreachable node and mark the
// value dead.
// TODO(jarin,tebbi) Find a way to unify/merge this insertion with
// InsertUnreachableIfNecessary.
Node* unreachable = effect =
graph()->NewNode(jsgraph_->common()->Unreachable(), effect, control);
const Operator* dead_value =
jsgraph_->common()->DeadValue(GetInfo(node)->representation());
node->ReplaceInput(0, unreachable);
node->TrimInputCount(dead_value->ValueInputCount());
ReplaceEffectControlUses(node, effect, control);
NodeProperties::ChangeOp(node, dead_value);
}
void ChangeToPureOp(Node* node, const Operator* new_op) {
DCHECK(new_op->HasProperty(Operator::kPure));
DCHECK_EQ(new_op->ValueInputCount(), node->op()->ValueInputCount());
if (node->op()->EffectInputCount() > 0) {
DCHECK_LT(0, node->op()->ControlInputCount());
Node* control = NodeProperties::GetControlInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
if (TypeOf(node).IsNone()) {
ChangeToDeadValue(node, effect, control);
return;
}
// Rewire the effect and control chains.
node->TrimInputCount(new_op->ValueInputCount());
ReplaceEffectControlUses(node, effect, control);
} else {
DCHECK_EQ(0, node->op()->ControlInputCount());
}
NodeProperties::ChangeOp(node, new_op);
}
void ChangeUnaryToPureBinaryOp(Node* node, const Operator* new_op,
int new_input_index, Node* new_input) {
DCHECK(new_op->HasProperty(Operator::kPure));
DCHECK_EQ(new_op->ValueInputCount(), 2);
DCHECK_EQ(node->op()->ValueInputCount(), 1);
DCHECK_LE(0, new_input_index);
DCHECK_LE(new_input_index, 1);
if (node->op()->EffectInputCount() > 0) {
DCHECK_LT(0, node->op()->ControlInputCount());
Node* control = NodeProperties::GetControlInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
if (TypeOf(node).IsNone()) {
ChangeToDeadValue(node, effect, control);
return;
}
node->TrimInputCount(node->op()->ValueInputCount());
ReplaceEffectControlUses(node, effect, control);
} else {
DCHECK_EQ(0, node->op()->ControlInputCount());
}
node->InsertInput(jsgraph_->zone(), new_input_index, new_input);
NodeProperties::ChangeOp(node, new_op);
}
// Converts input {index} of {node} according to given UseInfo {use},
// assuming the type of the input is {input_type}. If {input_type} is null,
// it takes the input from the input node {TypeOf(node->InputAt(index))}.
void ConvertInput(Node* node, int index, UseInfo use,
Type input_type = Type::Invalid()) {
Node* input = node->InputAt(index);
// In the change phase, insert a change before the use if necessary.
if (use.representation() == MachineRepresentation::kNone)
return; // No input requirement on the use.
DCHECK_NOT_NULL(input);
NodeInfo* input_info = GetInfo(input);
MachineRepresentation input_rep = input_info->representation();
if (input_rep != use.representation() ||
use.type_check() != TypeCheckKind::kNone) {
// Output representation doesn't match usage.
TRACE(" change: #%d:%s(@%d #%d:%s) ", node->id(), node->op()->mnemonic(),
index, input->id(), input->op()->mnemonic());
TRACE(" from ");
PrintOutputInfo(input_info);
TRACE(" to ");
PrintUseInfo(use);
TRACE("\n");
if (input_type.IsInvalid()) {
input_type = TypeOf(input);
}
Node* n = changer_->GetRepresentationFor(
input, input_info->representation(), input_type, node, use);
node->ReplaceInput(index, n);
}
}
template <Phase T>
void ProcessInput(Node* node, int index, UseInfo use);
// Just assert for Retype and Lower. Propagate specialized below.
template <Phase T>
void ProcessRemainingInputs(Node* node, int index) {
static_assert(retype<T>() || lower<T>(),
"This version of ProcessRemainingInputs has to be called in "
"the Retype or Lower phase.");
DCHECK_GE(index, NodeProperties::PastValueIndex(node));
DCHECK_GE(index, NodeProperties::PastContextIndex(node));
}
// Marks node as a possible revisit since it is a use of input that will be
// visited before input is visited.
void MarkAsPossibleRevisit(Node* node, Node* input) {
auto it = might_need_revisit_.find(input);
if (it == might_need_revisit_.end()) {
it = might_need_revisit_.insert({input, ZoneVector<Node*>(zone())}).first;
}
it->second.push_back(node);
TRACE(" Marking #%d: %s as needing revisit due to #%d: %s\n", node->id(),
node->op()->mnemonic(), input->id(), input->op()->mnemonic());
}
// Just assert for Retype. Propagate and Lower specialized below.
template <Phase T>
void VisitInputs(Node* node) {
static_assert(
retype<T>(),
"This version of VisitInputs has to be called in the Retype phase.");
}
template <Phase T>
void VisitReturn(Node* node) {
int tagged_limit = node->op()->ValueInputCount() +
OperatorProperties::GetContextInputCount(node->op()) +
OperatorProperties::GetFrameStateInputCount(node->op());
// Visit integer slot count to pop
ProcessInput<T>(node, 0, UseInfo::TruncatingWord32());
// Visit value, context and frame state inputs as tagged.
for (int i = 1; i < tagged_limit; i++) {
ProcessInput<T>(node, i, UseInfo::AnyTagged());
}
// Only enqueue other inputs (effects, control).
for (int i = tagged_limit; i < node->InputCount(); i++) {
EnqueueInput<T>(node, i);
}
}
// Helper for an unused node.
template <Phase T>
void VisitUnused(Node* node) {
int value_count = node->op()->ValueInputCount() +
OperatorProperties::GetContextInputCount(node->op()) +
OperatorProperties::GetFrameStateInputCount(node->op());
for (int i = 0; i < value_count; i++) {
ProcessInput<T>(node, i, UseInfo::None());
}
ProcessRemainingInputs<T>(node, value_count);
if (lower<T>()) Kill(node);
}
// Helper for no-op node.
template <Phase T>
void VisitNoop(Node* node, Truncation truncation) {
if (truncation.IsUnused()) return VisitUnused<T>(node);
MachineRepresentation representation =
GetOutputInfoForPhi(node, TypeOf(node), truncation);
VisitUnop<T>(node, UseInfo(representation, truncation), representation);
if (lower<T>()) DeferReplacement(node, node->InputAt(0));
}
// Helper for binops of the R x L -> O variety.
template <Phase T>
void VisitBinop(Node* node, UseInfo left_use, UseInfo right_use,
MachineRepresentation output,
Type restriction_type = Type::Any()) {
DCHECK_EQ(2, node->op()->ValueInputCount());
ProcessInput<T>(node, 0, left_use);
ProcessInput<T>(node, 1, right_use);
for (int i = 2; i < node->InputCount(); i++) {
EnqueueInput<T>(node, i);
}
SetOutput<T>(node, output, restriction_type);
}
// Helper for binops of the I x I -> O variety.
template <Phase T>
void VisitBinop(Node* node, UseInfo input_use, MachineRepresentation output,
Type restriction_type = Type::Any()) {
VisitBinop<T>(node, input_use, input_use, output, restriction_type);
}
template <Phase T>
void VisitSpeculativeInt32Binop(Node* node) {
DCHECK_EQ(2, node->op()->ValueInputCount());
if (BothInputsAre(node, Type::NumberOrOddball())) {
return VisitBinop<T>(node, UseInfo::TruncatingWord32(),
MachineRepresentation::kWord32);
}
NumberOperationHint hint = NumberOperationHintOf(node->op());
return VisitBinop<T>(node, CheckedUseInfoAsWord32FromHint(hint),
MachineRepresentation::kWord32);
}
// Helper for unops of the I -> O variety.
template <Phase T>
void VisitUnop(Node* node, UseInfo input_use, MachineRepresentation output,
Type restriction_type = Type::Any()) {
DCHECK_EQ(1, node->op()->ValueInputCount());
ProcessInput<T>(node, 0, input_use);
ProcessRemainingInputs<T>(node, 1);
SetOutput<T>(node, output, restriction_type);
}
// Helper for leaf nodes.
template <Phase T>
void VisitLeaf(Node* node, MachineRepresentation output) {
DCHECK_EQ(0, node->InputCount());
SetOutput<T>(node, output);
}
// Helpers for specific types of binops.
template <Phase T>
void VisitFloat64Binop(Node* node) {
VisitBinop<T>(node, UseInfo::TruncatingFloat64(),
MachineRepresentation::kFloat64);
}
template <Phase T>
void VisitInt64Binop(Node* node) {
VisitBinop<T>(node, UseInfo::Word64(), MachineRepresentation::kWord64);
}
template <Phase T>
void VisitWord32TruncatingBinop(Node* node) {
VisitBinop<T>(node, UseInfo::TruncatingWord32(),
MachineRepresentation::kWord32);
}
// Infer representation for phi-like nodes.
// The {node} parameter is only used to decide on the int64 representation.
// Once the type system supports an external pointer type, the {node}
// parameter can be removed.
MachineRepresentation GetOutputInfoForPhi(Node* node, Type type,
Truncation use) {
// Compute the representation.
if (type.Is(Type::None())) {
return MachineRepresentation::kNone;
} else if (type.Is(Type::Signed32()) || type.Is(Type::Unsigned32())) {
return MachineRepresentation::kWord32;
} else if (type.Is(Type::NumberOrOddball()) && use.IsUsedAsWord32()) {
return MachineRepresentation::kWord32;
} else if (type.Is(Type::Boolean())) {
return MachineRepresentation::kBit;
} else if (type.Is(Type::NumberOrOddball()) &&
use.TruncatesOddballAndBigIntToNumber()) {
return MachineRepresentation::kFloat64;
} else if (type.Is(Type::Union(Type::SignedSmall(), Type::NaN(), zone()))) {
// TODO(turbofan): For Phis that return either NaN or some Smi, it's
// beneficial to not go all the way to double, unless the uses are
// double uses. For tagging that just means some potentially expensive
// allocation code; we might want to do the same for -0 as well?
return MachineRepresentation::kTagged;
} else if (type.Is(Type::Number())) {
return MachineRepresentation::kFloat64;
} else if (type.Is(Type::BigInt()) && use.IsUsedAsWord64()) {
return MachineRepresentation::kWord64;
} else if (type.Is(Type::ExternalPointer()) ||
type.Is(Type::SandboxedExternalPointer())) {