summaryrefslogtreecommitdiff
path: root/deps/v8/src/maglev/maglev-graph-builder.h
blob: 26d7a4fa1a56013efed36376cdebb0b99a1393c3 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
// Copyright 2022 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.

#ifndef V8_MAGLEV_MAGLEV_GRAPH_BUILDER_H_
#define V8_MAGLEV_MAGLEV_GRAPH_BUILDER_H_

#include <cmath>
#include <iomanip>
#include <map>
#include <type_traits>

#include "src/base/logging.h"
#include "src/base/optional.h"
#include "src/codegen/source-position-table.h"
#include "src/common/globals.h"
#include "src/compiler/bytecode-analysis.h"
#include "src/compiler/bytecode-liveness-map.h"
#include "src/compiler/heap-refs.h"
#include "src/compiler/js-heap-broker.h"
#include "src/compiler/processed-feedback.h"
#include "src/deoptimizer/deoptimize-reason.h"
#include "src/flags/flags.h"
#include "src/interpreter/bytecode-array-iterator.h"
#include "src/interpreter/bytecode-decoder.h"
#include "src/interpreter/bytecode-register.h"
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter-intrinsics.h"
#include "src/maglev/maglev-graph-labeller.h"
#include "src/maglev/maglev-graph-printer.h"
#include "src/maglev/maglev-graph.h"
#include "src/maglev/maglev-ir.h"
#include "src/utils/memcopy.h"

namespace v8 {
namespace internal {
namespace maglev {

class MaglevGraphBuilder {
 public:
  explicit MaglevGraphBuilder(LocalIsolate* local_isolate,
                              MaglevCompilationUnit* compilation_unit,
                              Graph* graph,
                              MaglevGraphBuilder* parent = nullptr);

  void Build() {
    DCHECK(!is_inline());

    StartPrologue();
    for (int i = 0; i < parameter_count(); i++) {
      // TODO(v8:7700): Consider creating InitialValue nodes lazily.
      InitialValue* v = AddNewNode<InitialValue>(
          {}, interpreter::Register::FromParameterIndex(i));
      DCHECK_EQ(graph()->parameters().size(), static_cast<size_t>(i));
      graph()->parameters().push_back(v);
      SetArgument(i, v);
    }
    BuildRegisterFrameInitialization();
    BuildMergeStates();
    EndPrologue();
    BuildBody();
  }

  void StartPrologue();
  void SetArgument(int i, ValueNode* value);
  ValueNode* GetTaggedArgument(int i);
  void BuildRegisterFrameInitialization();
  void BuildMergeStates();
  BasicBlock* EndPrologue();

  void BuildBody() {
    for (iterator_.Reset(); !iterator_.done(); iterator_.Advance()) {
      local_isolate_->heap()->Safepoint();
      VisitSingleBytecode();
    }
  }

  Graph* graph() const { return graph_; }

 private:
  bool CheckType(ValueNode* node, NodeType type);
  NodeInfo* CreateInfoIfNot(ValueNode* node, NodeType type);
  bool EnsureType(ValueNode* node, NodeType type, NodeType* old = nullptr);
  bool is_toptier() {
    return v8_flags.lower_tier_as_toptier && !v8_flags.turbofan;
  }
  BasicBlock* CreateEdgeSplitBlock(int offset,
                                   int interrupt_budget_correction) {
    if (v8_flags.trace_maglev_graph_building) {
      std::cout << "== New empty block ==" << std::endl;
    }
    DCHECK_NULL(current_block_);
    current_block_ = zone()->New<BasicBlock>(nullptr);
    // Add an interrupt budget correction if necessary. This makes the edge
    // split block no longer empty, which is unexpected, but we're not changing
    // interpreter frame state, so that's ok.
    if (!is_toptier() && interrupt_budget_correction != 0) {
      DCHECK_GT(interrupt_budget_correction, 0);
      AddNewNode<IncreaseInterruptBudget>({}, interrupt_budget_correction);
    }
    BasicBlock* result = FinishBlock<Jump>({}, &jump_targets_[offset]);
    result->set_edge_split_block();
#ifdef DEBUG
    new_nodes_.clear();
#endif
    return result;
  }

  void ProcessMergePointAtExceptionHandlerStart(int offset) {
    MergePointInterpreterFrameState& merge_state = *merge_states_[offset];
    DCHECK_EQ(merge_state.predecessor_count(), 0);

    // Copy state.
    current_interpreter_frame_.CopyFrom(*compilation_unit_, merge_state);

    // Merges aren't simple fallthroughs, so we should reset the checkpoint
    // validity.
    latest_checkpointed_frame_.reset();

    // Register exception phis.
    if (has_graph_labeller()) {
      for (Phi* phi : *merge_states_[offset]->phis()) {
        graph_labeller()->RegisterNode(phi);
        if (v8_flags.trace_maglev_graph_building) {
          std::cout << "  " << phi << "  "
                    << PrintNodeLabel(graph_labeller(), phi) << ": "
                    << PrintNode(graph_labeller(), phi) << std::endl;
        }
      }
    }
  }

  void ProcessMergePoint(int offset) {
    // First copy the merge state to be the current state.
    MergePointInterpreterFrameState& merge_state = *merge_states_[offset];
    current_interpreter_frame_.CopyFrom(*compilation_unit_, merge_state);

    // Merges aren't simple fallthroughs, so we should reset the checkpoint
    // validity.
    latest_checkpointed_frame_.reset();

    if (merge_state.predecessor_count() == 1) return;

    // Set up edge-split.
    int predecessor_index = merge_state.predecessor_count() - 1;
    if (merge_state.is_loop()) {
      // For loops, the JumpLoop block hasn't been generated yet, and so isn't
      // in the list of jump targets. IT's the last predecessor, so drop the
      // index by one.
      DCHECK(merge_state.is_unmerged_loop());
      predecessor_index--;
    }
    BasicBlockRef* old_jump_targets = jump_targets_[offset].Reset();
    while (old_jump_targets != nullptr) {
      BasicBlock* predecessor = merge_state.predecessor_at(predecessor_index);
      ControlNode* control = predecessor->control_node();
      if (control->Is<ConditionalControlNode>()) {
        // CreateEmptyBlock automatically registers itself with the offset.
        predecessor = CreateEdgeSplitBlock(
            offset, old_jump_targets->interrupt_budget_correction());
        // Set the old predecessor's (the conditional block) reference to
        // point to the new empty predecessor block.
        old_jump_targets =
            old_jump_targets->SetToBlockAndReturnNext(predecessor);
      } else {
        // Re-register the block in the offset's ref list.
        old_jump_targets =
            old_jump_targets->MoveToRefList(&jump_targets_[offset]);
      }
      predecessor->set_predecessor_id(predecessor_index--);
    }
    DCHECK_EQ(predecessor_index, -1);
    if (has_graph_labeller()) {
      for (Phi* phi : *merge_states_[offset]->phis()) {
        graph_labeller()->RegisterNode(phi);
        if (v8_flags.trace_maglev_graph_building) {
          std::cout << "  " << phi << "  "
                    << PrintNodeLabel(graph_labeller(), phi) << ": "
                    << PrintNode(graph_labeller(), phi) << std::endl;
        }
      }
    }
  }

  // Return true if the given offset is a merge point, i.e. there are jumps
  // targetting it.
  bool IsOffsetAMergePoint(int offset) {
    return merge_states_[offset] != nullptr;
  }

  // Called when a block is killed by an unconditional eager deopt.
  void EmitUnconditionalDeopt(DeoptimizeReason reason) {
    // Create a block rather than calling finish, since we don't yet know the
    // next block's offset before the loop skipping the rest of the bytecodes.
    FinishBlock<Deopt>({}, reason);
    MarkBytecodeDead();
  }

  void MarkBytecodeDead() {
    DCHECK_NULL(current_block_);
    if (v8_flags.trace_maglev_graph_building) {
      std::cout << "== Dead ==\n"
                << std::setw(4) << iterator_.current_offset() << " : ";
      interpreter::BytecodeDecoder::Decode(std::cout,
                                           iterator_.current_address());
      std::cout << std::endl;
    }

    // If the current bytecode is a jump to elsewhere, then this jump is
    // also dead and we should make sure to merge it as a dead predecessor.
    interpreter::Bytecode bytecode = iterator_.current_bytecode();
    if (interpreter::Bytecodes::IsForwardJump(bytecode)) {
      // Jumps merge into their target, and conditional jumps also merge into
      // the fallthrough.
      MergeDeadIntoFrameState(iterator_.GetJumpTargetOffset());
      if (interpreter::Bytecodes::IsConditionalJump(bytecode)) {
        MergeDeadIntoFrameState(iterator_.next_offset());
      }
    } else if (bytecode == interpreter::Bytecode::kJumpLoop) {
      // JumpLoop merges into its loop header, which has to be treated
      // specially by the merge.
      MergeDeadLoopIntoFrameState(iterator_.GetJumpTargetOffset());
    } else if (interpreter::Bytecodes::IsSwitch(bytecode)) {
      // Switches merge into their targets, and into the fallthrough.
      for (auto offset : iterator_.GetJumpTableTargetOffsets()) {
        MergeDeadIntoFrameState(offset.target_offset);
      }
      MergeDeadIntoFrameState(iterator_.next_offset());
    } else if (!interpreter::Bytecodes::Returns(bytecode) &&
               !interpreter::Bytecodes::UnconditionallyThrows(bytecode)) {
      // Any other bytecode that doesn't return or throw will merge into the
      // fallthrough.
      MergeDeadIntoFrameState(iterator_.next_offset());
    } else if (interpreter::Bytecodes::Returns(bytecode) && is_inline()) {
      MergeDeadIntoFrameState(inline_exit_offset());
    }

    // TODO(leszeks): We could now continue iterating the bytecode
  }

  void UpdateSourceAndBytecodePosition(int offset) {
    if (source_position_iterator_.done()) return;
    if (source_position_iterator_.code_offset() == offset) {
      // TODO(leszeks): Add inlining support.
      const int kInliningId = SourcePosition::kNotInlined;
      current_source_position_ = SourcePosition(
          source_position_iterator_.source_position().ScriptOffset(),
          kInliningId);
      source_position_iterator_.Advance();
    } else {
      DCHECK_GT(source_position_iterator_.code_offset(), offset);
    }
  }

  void VisitSingleBytecode() {
    int offset = iterator_.current_offset();
    UpdateSourceAndBytecodePosition(offset);

    MergePointInterpreterFrameState* merge_state = merge_states_[offset];
    if (V8_UNLIKELY(merge_state != nullptr)) {
      if (current_block_ != nullptr) {
        // TODO(leszeks): Re-evaluate this DCHECK, we might hit it if the only
        // bytecodes in this basic block were only register juggling.
        // DCHECK(!current_block_->nodes().is_empty());
        BasicBlock* predecessor = FinishBlock<Jump>({}, &jump_targets_[offset]);
        merge_state->Merge(*compilation_unit_, graph_->smi(),
                           current_interpreter_frame_, predecessor, offset);
      }
      if (v8_flags.trace_maglev_graph_building) {
        auto detail = merge_state->is_exception_handler() ? "exception handler"
                      : merge_state->is_loop()            ? "loop header"
                                                          : "merge";
        std::cout << "== New block (" << detail << ") ==" << std::endl;
      }

      if (merge_state->is_exception_handler()) {
        DCHECK_EQ(predecessors_[offset], 0);
        // If we have no reference to this block, then the exception handler is
        // dead.
        if (!jump_targets_[offset].has_ref()) {
          MarkBytecodeDead();
          return;
        }
        ProcessMergePointAtExceptionHandlerStart(offset);
      } else {
        ProcessMergePoint(offset);
      }

      StartNewBlock(offset);
    } else if (V8_UNLIKELY(current_block_ == nullptr)) {
      // If we don't have a current block, the bytecode must be dead (because of
      // some earlier deopt). Mark this bytecode dead too and return.
      // TODO(leszeks): Merge these two conditions by marking dead states with
      // a sentinel value.
#ifdef DEBUG
      if (predecessors_[offset] == 1) {
        DCHECK(bytecode_analysis().IsLoopHeader(offset));
        DCHECK_NULL(merge_state);
      } else {
        DCHECK_EQ(predecessors_[offset], 0);
      }
#endif
      MarkBytecodeDead();
      return;
    }

    // Handle exceptions if we have a table.
    if (bytecode().handler_table_size() > 0) {
      if (catch_block_stack_.size() > 0) {
        // Pop all entries where offset >= end.
        while (catch_block_stack_.size() > 0) {
          HandlerTableEntry& entry = catch_block_stack_.top();
          if (offset < entry.end) break;
          catch_block_stack_.pop();
        }
      }
      // Push new entries from interpreter handler table where offset >= start
      // && offset < end.
      HandlerTable table(*bytecode().object());
      while (next_handler_table_index_ < table.NumberOfRangeEntries()) {
        int start = table.GetRangeStart(next_handler_table_index_);
        if (offset < start) break;
        int end = table.GetRangeEnd(next_handler_table_index_);
        if (offset >= end) {
          next_handler_table_index_++;
          continue;
        }
        int handler = table.GetRangeHandler(next_handler_table_index_);
        catch_block_stack_.push({end, handler});
        next_handler_table_index_++;
      }
    }

    DCHECK_NOT_NULL(current_block_);
    if (v8_flags.trace_maglev_graph_building) {
      std::cout << std::setw(4) << iterator_.current_offset() << " : ";
      interpreter::BytecodeDecoder::Decode(std::cout,
                                           iterator_.current_address());
      std::cout << std::endl;
    }
#ifdef DEBUG
    // Clear new nodes for the next VisitFoo
    new_nodes_.clear();
#endif
    switch (iterator_.current_bytecode()) {
#define BYTECODE_CASE(name, ...)       \
  case interpreter::Bytecode::k##name: \
    Visit##name();                     \
    break;
      BYTECODE_LIST(BYTECODE_CASE)
#undef BYTECODE_CASE
    }
  }

#define BYTECODE_VISITOR(name, ...) void Visit##name();
  BYTECODE_LIST(BYTECODE_VISITOR)
#undef BYTECODE_VISITOR

#define DECLARE_VISITOR(name, ...) \
  void VisitIntrinsic##name(interpreter::RegisterList args);
  INTRINSICS_LIST(DECLARE_VISITOR)
#undef DECLARE_VISITOR

  template <typename NodeT>
  NodeT* AddNode(NodeT* node) {
    if (node->properties().is_required_when_unused()) {
      MarkPossibleSideEffect();
    }
    current_block_->nodes().Add(node);
    if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
    if (v8_flags.trace_maglev_graph_building) {
      std::cout << "  " << node << "  "
                << PrintNodeLabel(graph_labeller(), node) << ": "
                << PrintNode(graph_labeller(), node) << std::endl;
    }
#ifdef DEBUG
    new_nodes_.insert(node);
#endif
    return node;
  }

  template <typename NodeT, typename... Args>
  NodeT* AddNewNode(size_t input_count, Args&&... args) {
    return AddNode(
        CreateNewNode<NodeT>(input_count, std::forward<Args>(args)...));
  }

  template <typename NodeT, typename... Args>
  NodeT* AddNewNode(std::initializer_list<ValueNode*> inputs, Args&&... args) {
    return AddNode(CreateNewNode<NodeT>(inputs, std::forward<Args>(args)...));
  }

  template <typename NodeT, typename... Args>
  NodeT* CreateNewNodeHelper(Args&&... args) {
    if constexpr (NodeT::kProperties.can_eager_deopt()) {
      return NodeBase::New<NodeT>(zone(), GetLatestCheckpointedFrame(),
                                  std::forward<Args>(args)...);
    } else if constexpr (NodeT::kProperties.can_lazy_deopt()) {
      return NodeBase::New<NodeT>(zone(), GetDeoptFrameForLazyDeopt(),
                                  std::forward<Args>(args)...);
    } else {
      return NodeBase::New<NodeT>(zone(), std::forward<Args>(args)...);
    }
  }

  template <typename NodeT, typename... Args>
  NodeT* CreateNewNode(Args&&... args) {
    NodeT* node = CreateNewNodeHelper<NodeT>(std::forward<Args>(args)...);
    if constexpr (NodeT::kProperties.can_throw()) {
      if (catch_block_stack_.size() > 0) {
        // Inside a try-block.
        int handler_offset = catch_block_stack_.top().handler;
        new (node->exception_handler_info())
            ExceptionHandlerInfo(&jump_targets_[handler_offset]);
      } else {
        // Patch no exception handler marker.
        // TODO(victorgomes): Avoid allocating exception handler data in this
        // case.
        new (node->exception_handler_info()) ExceptionHandlerInfo();
      }
    }
    return node;
  }

  enum ContextSlotMutability { kImmutable, kMutable };
  bool TrySpecializeLoadContextSlotToFunctionContext(
      ValueNode** context, size_t* depth, int slot_index,
      ContextSlotMutability slot_mutability);
  ValueNode* LoadAndCacheContextSlot(ValueNode* context, int offset,
                                     ContextSlotMutability slot_mutability);
  void BuildLoadContextSlot(ValueNode* context, size_t depth, int slot_index,
                            ContextSlotMutability slot_mutability);

  template <Builtin kBuiltin>
  CallBuiltin* BuildCallBuiltin(std::initializer_list<ValueNode*> inputs) {
    using Descriptor = typename CallInterfaceDescriptorFor<kBuiltin>::type;
    CallBuiltin* call_builtin;
    if constexpr (Descriptor::HasContextParameter()) {
      call_builtin =
          CreateNewNode<CallBuiltin>(inputs.size() + 1, kBuiltin, GetContext());
    } else {
      call_builtin = CreateNewNode<CallBuiltin>(inputs.size(), kBuiltin);
    }
    int arg_index = 0;
    for (auto* input : inputs) {
      call_builtin->set_arg(arg_index++, input);
    }
    return AddNode(call_builtin);
  }

  template <Builtin kBuiltin>
  CallBuiltin* BuildCallBuiltin(
      std::initializer_list<ValueNode*> inputs,
      compiler::FeedbackSource& feedback,
      CallBuiltin::FeedbackSlotType slot_type = CallBuiltin::kTaggedIndex) {
    CallBuiltin* call_builtin = BuildCallBuiltin<kBuiltin>(inputs);
    call_builtin->set_feedback(feedback, slot_type);
#ifdef DEBUG
    // Check that the last parameters are kSlot and kVector.
    using Descriptor = typename CallInterfaceDescriptorFor<kBuiltin>::type;
    int slot_index = call_builtin->InputCountWithoutContext();
    int vector_index = slot_index + 1;
    DCHECK_EQ(slot_index, Descriptor::kSlot);
    // TODO(victorgomes): Rename all kFeedbackVector parameters in the builtins
    // to kVector.
    DCHECK_EQ(vector_index, Descriptor::kVector);
    // Also check that the builtin does not allow var args.
    DCHECK_EQ(Descriptor::kAllowVarArgs, false);
#endif  // DEBUG
    return call_builtin;
  }

  void BuildLoadGlobal(compiler::NameRef name,
                       compiler::FeedbackSource& feedback_source,
                       TypeofMode typeof_mode);

  CallRuntime* BuildCallRuntime(Runtime::FunctionId function_id,
                                std::initializer_list<ValueNode*> inputs) {
    CallRuntime* call_runtime = CreateNewNode<CallRuntime>(
        inputs.size() + CallRuntime::kFixedInputCount, function_id,
        GetContext());
    int arg_index = 0;
    for (auto* input : inputs) {
      call_runtime->set_arg(arg_index++, input);
    }
    return AddNode(call_runtime);
  }

  void BuildAbort(AbortReason reason) {
    // Create a block rather than calling finish, since we don't yet know the
    // next block's offset before the loop skipping the rest of the bytecodes.
    FinishBlock<Abort>({}, reason);
    MarkBytecodeDead();
  }

  void Print(const char* str) {
    Handle<String> string_handle =
        local_isolate()->factory()->NewStringFromAsciiChecked(
            str, AllocationType::kOld);
    ValueNode* string_node = GetConstant(MakeRefAssumeMemoryFence(
        broker(), broker()->CanonicalPersistentHandle(string_handle)));
    BuildCallRuntime(Runtime::kGlobalPrint, {string_node});
  }

  void Print(ValueNode* value) {
    BuildCallRuntime(Runtime::kDebugPrint, {value});
  }

  void Print(const char* str, ValueNode* value) {
    Print(str);
    Print(value);
  }

  ValueNode* GetClosure() const {
    return current_interpreter_frame_.get(
        interpreter::Register::function_closure());
  }

  ValueNode* GetContext() const {
    return current_interpreter_frame_.get(
        interpreter::Register::current_context());
  }

  void SetContext(ValueNode* context) {
    current_interpreter_frame_.set(interpreter::Register::current_context(),
                                   context);
  }

  FeedbackSlot GetSlotOperand(int operand_index) const {
    return iterator_.GetSlotOperand(operand_index);
  }

  uint32_t GetFlag8Operand(int operand_index) const {
    return iterator_.GetFlag8Operand(operand_index);
  }

  uint32_t GetFlag16Operand(int operand_index) const {
    return iterator_.GetFlag16Operand(operand_index);
  }

  template <class T, typename = std::enable_if_t<
                         std::is_convertible<T*, Object*>::value>>
  typename compiler::ref_traits<T>::ref_type GetRefOperand(int operand_index) {
    // The BytecodeArray itself was fetched by using a barrier so all reads
    // from the constant pool are safe.
    return MakeRefAssumeMemoryFence(
        broker(), broker()->CanonicalPersistentHandle(
                      Handle<T>::cast(iterator_.GetConstantForIndexOperand(
                          operand_index, local_isolate()))));
  }

  SmiConstant* GetSmiConstant(int constant) {
    DCHECK(Smi::IsValid(constant));
    auto it = graph_->smi().find(constant);
    if (it == graph_->smi().end()) {
      SmiConstant* node = CreateNewNode<SmiConstant>(0, Smi::FromInt(constant));
      if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
      graph_->smi().emplace(constant, node);
      return node;
    }
    return it->second;
  }

  RootConstant* GetRootConstant(RootIndex index) {
    auto it = graph_->root().find(index);
    if (it == graph_->root().end()) {
      RootConstant* node = CreateNewNode<RootConstant>(0, index);
      if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
      graph_->root().emplace(index, node);
      return node;
    }
    return it->second;
  }

  RootConstant* GetBooleanConstant(bool value) {
    return GetRootConstant(value ? RootIndex::kTrueValue
                                 : RootIndex::kFalseValue);
  }

  Int32Constant* GetInt32Constant(int constant) {
    // The constant must fit in a Smi, since it could be later tagged in a Phi.
    DCHECK(Smi::IsValid(constant));
    auto it = graph_->int32().find(constant);
    if (it == graph_->int32().end()) {
      Int32Constant* node = CreateNewNode<Int32Constant>(0, constant);
      if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
      graph_->int32().emplace(constant, node);
      return node;
    }
    return it->second;
  }

  Float64Constant* GetFloat64Constant(double constant) {
    if (constant != constant) {
      if (graph_->nan() == nullptr) {
        graph_->set_nan(CreateNewNode<Float64Constant>(0, constant));
      }
      return graph_->nan();
    }
    auto it = graph_->float64().find(constant);
    if (it == graph_->float64().end()) {
      Float64Constant* node = CreateNewNode<Float64Constant>(0, constant);
      if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
      graph_->float64().emplace(constant, node);
      return node;
    }
    return it->second;
  }

  ValueNode* GetConstant(const compiler::ObjectRef& ref) {
    if (ref.IsSmi()) return GetSmiConstant(ref.AsSmi());

    // TODO(verwaest): Handle roots.
    const compiler::HeapObjectRef& constant = ref.AsHeapObject();
    auto it = graph_->constants().find(constant);
    if (it == graph_->constants().end()) {
      Constant* node = CreateNewNode<Constant>(0, constant);
      if (has_graph_labeller()) graph_labeller()->RegisterNode(node);
      graph_->constants().emplace(constant, node);
      return node;
    }
    return it->second;
  }

  bool IsConstantNodeTheHole(ValueNode* value) {
    DCHECK(IsConstantNode(value->opcode()));
    if (RootConstant* constant = value->TryCast<RootConstant>()) {
      return constant->index() == RootIndex::kTheHoleValue;
    }
    if (Constant* constant = value->TryCast<Constant>()) {
      return constant->IsTheHole();
    }
    // The other constants nodes cannot be TheHole.
    return false;
  }

  // Move an existing ValueNode between two registers. You can pass
  // virtual_accumulator as the src or dst to move in or out of the accumulator.
  void MoveNodeBetweenRegisters(interpreter::Register src,
                                interpreter::Register dst) {
    // We shouldn't be moving newly created nodes between registers.
    DCHECK_EQ(0, new_nodes_.count(current_interpreter_frame_.get(src)));
    DCHECK_NOT_NULL(current_interpreter_frame_.get(src));

    current_interpreter_frame_.set(dst, current_interpreter_frame_.get(src));
  }

  ValueNode* GetTaggedValue(interpreter::Register reg) {
    ValueNode* value = current_interpreter_frame_.get(reg);
    switch (value->properties().value_representation()) {
      case ValueRepresentation::kTagged:
        return value;
      case ValueRepresentation::kInt32: {
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->tagged_alternative == nullptr) {
          node_info->tagged_alternative = AddNewNode<CheckedSmiTag>({value});
        }
        return node_info->tagged_alternative;
      }
      case ValueRepresentation::kFloat64: {
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->tagged_alternative == nullptr) {
          node_info->tagged_alternative = AddNewNode<Float64Box>({value});
        }
        return node_info->tagged_alternative;
      }
    }
    UNREACHABLE();
  }

  void SetKnownType(ValueNode* node, NodeType type) {
    NodeInfo* known_info = known_node_aspects().GetOrCreateInfoFor(node);
    known_info->type = type;
  }

  ValueNode* GetInternalizedString(interpreter::Register reg) {
    ValueNode* node = GetTaggedValue(reg);
    if (known_node_aspects()
            .GetOrCreateInfoFor(node)
            ->is_internalized_string()) {
      return node;
    }
    if (Constant* constant = node->TryCast<Constant>()) {
      if (constant->object().IsInternalizedString()) {
        SetKnownType(constant, NodeType::kInternalizedString);
        return constant;
      }
    }
    node = AddNewNode<CheckedInternalizedString>({node});
    SetKnownType(node, NodeType::kInternalizedString);
    current_interpreter_frame_.set(reg, node);
    return node;
  }

  ValueNode* GetInt32(interpreter::Register reg) {
    ValueNode* value = current_interpreter_frame_.get(reg);
    switch (value->properties().value_representation()) {
      case ValueRepresentation::kTagged: {
        if (SmiConstant* constant = value->TryCast<SmiConstant>()) {
          return GetInt32Constant(constant->value().value());
        }
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->int32_alternative == nullptr) {
          node_info->int32_alternative = BuildSmiUntag(value);
        }
        return node_info->int32_alternative;
      }
      case ValueRepresentation::kInt32:
        return value;
      case ValueRepresentation::kFloat64: {
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->int32_alternative == nullptr) {
          node_info->int32_alternative =
              AddNewNode<CheckedTruncateFloat64ToInt32>({value});
        }
        return node_info->int32_alternative;
      }
    }
    UNREACHABLE();
  }

  ValueNode* GetFloat64(ValueNode* value) {
    switch (value->properties().value_representation()) {
      case ValueRepresentation::kTagged: {
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->float64_alternative == nullptr) {
          node_info->float64_alternative =
              AddNewNode<CheckedFloat64Unbox>({value});
        }
        return node_info->float64_alternative;
      }
      case ValueRepresentation::kInt32: {
        NodeInfo* node_info = known_node_aspects().GetOrCreateInfoFor(value);
        if (node_info->float64_alternative == nullptr) {
          node_info->float64_alternative =
              AddNewNode<ChangeInt32ToFloat64>({value});
        }
        return node_info->float64_alternative;
      }
      case ValueRepresentation::kFloat64:
        return value;
    }
    UNREACHABLE();
  }

  ValueNode* GetFloat64(interpreter::Register reg) {
    return GetFloat64(current_interpreter_frame_.get(reg));
  }

  ValueNode* GetAccumulatorTagged() {
    return GetTaggedValue(interpreter::Register::virtual_accumulator());
  }

  ValueNode* GetAccumulatorInt32() {
    return GetInt32(interpreter::Register::virtual_accumulator());
  }

  ValueNode* GetAccumulatorFloat64() {
    return GetFloat64(interpreter::Register::virtual_accumulator());
  }

  bool IsRegisterEqualToAccumulator(int operand_index) {
    interpreter::Register source = iterator_.GetRegisterOperand(operand_index);
    return current_interpreter_frame_.get(source) ==
           current_interpreter_frame_.accumulator();
  }

  ValueNode* LoadRegisterTagged(int operand_index) {
    return GetTaggedValue(iterator_.GetRegisterOperand(operand_index));
  }

  ValueNode* LoadRegisterInt32(int operand_index) {
    return GetInt32(iterator_.GetRegisterOperand(operand_index));
  }

  ValueNode* LoadRegisterFloat64(int operand_index) {
    return GetFloat64(iterator_.GetRegisterOperand(operand_index));
  }

  ValueNode* LoadFixedArrayElement(ValueNode* node, int index) {
    return AddNewNode<LoadTaggedField>({node},
                                       FixedArray::OffsetOfElementAt(index));
  }

  template <typename NodeT>
  void SetAccumulator(NodeT* node) {
    // Accumulator stores are equivalent to stores to the virtual accumulator
    // register.
    StoreRegister(interpreter::Register::virtual_accumulator(), node);
  }

  ValueNode* GetSecondValue(ValueNode* result) {
    // GetSecondReturnedValue must be added just after a node that calls a
    // builtin that expects 2 returned values. It simply binds kReturnRegister1
    // to a value node. Since the previous node must have been a builtin
    // call, the register is available in the register allocator. No gap moves
    // would be emitted between these two nodes.
    if (result->opcode() == Opcode::kCallRuntime) {
      DCHECK_EQ(result->Cast<CallRuntime>()->ReturnCount(), 2);
    } else if (result->opcode() == Opcode::kCallBuiltin) {
      DCHECK_EQ(result->Cast<CallBuiltin>()->ReturnCount(), 2);
    } else {
      DCHECK_EQ(result->opcode(), Opcode::kForInPrepare);
    }
    // {result} must be the last node in the current block.
    DCHECK(current_block_->nodes().Contains(result));
    DCHECK_EQ(result->NextNode(), nullptr);
    return AddNewNode<GetSecondReturnedValue>({});
  }

  template <typename NodeT>
  void StoreRegister(interpreter::Register target, NodeT* value) {
    // We should only set register values to nodes that were newly created in
    // this Visit. Existing nodes should be moved between registers with
    // MoveNodeBetweenRegisters.
    if (!IsConstantNode(value->opcode())) {
      DCHECK_NE(0, new_nodes_.count(value));
    }
    MarkAsLazyDeoptResult(value, target, 1);
    current_interpreter_frame_.set(target, value);
  }

  template <typename NodeT>
  void StoreRegisterPair(
      std::pair<interpreter::Register, interpreter::Register> target,
      NodeT* value) {
    const interpreter::Register target0 = target.first;
    const interpreter::Register target1 = target.second;

    DCHECK_EQ(interpreter::Register(target0.index() + 1), target1);
    DCHECK_EQ(value->ReturnCount(), 2);

    DCHECK_NE(0, new_nodes_.count(value));
    MarkAsLazyDeoptResult(value, target0, value->ReturnCount());
    current_interpreter_frame_.set(target0, value);

    ValueNode* second_value = GetSecondValue(value);
    DCHECK_NE(0, new_nodes_.count(second_value));
    current_interpreter_frame_.set(target1, second_value);
  }

  InterpretedDeoptFrame GetLatestCheckpointedFrame() {
    if (!latest_checkpointed_frame_) {
      latest_checkpointed_frame_.emplace(
          *compilation_unit_,
          zone()->New<CompactInterpreterFrameState>(
              *compilation_unit_, GetInLiveness(), current_interpreter_frame_),
          BytecodeOffset(iterator_.current_offset()), current_source_position_,
          // TODO(leszeks): Don't always allocate for the parent state,
          // maybe cache it on the graph builder?
          parent_
              ? zone()->New<DeoptFrame>(parent_->GetLatestCheckpointedFrame())
              : nullptr);
    }
    return *latest_checkpointed_frame_;
  }

  InterpretedDeoptFrame GetDeoptFrameForLazyDeopt() {
    return InterpretedDeoptFrame(
        *compilation_unit_,
        zone()->New<CompactInterpreterFrameState>(
            *compilation_unit_, GetOutLiveness(), current_interpreter_frame_),
        BytecodeOffset(iterator_.current_offset()), current_source_position_,
        // TODO(leszeks): Support inlining for lazy deopts.
        nullptr);
  }

  template <typename NodeT>
  void MarkAsLazyDeoptResult(NodeT* value,
                             interpreter::Register result_location,
                             int result_size) {
    DCHECK_EQ(NodeT::kProperties.can_lazy_deopt(),
              value->properties().can_lazy_deopt());
    if constexpr (NodeT::kProperties.can_lazy_deopt()) {
      value->lazy_deopt_info()->SetResultLocation(result_location, result_size);
    }
  }

  void MarkPossibleSideEffect() {
    // If there was a potential side effect, invalidate the previous checkpoint.
    latest_checkpointed_frame_.reset();

    // A side effect could change existing objects' maps. For stable maps we
    // know this hasn't happened (because we added a dependency on the maps
    // staying stable and therefore not possible to transition away from), but
    // we can no longer assume that objects with unstable maps still have the
    // same map. Unstable maps can also transition to stable ones, so the
    // set of stable maps becomes invalid for a not that had a unstable map.
    auto it = known_node_aspects().unstable_maps.begin();
    while (it != known_node_aspects().unstable_maps.end()) {
      if (it->second.size() == 0) {
        it++;
      } else {
        known_node_aspects().stable_maps.erase(it->first);
        it = known_node_aspects().unstable_maps.erase(it);
      }
    }
    // Similarly, side-effects can change object contents, so we have to clear
    // our known loaded properties -- however, constant properties are known
    // to not change (and we added a dependency on this), so we don't have to
    // clear those.
    known_node_aspects().loaded_properties.clear();
    known_node_aspects().loaded_context_slots.clear();
  }

  int next_offset() const {
    return iterator_.current_offset() + iterator_.current_bytecode_size();
  }
  const compiler::BytecodeLivenessState* GetInLiveness() const {
    return GetInLivenessFor(iterator_.current_offset());
  }
  const compiler::BytecodeLivenessState* GetInLivenessFor(int offset) const {
    return bytecode_analysis().GetInLivenessFor(offset);
  }
  const compiler::BytecodeLivenessState* GetOutLiveness() const {
    return GetOutLivenessFor(iterator_.current_offset());
  }
  const compiler::BytecodeLivenessState* GetOutLivenessFor(int offset) const {
    return bytecode_analysis().GetOutLivenessFor(offset);
  }

  void StartNewBlock(int offset) {
    DCHECK_NULL(current_block_);
    current_block_ = zone()->New<BasicBlock>(merge_states_[offset]);
    ResolveJumpsToBlockAtOffset(current_block_, offset);
  }

  template <typename ControlNodeT, typename... Args>
  BasicBlock* FinishBlock(std::initializer_list<ValueNode*> control_inputs,
                          Args&&... args) {
    ControlNode* control_node = CreateNewNode<ControlNodeT>(
        control_inputs, std::forward<Args>(args)...);
    current_block_->set_control_node(control_node);

    BasicBlock* block = current_block_;
    current_block_ = nullptr;

    graph()->Add(block);
    if (has_graph_labeller()) {
      graph_labeller()->RegisterBasicBlock(block);
      if (v8_flags.trace_maglev_graph_building) {
        bool kSkipTargets = true;
        std::cout << "  " << control_node << "  "
                  << PrintNodeLabel(graph_labeller(), control_node) << ": "
                  << PrintNode(graph_labeller(), control_node, kSkipTargets)
                  << std::endl;
      }
    }
    return block;
  }

  // Update all jumps which were targetting the not-yet-created block at the
  // given `block_offset`, to now point to the given `block`.
  void ResolveJumpsToBlockAtOffset(BasicBlock* block, int block_offset) {
    int interrupt_budget_correction = 0;
    BasicBlockRef* jump_target_refs_head =
        jump_targets_[block_offset].SetToBlockAndReturnNext(block);
    while (jump_target_refs_head != nullptr) {
      // Only one jump target should ever set the interrupt budget correction.
      DCHECK_EQ(interrupt_budget_correction, 0);
      interrupt_budget_correction =
          jump_target_refs_head->interrupt_budget_correction();
      jump_target_refs_head =
          jump_target_refs_head->SetToBlockAndReturnNext(block);
    }
    if (!is_toptier() && interrupt_budget_correction != 0) {
      DCHECK_GT(interrupt_budget_correction, 0);
      AddNewNode<IncreaseInterruptBudget>({}, interrupt_budget_correction);
    }
    DCHECK_EQ(jump_targets_[block_offset].block_ptr(), block);
  }

  void StartFallthroughBlock(int next_block_offset, BasicBlock* predecessor) {
    // Start a new block for the fallthrough path, unless it's a merge point, in
    // which case we merge our state into it. That merge-point could also be a
    // loop header, in which case the merge state might not exist yet (if the
    // only predecessors are this path and the JumpLoop).
    DCHECK_NULL(current_block_);

    if (NumPredecessors(next_block_offset) == 1) {
      if (v8_flags.trace_maglev_graph_building) {
        std::cout << "== New block (single fallthrough) ==" << std::endl;
      }
      StartNewBlock(next_block_offset);
    } else {
      MergeIntoFrameState(predecessor, next_block_offset);
    }
  }

  void InlineCallFromRegisters(int argc_count,
                               ConvertReceiverMode receiver_mode,
                               compiler::JSFunctionRef function);

  class CallArguments {
   public:
    enum Mode {
      kFromRegisters,
      kFromRegisterList,
    };

    CallArguments(ConvertReceiverMode receiver_mode, int reg_count,
                  interpreter::Register r0 = interpreter::Register(),
                  interpreter::Register r1 = interpreter::Register(),
                  interpreter::Register r2 = interpreter::Register())
        : receiver_mode_(receiver_mode),
          call_mode_(kFromRegisters),
          reg_count_(reg_count) {
      DCHECK_GE(reg_count, 0);
      DCHECK_LT(reg_count, 4);
      DCHECK_IMPLIES(receiver_mode_ != ConvertReceiverMode::kNullOrUndefined,
                     reg_count > 0);
      DCHECK_IMPLIES(reg_count > 0, r0.is_valid());
      regs_[0] = r0;
      DCHECK_IMPLIES(reg_count > 1, r1.is_valid());
      regs_[1] = r1;
      DCHECK_IMPLIES(reg_count > 2, r2.is_valid());
      regs_[2] = r2;
    }

    CallArguments(ConvertReceiverMode receiver_mode,
                  interpreter::RegisterList reglist)
        : receiver_mode_(receiver_mode),
          call_mode_(kFromRegisterList),
          reglist_(reglist) {}

    base::Optional<interpreter::Register> receiver() const {
      if (receiver_mode_ == ConvertReceiverMode::kNullOrUndefined) {
        return {};
      }
      if (call_mode_ == kFromRegisters) {
        DCHECK_GT(reg_count_, 0);
        return regs_[0];
      }
      return reglist_[0];
    }

    int count() const {
      int register_count =
          call_mode_ == kFromRegisters ? reg_count_ : reglist_.register_count();
      if (receiver_mode_ == ConvertReceiverMode::kNullOrUndefined) {
        return register_count;
      }
      return register_count - 1;
    }

    int count_with_receiver() const { return count() + 1; }

    const interpreter::Register operator[](size_t i) const {
      if (receiver_mode_ != ConvertReceiverMode::kNullOrUndefined) {
        i++;
      }
      if (call_mode_ == kFromRegisters) {
        DCHECK_LT(i, reg_count_);
        DCHECK_GE(i, 0);
        return regs_[i];
      }
      return reglist_[i];
    }

    ConvertReceiverMode receiver_mode() const { return receiver_mode_; }

    CallArguments PopReceiver(ConvertReceiverMode new_receiver_mode) const {
      DCHECK_NE(receiver_mode_, ConvertReceiverMode::kNullOrUndefined);
      DCHECK_NE(new_receiver_mode, ConvertReceiverMode::kNullOrUndefined);
      // If there is no non-receiver argument to become the new receiver,
      // consider the new receiver to be known undefined.
      if (count() == 0) {
        new_receiver_mode = ConvertReceiverMode::kNullOrUndefined;
      }
      if (call_mode_ == kFromRegisters) {
        return CallArguments(new_receiver_mode, reg_count_ - 1, regs_[1],
                             regs_[2]);
      }
      return CallArguments(new_receiver_mode, reglist_.PopLeft());
    }

   private:
    const ConvertReceiverMode receiver_mode_;
    const Mode call_mode_;
    union {
      struct {
        interpreter::Register regs_[3];
        int reg_count_;
      };
      interpreter::RegisterList reglist_;
    };
  };

  ValueNode* GetTaggedReceiver(const CallArguments& args) {
    auto maybe_receiver = args.receiver();
    if (maybe_receiver.has_value()) {
      return GetTaggedValue(*maybe_receiver);
    }
    DCHECK_EQ(args.receiver_mode(), ConvertReceiverMode::kNullOrUndefined);
    return GetRootConstant(RootIndex::kUndefinedValue);
  }
  ValueNode* GetConvertReceiver(compiler::JSFunctionRef function,
                                const CallArguments& args);

#define MAGLEV_REDUCED_BUILTIN(V) \
  V(FunctionPrototypeCall)        \
  V(StringFromCharCode)           \
  V(StringPrototypeCharCodeAt)

#define DEFINE_BUILTIN_REDUCER(Name)                           \
  bool TryReduce##Name(compiler::JSFunctionRef builtin_target, \
                       const CallArguments& args);
  MAGLEV_REDUCED_BUILTIN(DEFINE_BUILTIN_REDUCER)
#undef DEFINE_BUILTIN_REDUCER

  bool TryReduceBuiltin(compiler::JSFunctionRef builtin_target,
                        const CallArguments& args);

  bool TryBuildCallKnownJSFunction(compiler::JSFunctionRef function,
                                   const CallArguments& args);

  void BuildGenericCall(ValueNode* target, ValueNode* context,
                        Call::TargetType target_type, const CallArguments& args,
                        compiler::FeedbackSource& feedback_source);
  void BuildCall(ValueNode* target_node, const CallArguments& args,
                 compiler::FeedbackSource& feedback_source);
  void BuildCallFromRegisterList(ConvertReceiverMode receiver_mode);
  void BuildCallFromRegisters(int argc_count,
                              ConvertReceiverMode receiver_mode);

  bool TryBuildScriptContextConstantAccess(
      const compiler::GlobalAccessFeedback& global_access_feedback);
  bool TryBuildScriptContextAccess(
      const compiler::GlobalAccessFeedback& global_access_feedback);
  bool TryBuildPropertyCellAccess(
      const compiler::GlobalAccessFeedback& global_access_feedback);

  ValueNode* BuildSmiUntag(ValueNode* node);

  void BuildCheckSmi(ValueNode* object);
  void BuildCheckNumber(ValueNode* object);
  void BuildCheckHeapObject(ValueNode* object);
  void BuildCheckString(ValueNode* object);
  void BuildCheckSymbol(ValueNode* object);
  void BuildCheckMaps(ValueNode* object,
                      ZoneVector<compiler::MapRef> const& maps);
  // Emits an unconditional deopt and returns false if the node is a constant
  // that doesn't match the ref.
  bool BuildCheckValue(ValueNode* node, const compiler::HeapObjectRef& ref);

  ValueNode* GetInt32ElementIndex(interpreter::Register reg) {
    ValueNode* index_object = current_interpreter_frame_.get(reg);
    return GetInt32ElementIndex(index_object);
  }
  ValueNode* GetInt32ElementIndex(ValueNode* index_object);

  bool TryFoldLoadDictPrototypeConstant(
      compiler::PropertyAccessInfo access_info);
  bool TryFoldLoadConstantDataField(compiler::PropertyAccessInfo access_info,
                                    ValueNode* lookup_start_object);

  void BuildLoadField(compiler::PropertyAccessInfo access_info,
                      ValueNode* lookup_start_object);
  bool TryBuildStoreField(compiler::PropertyAccessInfo access_info,
                          ValueNode* receiver);
  bool TryBuildPropertyGetterCall(compiler::PropertyAccessInfo access_info,
                                  ValueNode* receiver,
                                  ValueNode* lookup_start_object);
  bool TryBuildPropertySetterCall(compiler::PropertyAccessInfo access_info,
                                  ValueNode* receiver, ValueNode* value);

  bool TryBuildPropertyLoad(ValueNode* receiver, ValueNode* lookup_start_object,
                            compiler::NameRef name,
                            compiler::PropertyAccessInfo const& access_info);
  bool TryBuildPropertyStore(ValueNode* receiver, compiler::NameRef name,
                             compiler::PropertyAccessInfo const& access_info);
  bool TryBuildPropertyAccess(ValueNode* receiver,
                              ValueNode* lookup_start_object,
                              compiler::NameRef name,
                              compiler::PropertyAccessInfo const& access_info,
                              compiler::AccessMode access_mode);

  bool TryBuildElementAccessOnString(
      ValueNode* object, ValueNode* index,
      compiler::KeyedAccessMode const& keyed_mode);

  bool TryBuildNamedAccess(ValueNode* receiver, ValueNode* lookup_start_object,
                           compiler::NamedAccessFeedback const& feedback,
                           compiler::AccessMode access_mode);
  bool TryBuildElementAccess(ValueNode* object, ValueNode* index,
                             compiler::ElementAccessFeedback const& feedback);

  // Load elimination -- when loading or storing a simple property without
  // side effects, record its value, and allow that value to be re-used on
  // subsequent loads.
  void RecordKnownProperty(ValueNode* lookup_start_object,
                           compiler::NameRef name, ValueNode* value,
                           bool is_const);
  bool TryReuseKnownPropertyLoad(ValueNode* lookup_start_object,
                                 compiler::NameRef name);

  enum InferHasInPrototypeChainResult {
    kMayBeInPrototypeChain,
    kIsInPrototypeChain,
    kIsNotInPrototypeChain
  };
  InferHasInPrototypeChainResult InferHasInPrototypeChain(
      ValueNode* receiver, compiler::HeapObjectRef prototype);
  bool TryBuildFastHasInPrototypeChain(ValueNode* object,
                                       compiler::ObjectRef prototype);
  void BuildHasInPrototypeChain(ValueNode* object,
                                compiler::ObjectRef prototype);
  bool TryBuildFastOrdinaryHasInstance(ValueNode* object,
                                       compiler::JSObjectRef callable,
                                       ValueNode* callable_node);
  void BuildOrdinaryHasInstance(ValueNode* object,
                                compiler::JSObjectRef callable,
                                ValueNode* callable_node);
  bool TryBuildFastInstanceOf(ValueNode* object,
                              compiler::JSObjectRef callable_ref,
                              ValueNode* callable_node);
  bool TryBuildFastInstanceOfWithFeedback(
      ValueNode* object, ValueNode* callable,
      compiler::FeedbackSource feedback_source);

  template <Operation kOperation>
  void BuildGenericUnaryOperationNode();
  template <Operation kOperation>
  void BuildGenericBinaryOperationNode();
  template <Operation kOperation>
  void BuildGenericBinarySmiOperationNode();

  template <Operation kOperation>
  ValueNode* AddNewInt32BinaryOperationNode(
      std::initializer_list<ValueNode*> inputs);
  template <Operation kOperation>
  ValueNode* AddNewFloat64BinaryOperationNode(
      std::initializer_list<ValueNode*> inputs);

  template <Operation kOperation>
  ValueNode* TryFoldInt32BinaryOperation(ValueNode* left, ValueNode* right);
  template <Operation kOperation>
  ValueNode* TryFoldInt32BinaryOperation(ValueNode* left, int right);

  template <Operation kOperation>
  void BuildInt32BinaryOperationNode();
  template <Operation kOperation>
  void BuildInt32BinarySmiOperationNode();
  template <Operation kOperation>
  void BuildFloat64BinaryOperationNode();
  template <Operation kOperation>
  void BuildFloat64BinarySmiOperationNode();

  template <Operation kOperation>
  void VisitUnaryOperation();
  template <Operation kOperation>
  void VisitBinaryOperation();
  template <Operation kOperation>
  void VisitBinarySmiOperation();

  template <typename CompareControlNode>
  bool TryBuildCompareOperation(Operation operation, ValueNode* left,
                                ValueNode* right);
  template <Operation kOperation>
  void VisitCompareOperation();

  void MergeIntoFrameState(BasicBlock* block, int target);
  void MergeDeadIntoFrameState(int target);
  void MergeDeadLoopIntoFrameState(int target);
  void MergeIntoInlinedReturnFrameState(BasicBlock* block);

  enum JumpType { kJumpIfTrue, kJumpIfFalse };
  void BuildBranchIfRootConstant(ValueNode* node, JumpType jump_type,
                                 RootIndex root_index);
  void BuildBranchIfTrue(ValueNode* node, JumpType jump_type);
  void BuildBranchIfNull(ValueNode* node, JumpType jump_type);
  void BuildBranchIfUndefined(ValueNode* node, JumpType jump_type);
  void BuildBranchIfToBooleanTrue(ValueNode* node, JumpType jump_type);

  void BuildToNumberOrToNumeric(Object::Conversion mode);

  void CalculatePredecessorCounts() {
    // Add 1 after the end of the bytecode so we can always write to the offset
    // after the last bytecode.
    size_t array_length = bytecode().length() + 1;
    predecessors_ = zone()->NewArray<uint32_t>(array_length);
    MemsetUint32(predecessors_, 1, array_length);

    interpreter::BytecodeArrayIterator iterator(bytecode().object());
    for (; !iterator.done(); iterator.Advance()) {
      interpreter::Bytecode bytecode = iterator.current_bytecode();
      if (interpreter::Bytecodes::IsJump(bytecode)) {
        predecessors_[iterator.GetJumpTargetOffset()]++;
        if (!interpreter::Bytecodes::IsConditionalJump(bytecode)) {
          predecessors_[iterator.next_offset()]--;
        }
      } else if (interpreter::Bytecodes::IsSwitch(bytecode)) {
        for (auto offset : iterator.GetJumpTableTargetOffsets()) {
          predecessors_[offset.target_offset]++;
        }
      } else if (interpreter::Bytecodes::Returns(bytecode) ||
                 interpreter::Bytecodes::UnconditionallyThrows(bytecode)) {
        predecessors_[iterator.next_offset()]--;
        // Collect inline return jumps in the slot after the last bytecode.
        if (is_inline() && interpreter::Bytecodes::Returns(bytecode)) {
          predecessors_[array_length - 1]++;
        }
      }
      // TODO(leszeks): Also consider handler entries (the bytecode analysis)
      // will do this automatically I guess if we merge this into that.
    }
    if (!is_inline()) {
      DCHECK_EQ(0, predecessors_[bytecode().length()]);
    }
  }

  int NumPredecessors(int offset) { return predecessors_[offset]; }

  compiler::JSHeapBroker* broker() const { return compilation_unit_->broker(); }
  const compiler::FeedbackVectorRef& feedback() const {
    return compilation_unit_->feedback();
  }
  const FeedbackNexus FeedbackNexusForOperand(int slot_operand_index) const {
    return FeedbackNexus(feedback().object(),
                         GetSlotOperand(slot_operand_index),
                         broker()->feedback_nexus_config());
  }
  const FeedbackNexus FeedbackNexusForSlot(FeedbackSlot slot) const {
    return FeedbackNexus(feedback().object(), slot,
                         broker()->feedback_nexus_config());
  }
  const compiler::BytecodeArrayRef& bytecode() const {
    return compilation_unit_->bytecode();
  }
  const compiler::BytecodeAnalysis& bytecode_analysis() const {
    return bytecode_analysis_;
  }
  LocalIsolate* local_isolate() const { return local_isolate_; }
  Zone* zone() const { return compilation_unit_->zone(); }
  int parameter_count() const { return compilation_unit_->parameter_count(); }
  int parameter_count_without_receiver() { return parameter_count() - 1; }
  int register_count() const { return compilation_unit_->register_count(); }
  bool has_graph_labeller() const {
    return compilation_unit_->has_graph_labeller();
  }
  MaglevGraphLabeller* graph_labeller() const {
    return compilation_unit_->graph_labeller();
  }
  KnownNodeAspects& known_node_aspects() {
    return current_interpreter_frame_.known_node_aspects();
  }

  // True when this graph builder is building the subgraph of an inlined
  // function.
  bool is_inline() const { return parent_ != nullptr; }

  // The fake offset used as a target for all exits of an inlined function.
  int inline_exit_offset() const {
    DCHECK(is_inline());
    return bytecode().length();
  }

  LocalIsolate* const local_isolate_;
  MaglevCompilationUnit* const compilation_unit_;
  MaglevGraphBuilder* const parent_;
  Graph* const graph_;
  compiler::BytecodeAnalysis bytecode_analysis_;
  interpreter::BytecodeArrayIterator iterator_;
  SourcePositionTableIterator source_position_iterator_;
  uint32_t* predecessors_;

  // Current block information.
  BasicBlock* current_block_ = nullptr;
  base::Optional<InterpretedDeoptFrame> latest_checkpointed_frame_;
  SourcePosition current_source_position_;

  BasicBlockRef* jump_targets_;
  MergePointInterpreterFrameState** merge_states_;

  InterpreterFrameState current_interpreter_frame_;

  struct HandlerTableEntry {
    int end;
    int handler;
  };
  ZoneStack<HandlerTableEntry> catch_block_stack_;
  int next_handler_table_index_ = 0;

#ifdef DEBUG
  std::unordered_set<Node*> new_nodes_;
#endif
};

}  // namespace maglev
}  // namespace internal
}  // namespace v8

#endif  // V8_MAGLEV_MAGLEV_GRAPH_BUILDER_H_