bytecode-graph-builder.cc 157 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/bytecode-graph-builder.h"

7
#include "src/ast/ast.h"
8
#include "src/codegen/source-position-table.h"
9
#include "src/compiler/access-builder.h"
10
#include "src/compiler/bytecode-analysis.h"
11
#include "src/compiler/compiler-source-position-table.h"
12
#include "src/compiler/linkage.h"
13
#include "src/compiler/node-matchers.h"
14
#include "src/compiler/operator-properties.h"
15
#include "src/compiler/simplified-operator.h"
16
#include "src/compiler/state-values-utils.h"
17
#include "src/compiler/vector-slot-pair.h"
18 19
#include "src/interpreter/bytecode-array-iterator.h"
#include "src/interpreter/bytecode-flags.h"
20
#include "src/interpreter/bytecodes.h"
21
#include "src/objects/js-array-inl.h"
22
#include "src/objects/js-generator.h"
23
#include "src/objects/literal-objects-inl.h"
24
#include "src/objects/objects-inl.h"
25
#include "src/objects/smi.h"
26
#include "src/objects/template-objects-inl.h"
27 28 29 30 31

namespace v8 {
namespace internal {
namespace compiler {

32 33
class BytecodeGraphBuilder {
 public:
34 35
  BytecodeGraphBuilder(JSHeapBroker* broker, Zone* local_zone,
                       Handle<BytecodeArray> bytecode_array,
36 37 38
                       Handle<SharedFunctionInfo> shared,
                       Handle<FeedbackVector> feedback_vector,
                       BailoutId osr_offset, JSGraph* jsgraph,
39
                       CallFrequency const& invocation_frequency,
40 41
                       SourcePositionTable* source_positions,
                       Handle<Context> native_context, int inlining_id,
42
                       BytecodeGraphBuilderFlags flags);
43 44 45 46 47 48 49 50 51 52

  // Creates a graph by visiting bytecodes.
  void CreateGraph();

 private:
  class Environment;
  class OsrIteratorState;
  struct SubEnvironment;

  void RemoveMergeEnvironmentsBeforeOffset(int limit_offset);
53
  void AdvanceToOsrEntryAndPeelLoops();
54

55 56 57 58
  // Advance {bytecode_iterator} to the given offset. If possible, also advance
  // {source_position_iterator} while updating the source position table.
  void AdvanceIteratorsTo(int bytecode_offset);

59
  void VisitSingleBytecode();
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
  void VisitBytecodes();

  // Get or create the node that represents the outer function closure.
  Node* GetFunctionClosure();

  // Builder for loading the a native context field.
  Node* BuildLoadNativeContextField(int index);

  // Helper function for creating a pair containing type feedback vector and
  // a feedback slot.
  VectorSlotPair CreateVectorSlotPair(int slot_id);

  void set_environment(Environment* env) { environment_ = env; }
  const Environment* environment() const { return environment_; }
  Environment* environment() { return environment_; }

  // Node creation helpers
  Node* NewNode(const Operator* op, bool incomplete = false) {
    return MakeNode(op, 0, static_cast<Node**>(nullptr), incomplete);
  }

  Node* NewNode(const Operator* op, Node* n1) {
    Node* buffer[] = {n1};
    return MakeNode(op, arraysize(buffer), buffer, false);
  }

  Node* NewNode(const Operator* op, Node* n1, Node* n2) {
    Node* buffer[] = {n1, n2};
    return MakeNode(op, arraysize(buffer), buffer, false);
  }

  Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3) {
    Node* buffer[] = {n1, n2, n3};
    return MakeNode(op, arraysize(buffer), buffer, false);
  }

  Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4) {
    Node* buffer[] = {n1, n2, n3, n4};
    return MakeNode(op, arraysize(buffer), buffer, false);
  }

  Node* NewNode(const Operator* op, Node* n1, Node* n2, Node* n3, Node* n4,
                Node* n5, Node* n6) {
    Node* buffer[] = {n1, n2, n3, n4, n5, n6};
    return MakeNode(op, arraysize(buffer), buffer, false);
  }

  // Helpers to create new control nodes.
  Node* NewIfTrue() { return NewNode(common()->IfTrue()); }
  Node* NewIfFalse() { return NewNode(common()->IfFalse()); }
  Node* NewIfValue(int32_t value) { return NewNode(common()->IfValue(value)); }
  Node* NewIfDefault() { return NewNode(common()->IfDefault()); }
  Node* NewMerge() { return NewNode(common()->Merge(1), true); }
  Node* NewLoop() { return NewNode(common()->Loop(1), true); }
  Node* NewBranch(Node* condition, BranchHint hint = BranchHint::kNone,
                  IsSafetyCheck is_safety_check = IsSafetyCheck::kSafetyCheck) {
    return NewNode(common()->Branch(hint, is_safety_check), condition);
  }
  Node* NewSwitch(Node* condition, int control_output_count) {
    return NewNode(common()->Switch(control_output_count), condition);
  }

  // Creates a new Phi node having {count} input values.
  Node* NewPhi(int count, Node* input, Node* control);
  Node* NewEffectPhi(int count, Node* input, Node* control);

  // Helpers for merging control, effect or value dependencies.
  Node* MergeControl(Node* control, Node* other);
  Node* MergeEffect(Node* effect, Node* other_effect, Node* control);
  Node* MergeValue(Node* value, Node* other_value, Node* control);

  // The main node creation chokepoint. Adds context, frame state, effect,
  // and control dependencies depending on the operator.
  Node* MakeNode(const Operator* op, int value_input_count,
                 Node* const* value_inputs, bool incomplete);

  Node** EnsureInputBufferSize(int size);

  Node* const* GetCallArgumentsFromRegisters(Node* callee, Node* receiver,
                                             interpreter::Register first_arg,
                                             int arg_count);
  Node* const* ProcessCallVarArgs(ConvertReceiverMode receiver_mode,
                                  Node* callee, interpreter::Register first_reg,
                                  int arg_count);
  Node* ProcessCallArguments(const Operator* call_op, Node* const* args,
                             int arg_count);
  Node* ProcessCallArguments(const Operator* call_op, Node* callee,
                             interpreter::Register receiver, size_t reg_count);
  Node* const* GetConstructArgumentsFromRegister(
      Node* target, Node* new_target, interpreter::Register first_arg,
      int arg_count);
  Node* ProcessConstructArguments(const Operator* op, Node* const* args,
                                  int arg_count);
  Node* ProcessCallRuntimeArguments(const Operator* call_runtime_op,
                                    interpreter::Register receiver,
                                    size_t reg_count);

  // Prepare information for eager deoptimization. This information is carried
  // by dedicated {Checkpoint} nodes that are wired into the effect chain.
  // Conceptually this frame state is "before" a given operation.
  void PrepareEagerCheckpoint();

  // Prepare information for lazy deoptimization. This information is attached
  // to the given node and the output value produced by the node is combined.
  // Conceptually this frame state is "after" a given operation.
  void PrepareFrameState(Node* node, OutputFrameStateCombine combine);

  void BuildCreateArguments(CreateArgumentsType type);
  Node* BuildLoadGlobal(Handle<Name> name, uint32_t feedback_slot_index,
                        TypeofMode typeof_mode);

  enum class StoreMode {
    // Check the prototype chain before storing.
    kNormal,
    // Store value to the receiver without checking the prototype chain.
    kOwn,
  };
  void BuildNamedStore(StoreMode store_mode);
  void BuildLdaLookupSlot(TypeofMode typeof_mode);
  void BuildLdaLookupContextSlot(TypeofMode typeof_mode);
  void BuildLdaLookupGlobalSlot(TypeofMode typeof_mode);
  void BuildCallVarArgs(ConvertReceiverMode receiver_mode);
  void BuildCall(ConvertReceiverMode receiver_mode, Node* const* args,
                 size_t arg_count, int slot_id);
  void BuildCall(ConvertReceiverMode receiver_mode,
                 std::initializer_list<Node*> args, int slot_id) {
    BuildCall(receiver_mode, args.begin(), args.size(), slot_id);
  }
  void BuildUnaryOp(const Operator* op);
  void BuildBinaryOp(const Operator* op);
  void BuildBinaryOpWithImmediate(const Operator* op);
  void BuildCompareOp(const Operator* op);
  void BuildDelete(LanguageMode language_mode);
  void BuildCastOperator(const Operator* op);
  void BuildHoleCheckAndThrow(Node* condition, Runtime::FunctionId runtime_id,
                              Node* name = nullptr);

  // Optional early lowering to the simplified operator level.  Note that
  // the result has already been wired into the environment just like
  // any other invocation of {NewNode} would do.
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedUnaryOp(
      const Operator* op, Node* operand, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedBinaryOp(
      const Operator* op, Node* left, Node* right, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedForInNext(
      Node* receiver, Node* cache_array, Node* cache_type, Node* index,
      FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedForInPrepare(
      Node* receiver, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedToNumber(
      Node* input, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedCall(const Operator* op,
                                                            Node* const* args,
                                                            int arg_count,
                                                            FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedConstruct(
      const Operator* op, Node* const* args, int arg_count, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedLoadNamed(
      const Operator* op, Node* receiver, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedLoadKeyed(
      const Operator* op, Node* receiver, Node* key, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedStoreNamed(
      const Operator* op, Node* receiver, Node* value, FeedbackSlot slot);
  JSTypeHintLowering::LoweringResult TryBuildSimplifiedStoreKeyed(
      const Operator* op, Node* receiver, Node* key, Node* value,
      FeedbackSlot slot);

  // Applies the given early reduction onto the current environment.
  void ApplyEarlyReduction(JSTypeHintLowering::LoweringResult reduction);

  // Check the context chain for extensions, for lookup fast paths.
  Environment* CheckContextExtensions(uint32_t depth);

  // Helper function to create binary operation hint from the recorded
  // type feedback.
  BinaryOperationHint GetBinaryOperationHint(int operand_index);

  // Helper function to create compare operation hint from the recorded
  // type feedback.
  CompareOperationHint GetCompareOperationHint();

  // Helper function to create for-in mode from the recorded type feedback.
  ForInMode GetForInMode(int operand_index);

  // Helper function to compute call frequency from the recorded type
  // feedback.
  CallFrequency ComputeCallFrequency(int slot_id) const;

  // Helper function to extract the speculation mode from the recorded type
  // feedback.
  SpeculationMode GetSpeculationMode(int slot_id) const;

  // Control flow plumbing.
  void BuildJump();
  void BuildJumpIf(Node* condition);
  void BuildJumpIfNot(Node* condition);
  void BuildJumpIfEqual(Node* comperand);
  void BuildJumpIfNotEqual(Node* comperand);
  void BuildJumpIfTrue();
  void BuildJumpIfFalse();
  void BuildJumpIfToBooleanTrue();
  void BuildJumpIfToBooleanFalse();
  void BuildJumpIfNotHole();
  void BuildJumpIfJSReceiver();

  void BuildSwitchOnSmi(Node* condition);
  void BuildSwitchOnGeneratorState(
      const ZoneVector<ResumeJumpTarget>& resume_jump_targets,
      bool allow_fallthrough_on_executing);

  // Simulates control flow by forward-propagating environments.
  void MergeIntoSuccessorEnvironment(int target_offset);
  void BuildLoopHeaderEnvironment(int current_offset);
  void SwitchToMergeEnvironment(int current_offset);

  // Simulates control flow that exits the function body.
  void MergeControlToLeaveFunction(Node* exit);

  // Builds loop exit nodes for every exited loop between the current bytecode
  // offset and {target_offset}.
  void BuildLoopExitsForBranch(int target_offset);
  void BuildLoopExitsForFunctionExit(const BytecodeLivenessState* liveness);
  void BuildLoopExitsUntilLoop(int loop_offset,
                               const BytecodeLivenessState* liveness);

  // Helper for building a return (from an actual return or a suspend).
  void BuildReturn(const BytecodeLivenessState* liveness);

  // Simulates entry and exit of exception handlers.
  void ExitThenEnterExceptionHandlers(int current_offset);

  // Update the current position of the {SourcePositionTable} to that of the
  // bytecode at {offset}, if any.
293
  void UpdateSourcePosition(int offset);
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

  // Growth increment for the temporary buffer used to construct input lists to
  // new nodes.
  static const int kInputBufferSizeIncrement = 64;

  // An abstract representation for an exception handler that is being
  // entered and exited while the graph builder is iterating over the
  // underlying bytecode. The exception handlers within the bytecode are
  // well scoped, hence will form a stack during iteration.
  struct ExceptionHandler {
    int start_offset_;      // Start offset of the handled area in the bytecode.
    int end_offset_;        // End offset of the handled area in the bytecode.
    int handler_offset_;    // Handler entry offset within the bytecode.
    int context_register_;  // Index of register holding handler context.
  };

  // Field accessors
  Graph* graph() const { return jsgraph_->graph(); }
  CommonOperatorBuilder* common() const { return jsgraph_->common(); }
  Zone* graph_zone() const { return graph()->zone(); }
  JSGraph* jsgraph() const { return jsgraph_; }
  Isolate* isolate() const { return jsgraph_->isolate(); }
  JSOperatorBuilder* javascript() const { return jsgraph_->javascript(); }
  SimplifiedOperatorBuilder* simplified() const {
    return jsgraph_->simplified();
  }
  Zone* local_zone() const { return local_zone_; }
  const Handle<BytecodeArray>& bytecode_array() const {
    return bytecode_array_;
  }
  const Handle<FeedbackVector>& feedback_vector() const {
    return feedback_vector_;
  }
  const JSTypeHintLowering& type_hint_lowering() const {
    return type_hint_lowering_;
  }
  const FrameStateFunctionInfo* frame_state_function_info() const {
    return frame_state_function_info_;
  }

334 335
  SourcePositionTableIterator& source_position_iterator() {
    return source_position_iterator_;
336 337
  }

338 339
  interpreter::BytecodeArrayIterator& bytecode_iterator() {
    return bytecode_iterator_;
340 341
  }

342
  BytecodeAnalysis const& bytecode_analysis() const {
343 344 345
    return bytecode_analysis_;
  }

346
  void RunBytecodeAnalysis() { bytecode_analysis_.Analyze(osr_offset_); }
347 348 349 350 351 352 353 354 355

  int currently_peeled_loop_offset() const {
    return currently_peeled_loop_offset_;
  }

  void set_currently_peeled_loop_offset(int offset) {
    currently_peeled_loop_offset_ = offset;
  }

356
  bool skip_next_stack_check() const { return skip_next_stack_check_; }
357

358
  void unset_skip_next_stack_check() { skip_next_stack_check_ = false; }
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

  int current_exception_handler() { return current_exception_handler_; }

  void set_current_exception_handler(int index) {
    current_exception_handler_ = index;
  }

  bool needs_eager_checkpoint() const { return needs_eager_checkpoint_; }
  void mark_as_needing_eager_checkpoint(bool value) {
    needs_eager_checkpoint_ = value;
  }

  Handle<SharedFunctionInfo> shared_info() const { return shared_info_; }

  Handle<Context> native_context() const { return native_context_; }

375 376
  JSHeapBroker* broker() const { return broker_; }

377 378 379 380
#define DECLARE_VISIT_BYTECODE(name, ...) void Visit##name();
  BYTECODE_LIST(DECLARE_VISIT_BYTECODE)
#undef DECLARE_VISIT_BYTECODE

381
  JSHeapBroker* const broker_;
382 383
  Zone* const local_zone_;
  JSGraph* const jsgraph_;
384
  CallFrequency const invocation_frequency_;
385 386 387 388 389 390 391
  Handle<BytecodeArray> const bytecode_array_;
  Handle<FeedbackVector> const feedback_vector_;
  JSTypeHintLowering const type_hint_lowering_;
  const FrameStateFunctionInfo* const frame_state_function_info_;
  SourcePositionTableIterator source_position_iterator_;
  interpreter::BytecodeArrayIterator bytecode_iterator_;
  BytecodeAnalysis bytecode_analysis_;
392
  Environment* environment_;
393
  BailoutId const osr_offset_;
394
  int currently_peeled_loop_offset_;
395
  bool skip_next_stack_check_;
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

  // Merge environments are snapshots of the environment at points where the
  // control flow merges. This models a forward data flow propagation of all
  // values from all predecessors of the merge in question. They are indexed by
  // the bytecode offset
  ZoneMap<int, Environment*> merge_environments_;

  // Generator merge environments are snapshots of the current resume
  // environment, tracing back through loop headers to the resume switch of a
  // generator. They allow us to model a single resume jump as several switch
  // statements across loop headers, keeping those loop headers reducible,
  // without having to merge the "executing" environments of the generator into
  // the "resuming" ones. They are indexed by the suspend id of the resume.
  ZoneMap<int, Environment*> generator_merge_environments_;

  // Exception handlers currently entered by the iteration.
  ZoneStack<ExceptionHandler> exception_handlers_;
  int current_exception_handler_;

  // Temporary storage for building node input lists.
  int input_buffer_size_;
  Node** input_buffer_;

  // Optimization to only create checkpoints when the current position in the
  // control-flow is not effect-dominated by another checkpoint already. All
  // operations that do not have observable side-effects can be re-evaluated.
  bool needs_eager_checkpoint_;

  // Nodes representing values in the activation record.
  SetOncePointer<Node> function_closure_;

  // Control nodes that exit the function body.
  ZoneVector<Node*> exit_controls_;

  StateValuesCache state_values_cache_;

  // The source position table, to be populated.
433
  SourcePositionTable* const source_positions_;
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

  SourcePosition const start_position_;

  Handle<SharedFunctionInfo> const shared_info_;

  // The native context for which we optimize.
  Handle<Context> const native_context_;

  static int const kBinaryOperationHintIndex = 1;
  static int const kCountOperationHintIndex = 0;
  static int const kBinaryOperationSmiHintIndex = 1;
  static int const kUnaryOperationHintIndex = 0;

  DISALLOW_COPY_AND_ASSIGN(BytecodeGraphBuilder);
};

450 451 452 453 454 455
// The abstract execution environment simulates the content of the interpreter
// register file. The environment performs SSA-renaming of all tracked nodes at
// split and merge points in the control flow.
class BytecodeGraphBuilder::Environment : public ZoneObject {
 public:
  Environment(BytecodeGraphBuilder* builder, int register_count,
456 457 458
              int parameter_count,
              interpreter::Register incoming_new_target_or_generator,
              Node* control_dependency);
459

460 461 462 463 464
  // Specifies whether environment binding methods should attach frame state
  // inputs to nodes representing the value being bound. This is done because
  // the {OutputFrameStateCombine} is closely related to the binding method.
  enum FrameStateAttachmentMode { kAttachFrameState, kDontAttachFrameState };

465 466 467 468 469
  int parameter_count() const { return parameter_count_; }
  int register_count() const { return register_count_; }

  Node* LookupAccumulator() const;
  Node* LookupRegister(interpreter::Register the_register) const;
470
  Node* LookupGeneratorState() const;
471

472 473
  void BindAccumulator(Node* node,
                       FrameStateAttachmentMode mode = kDontAttachFrameState);
474
  void BindRegister(interpreter::Register the_register, Node* node,
475 476 477 478
                    FrameStateAttachmentMode mode = kDontAttachFrameState);
  void BindRegistersToProjections(
      interpreter::Register first_reg, Node* node,
      FrameStateAttachmentMode mode = kDontAttachFrameState);
479
  void BindGeneratorState(Node* node);
480 481
  void RecordAfterState(Node* node,
                        FrameStateAttachmentMode mode = kDontAttachFrameState);
482 483 484 485 486 487 488 489 490

  // Effect dependency tracked by this environment.
  Node* GetEffectDependency() { return effect_dependency_; }
  void UpdateEffectDependency(Node* dependency) {
    effect_dependency_ = dependency;
  }

  // Preserve a checkpoint of the environment for the IR graph. Any
  // further mutation of the environment will not affect checkpoints.
491
  Node* Checkpoint(BailoutId bytecode_offset, OutputFrameStateCombine combine,
492
                   const BytecodeLivenessState* liveness);
493 494 495 496 497 498 499 500 501 502

  // Control dependency tracked by this environment.
  Node* GetControlDependency() const { return control_dependency_; }
  void UpdateControlDependency(Node* dependency) {
    control_dependency_ = dependency;
  }

  Node* Context() const { return context_; }
  void SetContext(Node* new_context) { context_ = new_context; }

503
  Environment* Copy();
504
  void Merge(Environment* other, const BytecodeLivenessState* liveness);
505

506
  void FillWithOsrValues();
507 508
  void PrepareForLoop(const BytecodeLoopAssignments& assignments,
                      const BytecodeLivenessState* liveness);
509
  void PrepareForLoopExit(Node* loop,
510 511
                          const BytecodeLoopAssignments& assignments,
                          const BytecodeLivenessState* liveness);
512

513
 private:
514
  explicit Environment(const Environment* copy);
515

516 517
  bool StateValuesRequireUpdate(Node** state_values, Node** values, int count);
  void UpdateStateValues(Node** state_values, Node** values, int count);
518 519
  Node* GetStateValuesFromCache(Node** values, int count,
                                const BitVector* liveness, int liveness_offset);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

  int RegisterToValuesIndex(interpreter::Register the_register) const;

  Zone* zone() const { return builder_->local_zone(); }
  Graph* graph() const { return builder_->graph(); }
  CommonOperatorBuilder* common() const { return builder_->common(); }
  BytecodeGraphBuilder* builder() const { return builder_; }
  const NodeVector* values() const { return &values_; }
  NodeVector* values() { return &values_; }
  int register_base() const { return register_base_; }
  int accumulator_base() const { return accumulator_base_; }

  BytecodeGraphBuilder* builder_;
  int register_count_;
  int parameter_count_;
  Node* context_;
  Node* control_dependency_;
  Node* effect_dependency_;
  NodeVector values_;
  Node* parameters_state_values_;
540
  Node* generator_state_;
541 542 543 544
  int register_base_;
  int accumulator_base_;
};

545 546 547 548 549 550 551 552 553 554 555 556
// A helper for creating a temporary sub-environment for simple branches.
struct BytecodeGraphBuilder::SubEnvironment final {
 public:
  explicit SubEnvironment(BytecodeGraphBuilder* builder)
      : builder_(builder), parent_(builder->environment()->Copy()) {}

  ~SubEnvironment() { builder_->set_environment(parent_); }

 private:
  BytecodeGraphBuilder* builder_;
  BytecodeGraphBuilder::Environment* parent_;
};
557

558 559 560
// Issues:
// - Scopes - intimately tied to AST. Need to eval what is needed.
// - Need to resolve closure parameter treatment.
561 562 563 564
BytecodeGraphBuilder::Environment::Environment(
    BytecodeGraphBuilder* builder, int register_count, int parameter_count,
    interpreter::Register incoming_new_target_or_generator,
    Node* control_dependency)
565 566 567 568 569
    : builder_(builder),
      register_count_(register_count),
      parameter_count_(parameter_count),
      control_dependency_(control_dependency),
      effect_dependency_(control_dependency),
570
      values_(builder->local_zone()),
571 572
      parameters_state_values_(nullptr),
      generator_state_(nullptr) {
573 574
  // The layout of values_ is:
  //
575
  // [receiver] [parameters] [registers] [accumulator]
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  //
  // parameter[0] is the receiver (this), parameters 1..N are the
  // parameters supplied to the method (arg0..argN-1). The accumulator
  // is stored separately.

  // Parameters including the receiver
  for (int i = 0; i < parameter_count; i++) {
    const char* debug_name = (i == 0) ? "%this" : nullptr;
    const Operator* op = common()->Parameter(i, debug_name);
    Node* parameter = builder->graph()->NewNode(op, graph()->start());
    values()->push_back(parameter);
  }

  // Registers
  register_base_ = static_cast<int>(values()->size());
  Node* undefined_constant = builder->jsgraph()->UndefinedConstant();
  values()->insert(values()->end(), register_count, undefined_constant);

  // Accumulator
595 596
  accumulator_base_ = static_cast<int>(values()->size());
  values()->push_back(undefined_constant);
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

  // Context
  int context_index = Linkage::GetJSCallContextParamIndex(parameter_count);
  const Operator* op = common()->Parameter(context_index, "%context");
  context_ = builder->graph()->NewNode(op, graph()->start());

  // Incoming new.target or generator register
  if (incoming_new_target_or_generator.is_valid()) {
    int new_target_index =
        Linkage::GetJSCallNewTargetParamIndex(parameter_count);
    const Operator* op = common()->Parameter(new_target_index, "%new.target");
    Node* new_target_node = builder->graph()->NewNode(op, graph()->start());

    int values_index = RegisterToValuesIndex(incoming_new_target_or_generator);
    values()->at(values_index) = new_target_node;
  }
613 614
}

615
BytecodeGraphBuilder::Environment::Environment(
616
    const BytecodeGraphBuilder::Environment* other)
617 618 619 620 621 622 623
    : builder_(other->builder_),
      register_count_(other->register_count_),
      parameter_count_(other->parameter_count_),
      context_(other->context_),
      control_dependency_(other->control_dependency_),
      effect_dependency_(other->effect_dependency_),
      values_(other->zone()),
624
      parameters_state_values_(other->parameters_state_values_),
625
      generator_state_(other->generator_state_),
626
      register_base_(other->register_base_),
627
      accumulator_base_(other->accumulator_base_) {
628 629 630 631
  values_ = other->values_;
}


632 633 634 635 636 637 638 639 640
int BytecodeGraphBuilder::Environment::RegisterToValuesIndex(
    interpreter::Register the_register) const {
  if (the_register.is_parameter()) {
    return the_register.ToParameterIndex(parameter_count());
  } else {
    return the_register.index() + register_base();
  }
}

641 642
Node* BytecodeGraphBuilder::Environment::LookupAccumulator() const {
  return values()->at(accumulator_base_);
643 644
}

645 646 647 648
Node* BytecodeGraphBuilder::Environment::LookupGeneratorState() const {
  DCHECK_NOT_NULL(generator_state_);
  return generator_state_;
}
649 650 651

Node* BytecodeGraphBuilder::Environment::LookupRegister(
    interpreter::Register the_register) const {
652 653
  if (the_register.is_current_context()) {
    return Context();
654 655 656 657 658 659
  } else if (the_register.is_function_closure()) {
    return builder()->GetFunctionClosure();
  } else {
    int values_index = RegisterToValuesIndex(the_register);
    return values()->at(values_index);
  }
660 661
}

662
void BytecodeGraphBuilder::Environment::BindAccumulator(
663 664 665
    Node* node, FrameStateAttachmentMode mode) {
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(0));
666 667 668 669
  }
  values()->at(accumulator_base_) = node;
}

670 671 672 673
void BytecodeGraphBuilder::Environment::BindGeneratorState(Node* node) {
  generator_state_ = node;
}

674 675
void BytecodeGraphBuilder::Environment::BindRegister(
    interpreter::Register the_register, Node* node,
676
    FrameStateAttachmentMode mode) {
677
  int values_index = RegisterToValuesIndex(the_register);
678 679 680
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(
                                           accumulator_base_ - values_index));
681 682
  }
  values()->at(values_index) = node;
683 684
}

685 686
void BytecodeGraphBuilder::Environment::BindRegistersToProjections(
    interpreter::Register first_reg, Node* node,
687
    FrameStateAttachmentMode mode) {
688
  int values_index = RegisterToValuesIndex(first_reg);
689 690 691
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(
                                           accumulator_base_ - values_index));
692 693 694 695 696
  }
  for (int i = 0; i < node->op()->ValueOutputCount(); i++) {
    values()->at(values_index + i) =
        builder()->NewNode(common()->Projection(i), node);
  }
697 698
}

699
void BytecodeGraphBuilder::Environment::RecordAfterState(
700 701 702 703
    Node* node, FrameStateAttachmentMode mode) {
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::Ignore());
  }
704 705
}

706
BytecodeGraphBuilder::Environment* BytecodeGraphBuilder::Environment::Copy() {
707
  return new (zone()) Environment(this);
708 709 710
}

void BytecodeGraphBuilder::Environment::Merge(
711 712
    BytecodeGraphBuilder::Environment* other,
    const BytecodeLivenessState* liveness) {
713 714 715 716 717 718 719 720 721 722 723 724
  // Create a merge of the control dependencies of both environments and update
  // the current environment's control dependency accordingly.
  Node* control = builder()->MergeControl(GetControlDependency(),
                                          other->GetControlDependency());
  UpdateControlDependency(control);

  // Create a merge of the effect dependencies of both environments and update
  // the current environment's effect dependency accordingly.
  Node* effect = builder()->MergeEffect(GetEffectDependency(),
                                        other->GetEffectDependency(), control);
  UpdateEffectDependency(effect);

725 726
  // Introduce Phi nodes for values that are live and have differing inputs at
  // the merge point, potentially extending an existing Phi node if possible.
727
  context_ = builder()->MergeValue(context_, other->context_, control);
728
  for (int i = 0; i < parameter_count(); i++) {
729 730
    values_[i] = builder()->MergeValue(values_[i], other->values_[i], control);
  }
731 732 733
  for (int i = 0; i < register_count(); i++) {
    int index = register_base() + i;
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
734 735 736 737 738 739 740 741 742 743 744 745
#if DEBUG
      // We only do these DCHECKs when we are not in the resume path of a
      // generator -- this is, when either there is no generator state at all,
      // or the generator state is not the constant "executing" value.
      if (generator_state_ == nullptr ||
          NumberMatcher(generator_state_)
              .Is(JSGeneratorObject::kGeneratorExecuting)) {
        DCHECK_NE(values_[index], builder()->jsgraph()->OptimizedOutConstant());
        DCHECK_NE(other->values_[index],
                  builder()->jsgraph()->OptimizedOutConstant());
      }
#endif
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766

      values_[index] =
          builder()->MergeValue(values_[index], other->values_[index], control);

    } else {
      values_[index] = builder()->jsgraph()->OptimizedOutConstant();
    }
  }

  if (liveness == nullptr || liveness->AccumulatorIsLive()) {
    DCHECK_NE(values_[accumulator_base()],
              builder()->jsgraph()->OptimizedOutConstant());
    DCHECK_NE(other->values_[accumulator_base()],
              builder()->jsgraph()->OptimizedOutConstant());

    values_[accumulator_base()] =
        builder()->MergeValue(values_[accumulator_base()],
                              other->values_[accumulator_base()], control);
  } else {
    values_[accumulator_base()] = builder()->jsgraph()->OptimizedOutConstant();
  }
767 768 769 770 771 772

  if (generator_state_ != nullptr) {
    DCHECK_NOT_NULL(other->generator_state_);
    generator_state_ = builder()->MergeValue(generator_state_,
                                             other->generator_state_, control);
  }
773 774
}

775
void BytecodeGraphBuilder::Environment::PrepareForLoop(
776 777
    const BytecodeLoopAssignments& assignments,
    const BytecodeLivenessState* liveness) {
778 779 780 781 782 783 784
  // Create a control node for the loop header.
  Node* control = builder()->NewLoop();

  // Create a Phi for external effects.
  Node* effect = builder()->NewEffectPhi(1, GetEffectDependency(), control);
  UpdateEffectDependency(effect);

785 786
  // Create Phis for any values that are live on entry to the loop and may be
  // updated by the end of the loop.
787
  context_ = builder()->NewPhi(1, context_, control);
788 789 790 791 792 793
  for (int i = 0; i < parameter_count(); i++) {
    if (assignments.ContainsParameter(i)) {
      values_[i] = builder()->NewPhi(1, values_[i], control);
    }
  }
  for (int i = 0; i < register_count(); i++) {
794 795
    if (assignments.ContainsLocal(i) &&
        (liveness == nullptr || liveness->RegisterIsLive(i))) {
796 797 798 799
      int index = register_base() + i;
      values_[index] = builder()->NewPhi(1, values_[index], control);
    }
  }
800 801
  // The accumulator should not be live on entry.
  DCHECK_IMPLIES(liveness != nullptr, !liveness->AccumulatorIsLive());
802

803 804 805 806
  if (generator_state_ != nullptr) {
    generator_state_ = builder()->NewPhi(1, generator_state_, control);
  }

807 808 809 810 811 812
  // Connect to the loop end.
  Node* terminate = builder()->graph()->NewNode(
      builder()->common()->Terminate(), effect, control);
  builder()->exit_controls_.push_back(terminate);
}

813
void BytecodeGraphBuilder::Environment::FillWithOsrValues() {
814 815
  Node* start = graph()->start();

816 817
  // Create OSR values for each environment value.
  SetContext(graph()->NewNode(
818
      common()->OsrValue(Linkage::kOsrContextSpillSlotIndex), start));
819 820 821 822 823
  int size = static_cast<int>(values()->size());
  for (int i = 0; i < size; i++) {
    int idx = i;  // Indexing scheme follows {StandardFrame}, adapt accordingly.
    if (i >= register_base()) idx += InterpreterFrameConstants::kExtraSlotCount;
    if (i >= accumulator_base()) idx = Linkage::kOsrAccumulatorRegisterIndex;
824
    values()->at(i) = graph()->NewNode(common()->OsrValue(idx), start);
825 826
  }
}
827

828
bool BytecodeGraphBuilder::Environment::StateValuesRequireUpdate(
829
    Node** state_values, Node** values, int count) {
830 831
  if (*state_values == nullptr) {
    return true;
832
  }
833
  Node::Inputs inputs = (*state_values)->inputs();
834
  if (inputs.count() != count) return true;
835
  for (int i = 0; i < count; i++) {
836
    if (inputs[i] != values[i]) {
837
      return true;
838 839 840 841 842
    }
  }
  return false;
}

843
void BytecodeGraphBuilder::Environment::PrepareForLoopExit(
844 845
    Node* loop, const BytecodeLoopAssignments& assignments,
    const BytecodeLivenessState* liveness) {
846 847 848 849 850 851 852 853 854 855 856 857 858
  DCHECK_EQ(loop->opcode(), IrOpcode::kLoop);

  Node* control = GetControlDependency();

  // Create the loop exit node.
  Node* loop_exit = graph()->NewNode(common()->LoopExit(), control, loop);
  UpdateControlDependency(loop_exit);

  // Rename the effect.
  Node* effect_rename = graph()->NewNode(common()->LoopExitEffect(),
                                         GetEffectDependency(), loop_exit);
  UpdateEffectDependency(effect_rename);

859
  // TODO(jarin) We should also rename context here. However, unconditional
860 861
  // renaming confuses global object and native context specialization.
  // We should only rename if the context is assigned in the loop.
862

863 864
  // Rename the environment values if they were assigned in the loop and are
  // live after exiting the loop.
865 866 867 868 869 870 871 872
  for (int i = 0; i < parameter_count(); i++) {
    if (assignments.ContainsParameter(i)) {
      Node* rename =
          graph()->NewNode(common()->LoopExitValue(), values_[i], loop_exit);
      values_[i] = rename;
    }
  }
  for (int i = 0; i < register_count(); i++) {
873 874
    if (assignments.ContainsLocal(i) &&
        (liveness == nullptr || liveness->RegisterIsLive(i))) {
875 876 877 878 879
      Node* rename = graph()->NewNode(common()->LoopExitValue(),
                                      values_[register_base() + i], loop_exit);
      values_[register_base() + i] = rename;
    }
  }
880 881 882 883 884
  if (liveness == nullptr || liveness->AccumulatorIsLive()) {
    Node* rename = graph()->NewNode(common()->LoopExitValue(),
                                    values_[accumulator_base()], loop_exit);
    values_[accumulator_base()] = rename;
  }
885 886 887 888 889

  if (generator_state_ != nullptr) {
    generator_state_ = graph()->NewNode(common()->LoopExitValue(),
                                        generator_state_, loop_exit);
  }
890
}
891 892

void BytecodeGraphBuilder::Environment::UpdateStateValues(Node** state_values,
893
                                                          Node** values,
894
                                                          int count) {
895
  if (StateValuesRequireUpdate(state_values, values, count)) {
896
    const Operator* op = common()->StateValues(count, SparseInputMask::Dense());
897
    (*state_values) = graph()->NewNode(op, count, values);
898 899 900
  }
}

901 902 903
Node* BytecodeGraphBuilder::Environment::GetStateValuesFromCache(
    Node** values, int count, const BitVector* liveness, int liveness_offset) {
  return builder_->state_values_cache_.GetNodeForValues(
904
      values, static_cast<size_t>(count), liveness, liveness_offset);
905 906
}

907
Node* BytecodeGraphBuilder::Environment::Checkpoint(
908
    BailoutId bailout_id, OutputFrameStateCombine combine,
909
    const BytecodeLivenessState* liveness) {
910 911 912
  if (parameter_count() == register_count()) {
    // Re-use the state-value cache if the number of local registers happens
    // to match the parameter count.
913 914
    parameters_state_values_ = GetStateValuesFromCache(
        &values()->at(0), parameter_count(), nullptr, 0);
915 916 917 918
  } else {
    UpdateStateValues(&parameters_state_values_, &values()->at(0),
                      parameter_count());
  }
919

920 921 922
  Node* registers_state_values =
      GetStateValuesFromCache(&values()->at(register_base()), register_count(),
                              liveness ? &liveness->bit_vector() : nullptr, 0);
923 924

  bool accumulator_is_live = !liveness || liveness->AccumulatorIsLive();
925
  Node* accumulator_state_value =
926 927 928
      accumulator_is_live && combine != OutputFrameStateCombine::PokeAt(0)
          ? values()->at(accumulator_base())
          : builder()->jsgraph()->OptimizedOutConstant();
929 930 931 932

  const Operator* op = common()->FrameState(
      bailout_id, combine, builder()->frame_state_function_info());
  Node* result = graph()->NewNode(
933
      op, parameters_state_values_, registers_state_values,
934
      accumulator_state_value, Context(), builder()->GetFunctionClosure(),
935 936 937 938 939
      builder()->graph()->start());

  return result;
}

940
BytecodeGraphBuilder::BytecodeGraphBuilder(
941 942
    JSHeapBroker* broker, Zone* local_zone,
    Handle<BytecodeArray> bytecode_array,
943
    Handle<SharedFunctionInfo> shared_info,
944
    Handle<FeedbackVector> feedback_vector, BailoutId osr_offset,
945
    JSGraph* jsgraph, CallFrequency const& invocation_frequency,
946
    SourcePositionTable* source_positions, Handle<Context> native_context,
947
    int inlining_id, BytecodeGraphBuilderFlags flags)
948 949
    : broker_(broker),
      local_zone_(local_zone),
950
      jsgraph_(jsgraph),
951
      invocation_frequency_(invocation_frequency),
952
      bytecode_array_(bytecode_array),
953
      feedback_vector_(feedback_vector),
954 955 956 957 958
      type_hint_lowering_(
          jsgraph, feedback_vector,
          (flags & BytecodeGraphBuilderFlag::kBailoutOnUninitialized)
              ? JSTypeHintLowering::kBailoutOnUninitialized
              : JSTypeHintLowering::kNoFlags),
959 960
      frame_state_function_info_(common()->CreateFrameStateFunctionInfo(
          FrameStateType::kInterpretedFunction,
961 962
          bytecode_array->parameter_count(), bytecode_array->register_count(),
          shared_info)),
963 964 965
      source_position_iterator_(
          handle(bytecode_array->SourcePositionTableIfCollected(), isolate())),
      bytecode_iterator_(bytecode_array),
966 967 968
      bytecode_analysis_(
          bytecode_array, local_zone,
          flags & BytecodeGraphBuilderFlag::kAnalyzeEnvironmentLiveness),
969
      environment_(nullptr),
970
      osr_offset_(osr_offset),
971
      currently_peeled_loop_offset_(-1),
972 973
      skip_next_stack_check_(flags &
                             BytecodeGraphBuilderFlag::kSkipFirstStackCheck),
974
      merge_environments_(local_zone),
975
      generator_merge_environments_(local_zone),
976 977
      exception_handlers_(local_zone),
      current_exception_handler_(0),
978 979
      input_buffer_size_(0),
      input_buffer_(nullptr),
980
      needs_eager_checkpoint_(true),
981 982
      exit_controls_(local_zone),
      state_values_cache_(jsgraph),
983
      source_positions_(source_positions),
984
      start_position_(shared_info->StartPosition(), inlining_id),
985
      shared_info_(shared_info),
986
      native_context_(native_context) {}
987

988 989
Node* BytecodeGraphBuilder::GetFunctionClosure() {
  if (!function_closure_.is_set()) {
990 991
    int index = Linkage::kJSCallClosureParamIndex;
    const Operator* op = common()->Parameter(index, "%closure");
992 993 994 995 996 997
    Node* node = NewNode(op, graph()->start());
    function_closure_.set(node);
  }
  return function_closure_.get();
}

998
Node* BytecodeGraphBuilder::BuildLoadNativeContextField(int index) {
999
  Node* result = NewNode(javascript()->LoadContext(0, index, true));
1000 1001
  NodeProperties::ReplaceContextInput(
      result, jsgraph()->HeapConstant(native_context()));
1002
  return result;
1003 1004
}

1005
VectorSlotPair BytecodeGraphBuilder::CreateVectorSlotPair(int slot_id) {
1006 1007 1008
  FeedbackSlot slot = FeedbackVector::ToSlot(slot_id);
  FeedbackNexus nexus(feedback_vector(), slot);
  return VectorSlotPair(feedback_vector(), slot, nexus.ic_state());
1009 1010
}

1011
void BytecodeGraphBuilder::CreateGraph() {
1012 1013
  BytecodeArrayRef bytecode_array_ref(broker(), bytecode_array());

1014 1015
  SourcePositionTable::Scope pos_scope(source_positions_, start_position_);

1016
  // Set up the basic structure of the graph. Outputs for {Start} are the formal
1017 1018
  // parameters (including the receiver) plus new target, number of arguments,
  // context and closure.
1019
  int actual_parameter_count = bytecode_array_ref.parameter_count() + 4;
1020 1021
  graph()->SetStart(graph()->NewNode(common()->Start(actual_parameter_count)));

1022 1023 1024 1025 1026
  Environment env(
      this, bytecode_array_ref.register_count(),
      bytecode_array_ref.parameter_count(),
      bytecode_array_ref.incoming_new_target_or_generator_register(),
      graph()->start());
1027 1028
  set_environment(&env);

1029
  VisitBytecodes();
1030 1031 1032 1033 1034 1035 1036 1037 1038

  // Finish the basic structure of the graph.
  DCHECK_NE(0u, exit_controls_.size());
  int const input_count = static_cast<int>(exit_controls_.size());
  Node** const inputs = &exit_controls_.front();
  Node* end = graph()->NewNode(common()->End(input_count), input_count, inputs);
  graph()->SetEnd(end);
}

1039
void BytecodeGraphBuilder::PrepareEagerCheckpoint() {
1040
  if (needs_eager_checkpoint()) {
1041 1042
    // Create an explicit checkpoint node for before the operation. This only
    // needs to happen if we aren't effect-dominated by a {Checkpoint} already.
1043
    mark_as_needing_eager_checkpoint(false);
1044 1045 1046 1047
    Node* node = NewNode(common()->Checkpoint());
    DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
    DCHECK_EQ(IrOpcode::kDead,
              NodeProperties::GetFrameStateInput(node)->opcode());
1048
    BailoutId bailout_id(bytecode_iterator().current_offset());
1049

1050
    const BytecodeLivenessState* liveness_before =
1051
        bytecode_analysis().GetInLivenessFor(
1052
            bytecode_iterator().current_offset());
1053

1054
    Node* frame_state_before = environment()->Checkpoint(
1055
        bailout_id, OutputFrameStateCombine::Ignore(), liveness_before);
1056
    NodeProperties::ReplaceFrameStateInput(node, frame_state_before);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
#ifdef DEBUG
  } else {
    // In case we skipped checkpoint creation above, we must be able to find an
    // existing checkpoint that effect-dominates the nodes about to be created.
    // Starting a search from the current effect-dependency has to succeed.
    Node* effect = environment()->GetEffectDependency();
    while (effect->opcode() != IrOpcode::kCheckpoint) {
      DCHECK(effect->op()->HasProperty(Operator::kNoWrite));
      DCHECK_EQ(1, effect->op()->EffectInputCount());
      effect = NodeProperties::GetEffectInput(effect);
    }
  }
#else
1070
  }
1071
#endif  // DEBUG
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
}

void BytecodeGraphBuilder::PrepareFrameState(Node* node,
                                             OutputFrameStateCombine combine) {
  if (OperatorProperties::HasFrameStateInput(node->op())) {
    // Add the frame state for after the operation. The node in question has
    // already been created and had a {Dead} frame state input up until now.
    DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
    DCHECK_EQ(IrOpcode::kDead,
              NodeProperties::GetFrameStateInput(node)->opcode());
1082
    BailoutId bailout_id(bytecode_iterator().current_offset());
1083

1084
    const BytecodeLivenessState* liveness_after =
1085
        bytecode_analysis().GetOutLivenessFor(
1086
            bytecode_iterator().current_offset());
1087

1088 1089
    Node* frame_state_after =
        environment()->Checkpoint(bailout_id, combine, liveness_after);
1090
    NodeProperties::ReplaceFrameStateInput(node, frame_state_after);
1091 1092 1093
  }
}

1094 1095 1096 1097 1098 1099 1100
void BytecodeGraphBuilder::AdvanceIteratorsTo(int bytecode_offset) {
  for (; bytecode_iterator().current_offset() != bytecode_offset;
       bytecode_iterator().Advance()) {
    UpdateSourcePosition(bytecode_iterator().current_offset());
  }
}

1101 1102 1103 1104 1105 1106 1107 1108
// Stores the state of the SourcePosition iterator, and the index to the
// current exception handlers stack. We need, during the OSR graph generation,
// to backup the states of these iterators at the LoopHeader offset of each
// outer loop which contains the OSR loop. The iterators are then restored when
// peeling the loops, so that both exception handling and synchronisation with
// the source position can be achieved.
class BytecodeGraphBuilder::OsrIteratorState {
 public:
1109 1110
  explicit OsrIteratorState(BytecodeGraphBuilder* graph_builder)
      : graph_builder_(graph_builder),
1111 1112 1113 1114
        saved_states_(graph_builder->local_zone()) {}

  void ProcessOsrPrelude() {
    ZoneVector<int> outer_loop_offsets(graph_builder_->local_zone());
1115 1116
    BytecodeAnalysis const& bytecode_analysis =
        graph_builder_->bytecode_analysis();
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    int osr_offset = bytecode_analysis.osr_entry_point();

    // We find here the outermost loop which contains the OSR loop.
    int outermost_loop_offset = osr_offset;
    while ((outermost_loop_offset =
                bytecode_analysis.GetLoopInfoFor(outermost_loop_offset)
                    .parent_offset()) != -1) {
      outer_loop_offsets.push_back(outermost_loop_offset);
    }
    outermost_loop_offset =
        outer_loop_offsets.empty() ? osr_offset : outer_loop_offsets.back();
1128
    graph_builder_->AdvanceIteratorsTo(outermost_loop_offset);
1129 1130 1131 1132 1133 1134 1135

    // We save some iterators states at the offsets of the loop headers of the
    // outer loops (the ones containing the OSR loop). They will be used for
    // jumping back in the bytecode.
    for (ZoneVector<int>::const_reverse_iterator it =
             outer_loop_offsets.crbegin();
         it != outer_loop_offsets.crend(); ++it) {
1136
      graph_builder_->AdvanceIteratorsTo(*it);
1137
      graph_builder_->ExitThenEnterExceptionHandlers(
1138 1139 1140 1141
          graph_builder_->bytecode_iterator().current_offset());
      saved_states_.push(IteratorsStates(
          graph_builder_->current_exception_handler(),
          graph_builder_->source_position_iterator().GetState()));
1142 1143 1144
    }

    // Finishing by advancing to the OSR entry
1145
    graph_builder_->AdvanceIteratorsTo(osr_offset);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

    // Enters all remaining exception handler which end before the OSR loop
    // so that on next call of VisitSingleBytecode they will get popped from
    // the exception handlers stack.
    graph_builder_->ExitThenEnterExceptionHandlers(osr_offset);
    graph_builder_->set_currently_peeled_loop_offset(
        bytecode_analysis.GetLoopInfoFor(osr_offset).parent_offset());
  }

  void RestoreState(int target_offset, int new_parent_offset) {
1156
    graph_builder_->bytecode_iterator().SetOffset(target_offset);
1157 1158 1159 1160
    // In case of a return, we must not build loop exits for
    // not-yet-built outer loops.
    graph_builder_->set_currently_peeled_loop_offset(new_parent_offset);
    IteratorsStates saved_state = saved_states_.top();
1161 1162
    graph_builder_->source_position_iterator().RestoreState(
        saved_state.source_iterator_state_);
1163 1164 1165 1166 1167 1168 1169 1170
    graph_builder_->set_current_exception_handler(
        saved_state.exception_handler_index_);
    saved_states_.pop();
  }

 private:
  struct IteratorsStates {
    int exception_handler_index_;
1171
    SourcePositionTableIterator::IndexAndPositionState source_iterator_state_;
1172

1173 1174 1175
    IteratorsStates(int exception_handler_index,
                    SourcePositionTableIterator::IndexAndPositionState
                        source_iterator_state)
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        : exception_handler_index_(exception_handler_index),
          source_iterator_state_(source_iterator_state) {}
  };

  BytecodeGraphBuilder* graph_builder_;
  ZoneStack<IteratorsStates> saved_states_;
};

void BytecodeGraphBuilder::RemoveMergeEnvironmentsBeforeOffset(
    int limit_offset) {
  if (!merge_environments_.empty()) {
    ZoneMap<int, Environment*>::iterator it = merge_environments_.begin();
    ZoneMap<int, Environment*>::iterator stop_it = merge_environments_.end();
    while (it != stop_it && it->first <= limit_offset) {
      it = merge_environments_.erase(it);
    }
  }
}

// We will iterate through the OSR loop, then its parent, and so on
// until we have reached the outmost loop containing the OSR loop. We do
// not generate nodes for anything before the outermost loop.
1198 1199
void BytecodeGraphBuilder::AdvanceToOsrEntryAndPeelLoops() {
  OsrIteratorState iterator_states(this);
1200
  iterator_states.ProcessOsrPrelude();
1201 1202
  int osr_offset = bytecode_analysis().osr_entry_point();
  DCHECK_EQ(bytecode_iterator().current_offset(), osr_offset);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

  environment()->FillWithOsrValues();

  // Suppose we have n nested loops, loop_0 being the outermost one, and
  // loop_n being the OSR loop. We start iterating the bytecode at the header
  // of loop_n (the OSR loop), and then we peel the part of the the body of
  // loop_{n-1} following the end of loop_n. We then rewind the iterator to
  // the header of loop_{n-1}, and so on until we have partly peeled loop 0.
  // The full loop_0 body will be generating with the rest of the function,
  // outside the OSR generation.

  // To do so, if we are visiting a loop, we continue to visit what's left
  // of its parent, and then when reaching the parent's JumpLoop, we do not
  // create any jump for that but rewind the bytecode iterator to visit the
  // parent loop entirely, and so on.

  int current_parent_offset =
1220
      bytecode_analysis().GetLoopInfoFor(osr_offset).parent_offset();
1221
  while (current_parent_offset != -1) {
1222
    const LoopInfo& current_parent_loop =
1223
        bytecode_analysis().GetLoopInfoFor(current_parent_offset);
1224 1225
    // We iterate until the back edge of the parent loop, which we detect by
    // the offset that the JumpLoop targets.
1226 1227 1228 1229
    for (; !bytecode_iterator().done(); bytecode_iterator().Advance()) {
      if (bytecode_iterator().current_bytecode() ==
              interpreter::Bytecode::kJumpLoop &&
          bytecode_iterator().GetJumpTargetOffset() == current_parent_offset) {
1230 1231 1232
        // Reached the end of the current parent loop.
        break;
      }
1233
      VisitSingleBytecode();
1234
    }
1235 1236
    DCHECK(!bytecode_iterator()
                .done());  // Should have found the loop's jump target.
1237 1238 1239 1240

    // We also need to take care of the merge environments and exceptions
    // handlers here because the omitted JumpLoop bytecode can still be the
    // target of jumps or the first bytecode after a try block.
1241 1242
    ExitThenEnterExceptionHandlers(bytecode_iterator().current_offset());
    SwitchToMergeEnvironment(bytecode_iterator().current_offset());
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

    // This jump is the jump of our parent loop, which is not yet created.
    // So we do not build the jump nodes, but restore the bytecode and the
    // SourcePosition iterators to the values they had when we were visiting
    // the offset pointed at by the JumpLoop we've just reached.
    // We have already built nodes for inner loops, but now we will
    // iterate again over them and build new nodes corresponding to the same
    // bytecode offsets. Any jump or reference to this inner loops must now
    // point to the new nodes we will build, hence we clear the relevant part
    // of the environment.
    // Completely clearing the environment is not possible because merge
    // environments for forward jumps out of the loop need to be preserved
    // (e.g. a return or a labeled break in the middle of a loop).
1256
    RemoveMergeEnvironmentsBeforeOffset(bytecode_iterator().current_offset());
1257 1258 1259 1260 1261 1262
    iterator_states.RestoreState(current_parent_offset,
                                 current_parent_loop.parent_offset());
    current_parent_offset = current_parent_loop.parent_offset();
  }
}

1263 1264 1265
void BytecodeGraphBuilder::VisitSingleBytecode() {
  int current_offset = bytecode_iterator().current_offset();
  UpdateSourcePosition(current_offset);
1266 1267 1268 1269 1270 1271 1272 1273
  ExitThenEnterExceptionHandlers(current_offset);
  DCHECK_GE(exception_handlers_.empty() ? current_offset
                                        : exception_handlers_.top().end_offset_,
            current_offset);
  SwitchToMergeEnvironment(current_offset);

  if (environment() != nullptr) {
    BuildLoopHeaderEnvironment(current_offset);
1274 1275 1276
    if (skip_next_stack_check() && bytecode_iterator().current_bytecode() ==
                                       interpreter::Bytecode::kStackCheck) {
      unset_skip_next_stack_check();
1277 1278 1279
      return;
    }

1280
    switch (bytecode_iterator().current_bytecode()) {
1281 1282 1283 1284 1285
#define BYTECODE_CASE(name, ...)       \
  case interpreter::Bytecode::k##name: \
    Visit##name();                     \
    break;
      BYTECODE_LIST(BYTECODE_CASE)
1286
#undef BYTECODE_CASE
1287 1288 1289 1290 1291
    }
  }
}

void BytecodeGraphBuilder::VisitBytecodes() {
1292
  RunBytecodeAnalysis();
1293

1294
  if (!bytecode_analysis().resume_jump_targets().empty()) {
1295 1296 1297 1298
    environment()->BindGeneratorState(
        jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
  }

1299
  if (bytecode_analysis().HasOsrEntryPoint()) {
1300 1301 1302 1303
    // We peel the OSR loop and any outer loop containing it except that we
    // leave the nodes corresponding to the whole outermost loop (including
    // the last copies of the loops it contains) to be generated by the normal
    // bytecode iteration below.
1304
    AdvanceToOsrEntryAndPeelLoops();
1305
  }
1306

1307
  bool has_one_shot_bytecode = false;
1308
  for (; !bytecode_iterator().done(); bytecode_iterator().Advance()) {
1309
    if (interpreter::Bytecodes::IsOneShotBytecode(
1310
            bytecode_iterator().current_bytecode())) {
1311 1312
      has_one_shot_bytecode = true;
    }
1313
    VisitSingleBytecode();
1314
  }
1315 1316 1317 1318 1319 1320

  if (has_one_shot_bytecode) {
    isolate()->CountUsage(
        v8::Isolate::UseCounterFeature::kOptimizedFunctionWithOneShotBytecode);
  }

1321
  DCHECK(exception_handlers_.empty());
1322 1323
}

1324
void BytecodeGraphBuilder::VisitLdaZero() {
1325 1326 1327 1328
  Node* node = jsgraph()->ZeroConstant();
  environment()->BindAccumulator(node);
}

1329
void BytecodeGraphBuilder::VisitLdaSmi() {
1330
  Node* node = jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
1331 1332 1333
  environment()->BindAccumulator(node);
}

1334
void BytecodeGraphBuilder::VisitLdaConstant() {
1335 1336
  Node* node = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1337 1338 1339
  environment()->BindAccumulator(node);
}

1340
void BytecodeGraphBuilder::VisitLdaUndefined() {
1341 1342 1343 1344
  Node* node = jsgraph()->UndefinedConstant();
  environment()->BindAccumulator(node);
}

1345
void BytecodeGraphBuilder::VisitLdaNull() {
1346 1347 1348 1349
  Node* node = jsgraph()->NullConstant();
  environment()->BindAccumulator(node);
}

1350
void BytecodeGraphBuilder::VisitLdaTheHole() {
1351 1352 1353 1354
  Node* node = jsgraph()->TheHoleConstant();
  environment()->BindAccumulator(node);
}

1355
void BytecodeGraphBuilder::VisitLdaTrue() {
1356 1357 1358 1359
  Node* node = jsgraph()->TrueConstant();
  environment()->BindAccumulator(node);
}

1360
void BytecodeGraphBuilder::VisitLdaFalse() {
1361 1362 1363 1364
  Node* node = jsgraph()->FalseConstant();
  environment()->BindAccumulator(node);
}

1365 1366 1367
void BytecodeGraphBuilder::VisitLdar() {
  Node* value =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1368 1369 1370
  environment()->BindAccumulator(value);
}

1371
void BytecodeGraphBuilder::VisitStar() {
1372
  Node* value = environment()->LookupAccumulator();
1373
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), value);
1374 1375
}

1376 1377 1378 1379
void BytecodeGraphBuilder::VisitMov() {
  Node* value =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(1), value);
1380 1381
}

1382 1383
Node* BytecodeGraphBuilder::BuildLoadGlobal(Handle<Name> name,
                                            uint32_t feedback_slot_index,
1384 1385
                                            TypeofMode typeof_mode) {
  VectorSlotPair feedback = CreateVectorSlotPair(feedback_slot_index);
1386
  DCHECK(IsLoadGlobalICKind(feedback_vector()->GetKind(feedback.slot())));
1387
  const Operator* op = javascript()->LoadGlobal(name, feedback, typeof_mode);
1388
  return NewNode(op);
1389 1390
}

1391
void BytecodeGraphBuilder::VisitLdaGlobal() {
1392
  PrepareEagerCheckpoint();
1393 1394
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
1395 1396 1397
  uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
  Node* node =
      BuildLoadGlobal(name, feedback_slot_index, TypeofMode::NOT_INSIDE_TYPEOF);
1398
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1399 1400
}

1401
void BytecodeGraphBuilder::VisitLdaGlobalInsideTypeof() {
1402
  PrepareEagerCheckpoint();
1403 1404
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
1405 1406 1407
  uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
  Node* node =
      BuildLoadGlobal(name, feedback_slot_index, TypeofMode::INSIDE_TYPEOF);
1408
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1409 1410
}

1411
void BytecodeGraphBuilder::VisitStaGlobal() {
1412
  PrepareEagerCheckpoint();
1413 1414
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
1415 1416
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(1));
1417 1418
  Node* value = environment()->LookupAccumulator();

1419 1420
  LanguageMode language_mode =
      feedback.vector()->GetLanguageMode(feedback.slot());
1421
  const Operator* op = javascript()->StoreGlobal(language_mode, name, feedback);
1422
  Node* node = NewNode(op, value);
1423
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1424 1425
}

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
void BytecodeGraphBuilder::VisitStaInArrayLiteral() {
  PrepareEagerCheckpoint();
  Node* value = environment()->LookupAccumulator();
  Node* array =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
  const Operator* op = javascript()->StoreInArrayLiteral(feedback);

  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreKeyed(op, array, index, value, feedback.slot());
  if (lowering.IsExit()) return;

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(op, array, index, value);
  }

  environment()->RecordAfterState(node, Environment::kAttachFrameState);
}

1452
void BytecodeGraphBuilder::VisitStaDataPropertyInLiteral() {
1453 1454
  PrepareEagerCheckpoint();

1455 1456 1457 1458
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* name =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
1459 1460 1461 1462
  Node* value = environment()->LookupAccumulator();
  int flags = bytecode_iterator().GetFlagOperand(2);
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(3));
1463

1464
  const Operator* op = javascript()->StoreDataPropertyInLiteral(feedback);
1465
  Node* node = NewNode(op, object, name, value, jsgraph()->Constant(flags));
1466
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1467 1468 1469 1470 1471
}

void BytecodeGraphBuilder::VisitCollectTypeProfile() {
  PrepareEagerCheckpoint();

1472 1473
  Node* position =
      jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
1474 1475 1476 1477 1478
  Node* value = environment()->LookupAccumulator();
  Node* vector = jsgraph()->Constant(feedback_vector());

  const Operator* op = javascript()->CallRuntime(Runtime::kCollectTypeProfile);

1479
  Node* node = NewNode(op, position, value, vector);
1480
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1481 1482
}

1483
void BytecodeGraphBuilder::VisitLdaContextSlot() {
1484 1485 1486
  const Operator* op = javascript()->LoadContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1), false);
1487
  Node* node = NewNode(op);
1488 1489
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1490
  NodeProperties::ReplaceContextInput(node, context);
1491
  environment()->BindAccumulator(node);
1492 1493
}

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
void BytecodeGraphBuilder::VisitLdaImmutableContextSlot() {
  const Operator* op = javascript()->LoadContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1), true);
  Node* node = NewNode(op);
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  NodeProperties::ReplaceContextInput(node, context);
  environment()->BindAccumulator(node);
}

1505
void BytecodeGraphBuilder::VisitLdaCurrentContextSlot() {
1506 1507
  const Operator* op = javascript()->LoadContext(
      0, bytecode_iterator().GetIndexOperand(0), false);
1508
  Node* node = NewNode(op);
1509
  environment()->BindAccumulator(node);
1510 1511
}

1512 1513 1514 1515 1516 1517 1518
void BytecodeGraphBuilder::VisitLdaImmutableCurrentContextSlot() {
  const Operator* op = javascript()->LoadContext(
      0, bytecode_iterator().GetIndexOperand(0), true);
  Node* node = NewNode(op);
  environment()->BindAccumulator(node);
}

1519
void BytecodeGraphBuilder::VisitStaContextSlot() {
1520 1521 1522
  const Operator* op = javascript()->StoreContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1));
1523 1524
  Node* value = environment()->LookupAccumulator();
  Node* node = NewNode(op, value);
1525 1526
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1527
  NodeProperties::ReplaceContextInput(node, context);
1528 1529
}

1530 1531 1532 1533
void BytecodeGraphBuilder::VisitStaCurrentContextSlot() {
  const Operator* op =
      javascript()->StoreContext(0, bytecode_iterator().GetIndexOperand(0));
  Node* value = environment()->LookupAccumulator();
1534
  NewNode(op, value);
1535 1536
}

1537
void BytecodeGraphBuilder::BuildLdaLookupSlot(TypeofMode typeof_mode) {
1538
  PrepareEagerCheckpoint();
1539 1540
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1541 1542 1543 1544 1545
  const Operator* op =
      javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                    ? Runtime::kLoadLookupSlot
                                    : Runtime::kLoadLookupSlotInsideTypeof);
  Node* value = NewNode(op, name);
1546
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
1547 1548
}

1549 1550
void BytecodeGraphBuilder::VisitLdaLookupSlot() {
  BuildLdaLookupSlot(TypeofMode::NOT_INSIDE_TYPEOF);
1551 1552
}

1553 1554
void BytecodeGraphBuilder::VisitLdaLookupSlotInsideTypeof() {
  BuildLdaLookupSlot(TypeofMode::INSIDE_TYPEOF);
1555 1556
}

1557 1558 1559
BytecodeGraphBuilder::Environment* BytecodeGraphBuilder::CheckContextExtensions(
    uint32_t depth) {
  // Output environment where the context has an extension
1560 1561
  Environment* slow_environment = nullptr;

1562 1563
  // We only need to check up to the last-but-one depth, because the an eval
  // in the same scope as the variable itself has no way of shadowing it.
1564 1565
  for (uint32_t d = 0; d < depth; d++) {
    Node* extension_slot =
1566
        NewNode(javascript()->LoadContext(d, Context::EXTENSION_INDEX, false));
1567 1568

    Node* check_no_extension =
1569 1570
        NewNode(simplified()->ReferenceEqual(), extension_slot,
                jsgraph()->TheHoleConstant());
1571 1572 1573 1574

    NewBranch(check_no_extension);

    {
1575 1576
      SubEnvironment sub_environment(this);

1577 1578 1579
      NewIfFalse();
      // If there is an extension, merge into the slow path.
      if (slow_environment == nullptr) {
1580
        slow_environment = environment();
1581 1582
        NewMerge();
      } else {
1583
        slow_environment->Merge(environment(),
1584
                                bytecode_analysis().GetInLivenessFor(
1585
                                    bytecode_iterator().current_offset()));
1586 1587 1588
      }
    }

1589 1590 1591
    NewIfTrue();
    // Do nothing on if there is no extension, eventually falling through to
    // the fast path.
1592 1593
  }

1594 1595
  // The depth can be zero, in which case no slow-path checks are built, and
  // the slow path environment can be null.
1596
  DCHECK(depth == 0 || slow_environment != nullptr);
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

  return slow_environment;
}

void BytecodeGraphBuilder::BuildLdaLookupContextSlot(TypeofMode typeof_mode) {
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(2);

  // Check if any context in the depth has an extension.
  Environment* slow_environment = CheckContextExtensions(depth);

1607 1608 1609 1610 1611
  // Fast path, do a context load.
  {
    uint32_t slot_index = bytecode_iterator().GetIndexOperand(1);

    const Operator* op = javascript()->LoadContext(depth, slot_index, false);
1612
    environment()->BindAccumulator(NewNode(op));
1613
  }
1614

1615 1616 1617 1618 1619
  // Only build the slow path if there were any slow-path checks.
  if (slow_environment != nullptr) {
    // Add a merge to the fast environment.
    NewMerge();
    Environment* fast_environment = environment();
1620

1621 1622 1623 1624
    // Slow path, do a runtime load lookup.
    set_environment(slow_environment);
    {
      Node* name = jsgraph()->Constant(
1625
          handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1626 1627 1628 1629 1630 1631

      const Operator* op =
          javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                        ? Runtime::kLoadLookupSlot
                                        : Runtime::kLoadLookupSlotInsideTypeof);
      Node* value = NewNode(op, name);
1632
      environment()->BindAccumulator(value, Environment::kAttachFrameState);
1633
    }
1634

1635
    fast_environment->Merge(environment(),
1636
                            bytecode_analysis().GetOutLivenessFor(
1637
                                bytecode_iterator().current_offset()));
1638
    set_environment(fast_environment);
1639
    mark_as_needing_eager_checkpoint(true);
1640
  }
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
}

void BytecodeGraphBuilder::VisitLdaLookupContextSlot() {
  BuildLdaLookupContextSlot(TypeofMode::NOT_INSIDE_TYPEOF);
}

void BytecodeGraphBuilder::VisitLdaLookupContextSlotInsideTypeof() {
  BuildLdaLookupContextSlot(TypeofMode::INSIDE_TYPEOF);
}

1651
void BytecodeGraphBuilder::BuildLdaLookupGlobalSlot(TypeofMode typeof_mode) {
1652 1653 1654 1655 1656 1657 1658
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(2);

  // Check if any context in the depth has an extension.
  Environment* slow_environment = CheckContextExtensions(depth);

  // Fast path, do a global load.
  {
1659
    PrepareEagerCheckpoint();
1660 1661 1662
    Handle<Name> name(
        Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
        isolate());
1663 1664
    uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
    Node* node = BuildLoadGlobal(name, feedback_slot_index, typeof_mode);
1665
    environment()->BindAccumulator(node, Environment::kAttachFrameState);
1666
  }
1667

1668 1669 1670
  // Only build the slow path if there were any slow-path checks.
  if (slow_environment != nullptr) {
    // Add a merge to the fast environment.
1671
    NewMerge();
1672
    Environment* fast_environment = environment();
1673

1674 1675 1676 1677
    // Slow path, do a runtime load lookup.
    set_environment(slow_environment);
    {
      Node* name = jsgraph()->Constant(
1678
          handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1679

1680 1681 1682 1683 1684
      const Operator* op =
          javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                        ? Runtime::kLoadLookupSlot
                                        : Runtime::kLoadLookupSlotInsideTypeof);
      Node* value = NewNode(op, name);
1685
      environment()->BindAccumulator(value, Environment::kAttachFrameState);
1686
    }
1687

1688
    fast_environment->Merge(environment(),
1689
                            bytecode_analysis().GetOutLivenessFor(
1690
                                bytecode_iterator().current_offset()));
1691
    set_environment(fast_environment);
1692
    mark_as_needing_eager_checkpoint(true);
1693
  }
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
}

void BytecodeGraphBuilder::VisitLdaLookupGlobalSlot() {
  BuildLdaLookupGlobalSlot(TypeofMode::NOT_INSIDE_TYPEOF);
}

void BytecodeGraphBuilder::VisitLdaLookupGlobalSlotInsideTypeof() {
  BuildLdaLookupGlobalSlot(TypeofMode::INSIDE_TYPEOF);
}

1704
void BytecodeGraphBuilder::VisitStaLookupSlot() {
1705
  PrepareEagerCheckpoint();
1706
  Node* value = environment()->LookupAccumulator();
1707 1708
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1709 1710 1711 1712 1713 1714 1715 1716 1717
  int bytecode_flags = bytecode_iterator().GetFlagOperand(1);
  LanguageMode language_mode = static_cast<LanguageMode>(
      interpreter::StoreLookupSlotFlags::LanguageModeBit::decode(
          bytecode_flags));
  LookupHoistingMode lookup_hoisting_mode = static_cast<LookupHoistingMode>(
      interpreter::StoreLookupSlotFlags::LookupHoistingModeBit::decode(
          bytecode_flags));
  DCHECK_IMPLIES(lookup_hoisting_mode == LookupHoistingMode::kLegacySloppy,
                 is_sloppy(language_mode));
1718
  const Operator* op = javascript()->CallRuntime(
1719 1720 1721 1722 1723
      is_strict(language_mode)
          ? Runtime::kStoreLookupSlot_Strict
          : lookup_hoisting_mode == LookupHoistingMode::kLegacySloppy
                ? Runtime::kStoreLookupSlot_SloppyHoisting
                : Runtime::kStoreLookupSlot_Sloppy);
1724
  Node* store = NewNode(op, name, value);
1725
  environment()->BindAccumulator(store, Environment::kAttachFrameState);
1726 1727
}

1728 1729
void BytecodeGraphBuilder::VisitLdaNamedProperty() {
  PrepareEagerCheckpoint();
1730 1731
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1732 1733
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
1734 1735
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1736
  const Operator* op = javascript()->LoadNamed(name, feedback);
1737

1738 1739 1740 1741
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedLoadNamed(op, object, feedback.slot());
  if (lowering.IsExit()) return;

1742
  Node* node = nullptr;
1743 1744
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1745
  } else {
1746
    DCHECK(!lowering.Changed());
1747 1748
    node = NewNode(op, object);
  }
1749
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1750
}
1751

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
void BytecodeGraphBuilder::VisitLdaNamedPropertyNoFeedback() {
  PrepareEagerCheckpoint();
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
  const Operator* op = javascript()->LoadNamed(name, VectorSlotPair());
  Node* node = NewNode(op, object);
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

1763
void BytecodeGraphBuilder::VisitLdaKeyedProperty() {
1764
  PrepareEagerCheckpoint();
1765
  Node* key = environment()->LookupAccumulator();
1766 1767 1768 1769
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(1));
1770
  const Operator* op = javascript()->LoadProperty(feedback);
1771

1772 1773 1774 1775
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedLoadKeyed(op, object, key, feedback.slot());
  if (lowering.IsExit()) return;

1776
  Node* node = nullptr;
1777 1778
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1779
  } else {
1780
    DCHECK(!lowering.Changed());
1781 1782
    node = NewNode(op, object, key);
  }
1783
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1784 1785
}

1786
void BytecodeGraphBuilder::BuildNamedStore(StoreMode store_mode) {
1787
  PrepareEagerCheckpoint();
1788
  Node* value = environment()->LookupAccumulator();
1789 1790
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1791 1792
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
1793 1794
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1795

1796 1797 1798 1799 1800 1801
  const Operator* op;
  if (store_mode == StoreMode::kOwn) {
    DCHECK_EQ(FeedbackSlotKind::kStoreOwnNamed,
              feedback.vector()->GetKind(feedback.slot()));
    op = javascript()->StoreNamedOwn(name, feedback);
  } else {
1802
    DCHECK_EQ(StoreMode::kNormal, store_mode);
1803 1804
    LanguageMode language_mode =
        feedback.vector()->GetLanguageMode(feedback.slot());
1805 1806
    op = javascript()->StoreNamed(language_mode, name, feedback);
  }
1807

1808 1809 1810 1811
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreNamed(op, object, value, feedback.slot());
  if (lowering.IsExit()) return;

1812
  Node* node = nullptr;
1813 1814
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1815
  } else {
1816
    DCHECK(!lowering.Changed());
1817 1818
    node = NewNode(op, object, value);
  }
1819
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1820 1821
}

1822 1823
void BytecodeGraphBuilder::VisitStaNamedProperty() {
  BuildNamedStore(StoreMode::kNormal);
1824 1825
}

1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
void BytecodeGraphBuilder::VisitStaNamedPropertyNoFeedback() {
  PrepareEagerCheckpoint();
  Node* value = environment()->LookupAccumulator();
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
  LanguageMode language_mode =
      static_cast<LanguageMode>(bytecode_iterator().GetFlagOperand(2));
  const Operator* op =
      javascript()->StoreNamed(language_mode, name, VectorSlotPair());
  Node* node = NewNode(op, object, value);
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
}

1841
void BytecodeGraphBuilder::VisitStaNamedOwnProperty() {
1842
  BuildNamedStore(StoreMode::kOwn);
1843 1844
}

1845
void BytecodeGraphBuilder::VisitStaKeyedProperty() {
1846
  PrepareEagerCheckpoint();
1847
  Node* value = environment()->LookupAccumulator();
1848 1849 1850 1851 1852 1853
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* key =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1854 1855
  LanguageMode language_mode =
      feedback.vector()->GetLanguageMode(feedback.slot());
1856
  const Operator* op = javascript()->StoreProperty(language_mode, feedback);
1857

1858 1859 1860 1861
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreKeyed(op, object, key, value, feedback.slot());
  if (lowering.IsExit()) return;

1862
  Node* node = nullptr;
1863 1864
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1865
  } else {
1866
    DCHECK(!lowering.Changed());
1867 1868 1869
    node = NewNode(op, object, key, value);
  }

1870
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1871 1872
}

1873
void BytecodeGraphBuilder::VisitLdaModuleVariable() {
1874 1875
  int32_t cell_index = bytecode_iterator().GetImmediateOperand(0);
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(1);
1876 1877
  Node* module =
      NewNode(javascript()->LoadContext(depth, Context::EXTENSION_INDEX, true));
1878 1879
  Node* value = NewNode(javascript()->LoadModule(cell_index), module);
  environment()->BindAccumulator(value);
1880 1881 1882
}

void BytecodeGraphBuilder::VisitStaModuleVariable() {
1883 1884
  int32_t cell_index = bytecode_iterator().GetImmediateOperand(0);
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(1);
1885 1886
  Node* module =
      NewNode(javascript()->LoadContext(depth, Context::EXTENSION_INDEX, true));
1887
  Node* value = environment()->LookupAccumulator();
1888
  NewNode(javascript()->StoreModule(cell_index), module, value);
1889 1890
}

1891
void BytecodeGraphBuilder::VisitPushContext() {
1892
  Node* new_context = environment()->LookupAccumulator();
1893
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0),
1894 1895
                              environment()->Context());
  environment()->SetContext(new_context);
1896 1897
}

1898 1899 1900
void BytecodeGraphBuilder::VisitPopContext() {
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1901
  environment()->SetContext(context);
1902 1903
}

1904
void BytecodeGraphBuilder::VisitCreateClosure() {
1905 1906 1907 1908
  Handle<SharedFunctionInfo> shared_info(
      SharedFunctionInfo::cast(
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1909
  AllocationType allocation =
1910
      interpreter::CreateClosureFlags::PretenuredBit::decode(
1911
          bytecode_iterator().GetFlagOperand(2))
1912 1913
          ? AllocationType::kOld
          : AllocationType::kYoung;
1914
  const Operator* op = javascript()->CreateClosure(
1915 1916 1917
      shared_info,
      feedback_vector()->GetClosureFeedbackCell(
          bytecode_iterator().GetIndexOperand(1)),
1918 1919
      handle(jsgraph()->isolate()->builtins()->builtin(Builtins::kCompileLazy),
             isolate()),
1920
      allocation);
1921 1922 1923 1924
  Node* closure = NewNode(op);
  environment()->BindAccumulator(closure);
}

1925
void BytecodeGraphBuilder::VisitCreateBlockContext() {
1926 1927 1928
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1929 1930

  const Operator* op = javascript()->CreateBlockContext(scope_info);
1931
  Node* context = NewNode(op);
1932 1933 1934
  environment()->BindAccumulator(context);
}

1935
void BytecodeGraphBuilder::VisitCreateFunctionContext() {
1936 1937 1938
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1939
  uint32_t slots = bytecode_iterator().GetUnsignedImmediateOperand(1);
1940
  const Operator* op =
1941 1942
      javascript()->CreateFunctionContext(scope_info, slots, FUNCTION_SCOPE);
  Node* context = NewNode(op);
1943 1944 1945 1946
  environment()->BindAccumulator(context);
}

void BytecodeGraphBuilder::VisitCreateEvalContext() {
1947 1948 1949
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1950 1951 1952 1953
  uint32_t slots = bytecode_iterator().GetUnsignedImmediateOperand(1);
  const Operator* op =
      javascript()->CreateFunctionContext(scope_info, slots, EVAL_SCOPE);
  Node* context = NewNode(op);
1954 1955 1956
  environment()->BindAccumulator(context);
}

1957 1958 1959
void BytecodeGraphBuilder::VisitCreateCatchContext() {
  interpreter::Register reg = bytecode_iterator().GetRegisterOperand(0);
  Node* exception = environment()->LookupRegister(reg);
1960 1961 1962
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(1)),
      isolate());
1963

1964
  const Operator* op = javascript()->CreateCatchContext(scope_info);
1965
  Node* context = NewNode(op, exception);
1966 1967 1968
  environment()->BindAccumulator(context);
}

1969 1970 1971
void BytecodeGraphBuilder::VisitCreateWithContext() {
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1972 1973 1974
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(1)),
      isolate());
1975

1976
  const Operator* op = javascript()->CreateWithContext(scope_info);
1977
  Node* context = NewNode(op, object);
1978 1979 1980
  environment()->BindAccumulator(context);
}

1981 1982
void BytecodeGraphBuilder::BuildCreateArguments(CreateArgumentsType type) {
  const Operator* op = javascript()->CreateArguments(type);
1983
  Node* object = NewNode(op, GetFunctionClosure());
1984
  environment()->BindAccumulator(object, Environment::kAttachFrameState);
1985 1986
}

1987
void BytecodeGraphBuilder::VisitCreateMappedArguments() {
1988
  BuildCreateArguments(CreateArgumentsType::kMappedArguments);
1989 1990
}

1991
void BytecodeGraphBuilder::VisitCreateUnmappedArguments() {
1992
  BuildCreateArguments(CreateArgumentsType::kUnmappedArguments);
1993 1994
}

1995 1996
void BytecodeGraphBuilder::VisitCreateRestParameter() {
  BuildCreateArguments(CreateArgumentsType::kRestParameter);
1997 1998
}

1999
void BytecodeGraphBuilder::VisitCreateRegExpLiteral() {
2000 2001 2002
  Handle<String> constant_pattern(
      String::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
2003 2004
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
2005
  int literal_flags = bytecode_iterator().GetFlagOperand(2);
2006 2007
  Node* literal = NewNode(
      javascript()->CreateLiteralRegExp(constant_pattern, pair, literal_flags));
2008
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
2009 2010
}

2011
void BytecodeGraphBuilder::VisitCreateArrayLiteral() {
2012 2013
  Handle<ArrayBoilerplateDescription> array_boilerplate_description(
      ArrayBoilerplateDescription::cast(
2014 2015
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
2016 2017
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
2018 2019 2020
  int bytecode_flags = bytecode_iterator().GetFlagOperand(2);
  int literal_flags =
      interpreter::CreateArrayLiteralFlags::FlagsBits::decode(bytecode_flags);
2021 2022 2023 2024 2025
  // Disable allocation site mementos. Only unoptimized code will collect
  // feedback about allocation site. Once the code is optimized we expect the
  // data to converge. So, we disable allocation site mementos in optimized
  // code. We can revisit this when we have data to the contrary.
  literal_flags |= ArrayLiteral::kDisableMementos;
2026 2027
  // TODO(mstarzinger): Thread through number of elements. The below number is
  // only an estimate and does not match {ArrayLiteral::values::length}.
2028
  int number_of_elements =
2029
      array_boilerplate_description->constant_elements().length();
2030
  Node* literal = NewNode(javascript()->CreateLiteralArray(
2031
      array_boilerplate_description, pair, literal_flags, number_of_elements));
2032
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
2033 2034
}

2035
void BytecodeGraphBuilder::VisitCreateEmptyArrayLiteral() {
2036 2037 2038
  int const slot_id = bytecode_iterator().GetIndexOperand(0);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
  Node* literal = NewNode(javascript()->CreateEmptyLiteralArray(pair));
2039 2040 2041
  environment()->BindAccumulator(literal);
}

2042 2043 2044 2045 2046 2047
void BytecodeGraphBuilder::VisitCreateArrayFromIterable() {
  Node* iterable = NewNode(javascript()->CreateArrayFromIterable(),
                           environment()->LookupAccumulator());
  environment()->BindAccumulator(iterable, Environment::kAttachFrameState);
}

2048
void BytecodeGraphBuilder::VisitCreateObjectLiteral() {
2049 2050
  Handle<ObjectBoilerplateDescription> constant_properties(
      ObjectBoilerplateDescription::cast(
2051 2052
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
2053 2054
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
2055 2056 2057
  int bytecode_flags = bytecode_iterator().GetFlagOperand(2);
  int literal_flags =
      interpreter::CreateObjectLiteralFlags::FlagsBits::decode(bytecode_flags);
2058 2059
  // TODO(mstarzinger): Thread through number of properties. The below number is
  // only an estimate and does not match {ObjectLiteral::properties_count}.
2060
  int number_of_properties = constant_properties->size();
2061 2062
  Node* literal = NewNode(javascript()->CreateLiteralObject(
      constant_properties, pair, literal_flags, number_of_properties));
2063
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
2064 2065
}

2066
void BytecodeGraphBuilder::VisitCreateEmptyObjectLiteral() {
2067 2068
  Node* literal =
      NewNode(javascript()->CreateEmptyLiteralObject(), GetFunctionClosure());
2069 2070 2071
  environment()->BindAccumulator(literal);
}

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
void BytecodeGraphBuilder::VisitCloneObject() {
  PrepareEagerCheckpoint();
  Node* source =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  int flags = bytecode_iterator().GetFlagOperand(1);
  int slot = bytecode_iterator().GetIndexOperand(2);
  const Operator* op =
      javascript()->CloneObject(CreateVectorSlotPair(slot), flags);
  Node* value = NewNode(op, source);
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
}

2084
void BytecodeGraphBuilder::VisitGetTemplateObject() {
2085 2086 2087 2088
  Handle<TemplateObjectDescription> description(
      TemplateObjectDescription::cast(
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
2089 2090 2091 2092
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
  FeedbackNexus nexus(feedback_vector(), slot);

  Handle<JSArray> cached_value;
2093
  if (nexus.GetFeedback() == MaybeObject::FromSmi(Smi::zero())) {
2094 2095 2096
    // It's not observable when the template object is created, so we
    // can just create it eagerly during graph building and bake in
    // the JSArray constant here.
2097 2098
    cached_value = TemplateObjectDescription::GetTemplateObject(
        isolate(), native_context(), description, shared_info(), slot.ToInt());
2099
    nexus.vector().Set(slot, *cached_value);
2100
  } else {
2101 2102 2103
    cached_value =
        handle(JSArray::cast(nexus.GetFeedback()->GetHeapObjectAssumeStrong()),
               isolate());
2104 2105 2106
  }

  Node* template_object = jsgraph()->HeapConstant(cached_value);
2107 2108 2109
  environment()->BindAccumulator(template_object);
}

2110
Node* const* BytecodeGraphBuilder::GetCallArgumentsFromRegisters(
2111 2112 2113 2114 2115 2116 2117 2118
    Node* callee, Node* receiver, interpreter::Register first_arg,
    int arg_count) {
  // The arity of the Call node -- includes the callee, receiver and function
  // arguments.
  int arity = 2 + arg_count;

  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));

2119
  all[0] = callee;
2120 2121 2122 2123 2124 2125 2126
  all[1] = receiver;

  // The function arguments are in consecutive registers.
  int arg_base = first_arg.index();
  for (int i = 0; i < arg_count; ++i) {
    all[2 + i] =
        environment()->LookupRegister(interpreter::Register(arg_base + i));
2127
  }
2128

2129 2130 2131 2132 2133
  return all;
}

Node* BytecodeGraphBuilder::ProcessCallArguments(const Operator* call_op,
                                                 Node* const* args,
2134 2135
                                                 int arg_count) {
  return MakeNode(call_op, arg_count, args, false);
2136 2137 2138 2139 2140
}

Node* BytecodeGraphBuilder::ProcessCallArguments(const Operator* call_op,
                                                 Node* callee,
                                                 interpreter::Register receiver,
2141 2142 2143 2144 2145 2146 2147
                                                 size_t reg_count) {
  Node* receiver_node = environment()->LookupRegister(receiver);
  // The receiver is followed by the arguments in the consecutive registers.
  DCHECK_GE(reg_count, 1);
  interpreter::Register first_arg = interpreter::Register(receiver.index() + 1);
  int arg_count = static_cast<int>(reg_count) - 1;

2148 2149
  Node* const* call_args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                         first_arg, arg_count);
2150
  return ProcessCallArguments(call_op, call_args, 2 + arg_count);
2151 2152
}

2153
void BytecodeGraphBuilder::BuildCall(ConvertReceiverMode receiver_mode,
2154 2155
                                     Node* const* args, size_t arg_count,
                                     int slot_id) {
2156 2157 2158
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            receiver_mode);
2159
  PrepareEagerCheckpoint();
2160

2161
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
2162

2163
  CallFrequency frequency = ComputeCallFrequency(slot_id);
2164
  const Operator* op =
2165 2166
      javascript()->Call(arg_count, frequency, feedback, receiver_mode,
                         GetSpeculationMode(slot_id));
2167 2168 2169 2170
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedCall(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2171
  Node* node = nullptr;
2172 2173
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2174
  } else {
2175
    DCHECK(!lowering.Changed());
2176 2177 2178
    node = ProcessCallArguments(op, args, static_cast<int>(arg_count));
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2179 2180
}

2181 2182 2183 2184
Node* const* BytecodeGraphBuilder::ProcessCallVarArgs(
    ConvertReceiverMode receiver_mode, Node* callee,
    interpreter::Register first_reg, int arg_count) {
  DCHECK_GE(arg_count, 0);
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
  Node* receiver_node;
  interpreter::Register first_arg;

  if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
    // The receiver is implicit (and undefined), the arguments are in
    // consecutive registers.
    receiver_node = jsgraph()->UndefinedConstant();
    first_arg = first_reg;
  } else {
    // The receiver is the first register, followed by the arguments in the
    // consecutive registers.
    receiver_node = environment()->LookupRegister(first_reg);
    first_arg = interpreter::Register(first_reg.index() + 1);
  }

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
  Node* const* call_args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                         first_arg, arg_count);
  return call_args;
}

void BytecodeGraphBuilder::BuildCallVarArgs(ConvertReceiverMode receiver_mode) {
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            receiver_mode);
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
  int const slot_id = bytecode_iterator().GetIndexOperand(3);

  int arg_count = receiver_mode == ConvertReceiverMode::kNullOrUndefined
                      ? static_cast<int>(reg_count)
                      : static_cast<int>(reg_count) - 1;
2218
  Node* const* call_args =
2219
      ProcessCallVarArgs(receiver_mode, callee, first_reg, arg_count);
2220 2221
  BuildCall(receiver_mode, call_args, static_cast<size_t>(2 + arg_count),
            slot_id);
2222 2223
}

2224
void BytecodeGraphBuilder::VisitCallAnyReceiver() {
2225
  BuildCallVarArgs(ConvertReceiverMode::kAny);
2226 2227
}

2228
void BytecodeGraphBuilder::VisitCallNoFeedback() {
2229 2230 2231 2232
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            ConvertReceiverMode::kAny);

2233
  PrepareEagerCheckpoint();
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));

  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);

  // The receiver is the first register, followed by the arguments in the
  // consecutive registers.
  int arg_count = static_cast<int>(reg_count) - 1;
  // The arity of the Call node -- includes the callee, receiver and function
  // arguments.
  int arity = 2 + arg_count;

  // Setting call frequency to a value less than min_inlining frequency to
  // prevent inlining of one-shot call node.
  DCHECK(CallFrequency::kNoFeedbackCallFrequency < FLAG_min_inlining_frequency);
  const Operator* call = javascript()->Call(
      arity, CallFrequency(CallFrequency::kNoFeedbackCallFrequency));
  Node* const* call_args = ProcessCallVarArgs(ConvertReceiverMode::kAny, callee,
                                              first_reg, arg_count);
  Node* value = ProcessCallArguments(call, call_args, arity);
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2256 2257
}

2258
void BytecodeGraphBuilder::VisitCallProperty() {
2259
  BuildCallVarArgs(ConvertReceiverMode::kNotNullOrUndefined);
2260 2261 2262
}

void BytecodeGraphBuilder::VisitCallProperty0() {
2263 2264 2265 2266 2267
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int const slot_id = bytecode_iterator().GetIndexOperand(2);
2268 2269
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined, {callee, receiver},
            slot_id);
2270 2271
}

2272
void BytecodeGraphBuilder::VisitCallProperty1() {
2273 2274 2275 2276 2277 2278 2279
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  Node* arg0 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
2280 2281
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined, {callee, receiver, arg0},
            slot_id);
2282 2283
}

2284
void BytecodeGraphBuilder::VisitCallProperty2() {
2285 2286 2287 2288 2289 2290 2291 2292 2293
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  Node* arg0 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  Node* arg1 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(3));
  int const slot_id = bytecode_iterator().GetIndexOperand(4);
2294
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined,
2295 2296 2297
            {callee, receiver, arg0, arg1}, slot_id);
}

2298
void BytecodeGraphBuilder::VisitCallUndefinedReceiver() {
2299
  BuildCallVarArgs(ConvertReceiverMode::kNullOrUndefined);
2300 2301
}

2302
void BytecodeGraphBuilder::VisitCallUndefinedReceiver0() {
2303 2304
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2305 2306
  Node* receiver = jsgraph()->UndefinedConstant();
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
2307
  BuildCall(ConvertReceiverMode::kNullOrUndefined, {callee, receiver}, slot_id);
2308 2309
}

2310
void BytecodeGraphBuilder::VisitCallUndefinedReceiver1() {
2311 2312
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2313
  Node* receiver = jsgraph()->UndefinedConstant();
2314
  Node* arg0 =
2315 2316
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int const slot_id = bytecode_iterator().GetIndexOperand(2);
2317 2318
  BuildCall(ConvertReceiverMode::kNullOrUndefined, {callee, receiver, arg0},
            slot_id);
2319 2320
}

2321
void BytecodeGraphBuilder::VisitCallUndefinedReceiver2() {
2322 2323
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2324
  Node* receiver = jsgraph()->UndefinedConstant();
2325
  Node* arg0 =
2326
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
2327
  Node* arg1 =
2328 2329
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
2330
  BuildCall(ConvertReceiverMode::kNullOrUndefined,
2331
            {callee, receiver, arg0, arg1}, slot_id);
2332 2333
}

2334 2335
void BytecodeGraphBuilder::VisitCallWithSpread() {
  PrepareEagerCheckpoint();
2336 2337 2338
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
2339
  Node* receiver_node = environment()->LookupRegister(receiver);
2340
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2341 2342
  interpreter::Register first_arg = interpreter::Register(receiver.index() + 1);
  int arg_count = static_cast<int>(reg_count) - 1;
2343 2344
  Node* const* args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                    first_arg, arg_count);
2345 2346
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
2347

2348 2349 2350
  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->CallWithSpread(
      static_cast<int>(reg_count + 1), frequency, feedback);
2351 2352 2353 2354 2355

  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedCall(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2356
  Node* node = nullptr;
2357 2358
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2359
  } else {
2360
    DCHECK(!lowering.Changed());
2361 2362 2363
    node = ProcessCallArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2364 2365
}

2366
void BytecodeGraphBuilder::VisitCallJSRuntime() {
2367
  PrepareEagerCheckpoint();
2368 2369
  Node* callee = BuildLoadNativeContextField(
      bytecode_iterator().GetNativeContextIndexOperand(0));
2370
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
2371
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2372
  int arg_count = static_cast<int>(reg_count);
2373

2374 2375 2376 2377
  const Operator* call = javascript()->Call(2 + arg_count);
  Node* const* call_args = ProcessCallVarArgs(
      ConvertReceiverMode::kNullOrUndefined, callee, first_reg, arg_count);
  Node* value = ProcessCallArguments(call, call_args, 2 + arg_count);
2378
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2379 2380
}

2381
Node* BytecodeGraphBuilder::ProcessCallRuntimeArguments(
2382 2383 2384 2385 2386 2387 2388 2389
    const Operator* call_runtime_op, interpreter::Register receiver,
    size_t reg_count) {
  int arg_count = static_cast<int>(reg_count);
  // arity is args.
  int arity = arg_count;
  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));
  int first_arg_index = receiver.index();
  for (int i = 0; i < static_cast<int>(reg_count); ++i) {
2390 2391 2392
    all[i] = environment()->LookupRegister(
        interpreter::Register(first_arg_index + i));
  }
2393
  Node* value = MakeNode(call_runtime_op, arity, all, false);
2394 2395 2396
  return value;
}

2397
void BytecodeGraphBuilder::VisitCallRuntime() {
2398
  PrepareEagerCheckpoint();
2399
  Runtime::FunctionId function_id = bytecode_iterator().GetRuntimeIdOperand(0);
2400 2401
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2402 2403

  // Create node to perform the runtime call.
2404
  const Operator* call = javascript()->CallRuntime(function_id, reg_count);
2405
  Node* value = ProcessCallRuntimeArguments(call, receiver, reg_count);
2406
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2407 2408 2409

  // Connect to the end if {function_id} is non-returning.
  if (Runtime::IsNonReturning(function_id)) {
2410
    // TODO(7099): Investigate if we need LoopExit node here.
2411 2412 2413
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }
2414 2415
}

2416
void BytecodeGraphBuilder::VisitCallRuntimeForPair() {
2417
  PrepareEagerCheckpoint();
2418
  Runtime::FunctionId functionId = bytecode_iterator().GetRuntimeIdOperand(0);
2419 2420
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2421 2422
  interpreter::Register first_return =
      bytecode_iterator().GetRegisterOperand(3);
2423 2424

  // Create node to perform the runtime call.
2425 2426
  const Operator* call = javascript()->CallRuntime(functionId, reg_count);
  Node* return_pair = ProcessCallRuntimeArguments(call, receiver, reg_count);
2427 2428
  environment()->BindRegistersToProjections(first_return, return_pair,
                                            Environment::kAttachFrameState);
2429 2430
}

2431 2432 2433
Node* const* BytecodeGraphBuilder::GetConstructArgumentsFromRegister(
    Node* target, Node* new_target, interpreter::Register first_arg,
    int arg_count) {
2434 2435 2436
  // arity is args + callee and new target.
  int arity = arg_count + 2;
  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));
2437 2438
  all[0] = target;
  int first_arg_index = first_arg.index();
2439 2440 2441
  for (int i = 0; i < arg_count; ++i) {
    all[1 + i] = environment()->LookupRegister(
        interpreter::Register(first_arg_index + i));
2442 2443
  }
  all[arity - 1] = new_target;
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
  return all;
}

Node* BytecodeGraphBuilder::ProcessConstructArguments(const Operator* op,
                                                      Node* const* args,
                                                      int arg_count) {
  return MakeNode(op, arg_count, args, false);
}

void BytecodeGraphBuilder::VisitConstruct() {
  PrepareEagerCheckpoint();
  interpreter::Register callee_reg = bytecode_iterator().GetRegisterOperand(0);
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);

  Node* new_target = environment()->LookupAccumulator();
  Node* callee = environment()->LookupRegister(callee_reg);

  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->Construct(
      static_cast<uint32_t>(reg_count + 2), frequency, feedback);
  int arg_count = static_cast<int>(reg_count);
  Node* const* args = GetConstructArgumentsFromRegister(callee, new_target,
                                                        first_reg, arg_count);
2470 2471 2472 2473
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedConstruct(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2474
  Node* node = nullptr;
2475 2476
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2477
  } else {
2478
    DCHECK(!lowering.Changed());
2479 2480 2481
    node = ProcessConstructArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2482 2483
}

2484
void BytecodeGraphBuilder::VisitConstructWithSpread() {
2485
  PrepareEagerCheckpoint();
2486
  interpreter::Register callee_reg = bytecode_iterator().GetRegisterOperand(0);
2487
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
2488
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2489 2490
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
2491 2492 2493

  Node* new_target = environment()->LookupAccumulator();
  Node* callee = environment()->LookupRegister(callee_reg);
2494

2495 2496 2497
  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->ConstructWithSpread(
      static_cast<uint32_t>(reg_count + 2), frequency, feedback);
2498 2499 2500
  int arg_count = static_cast<int>(reg_count);
  Node* const* args = GetConstructArgumentsFromRegister(callee, new_target,
                                                        first_reg, arg_count);
2501 2502 2503 2504
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedConstruct(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2505
  Node* node = nullptr;
2506 2507
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2508
  } else {
2509
    DCHECK(!lowering.Changed());
2510 2511 2512
    node = ProcessConstructArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2513 2514
}

2515
void BytecodeGraphBuilder::VisitInvokeIntrinsic() {
2516
  PrepareEagerCheckpoint();
2517
  Runtime::FunctionId functionId = bytecode_iterator().GetIntrinsicIdOperand(0);
2518 2519
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2520 2521 2522

  // Create node to perform the runtime call. Turbofan will take care of the
  // lowering.
2523 2524
  const Operator* call = javascript()->CallRuntime(functionId, reg_count);
  Node* value = ProcessCallRuntimeArguments(call, receiver, reg_count);
2525
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2526 2527
}

2528
void BytecodeGraphBuilder::VisitThrow() {
2529
  BuildLoopExitsForFunctionExit(bytecode_analysis().GetInLivenessFor(
2530
      bytecode_iterator().current_offset()));
2531
  Node* value = environment()->LookupAccumulator();
2532
  Node* call = NewNode(javascript()->CallRuntime(Runtime::kThrow), value);
2533
  environment()->BindAccumulator(call, Environment::kAttachFrameState);
2534
  Node* control = NewNode(common()->Throw());
2535
  MergeControlToLeaveFunction(control);
2536 2537
}

2538
void BytecodeGraphBuilder::VisitAbort() {
2539
  BuildLoopExitsForFunctionExit(bytecode_analysis().GetInLivenessFor(
2540
      bytecode_iterator().current_offset()));
2541 2542
  AbortReason reason =
      static_cast<AbortReason>(bytecode_iterator().GetIndexOperand(0));
2543 2544 2545 2546 2547
  NewNode(simplified()->RuntimeAbort(reason));
  Node* control = NewNode(common()->Throw());
  MergeControlToLeaveFunction(control);
}

2548
void BytecodeGraphBuilder::VisitReThrow() {
2549
  BuildLoopExitsForFunctionExit(bytecode_analysis().GetInLivenessFor(
2550
      bytecode_iterator().current_offset()));
2551
  Node* value = environment()->LookupAccumulator();
2552 2553
  NewNode(javascript()->CallRuntime(Runtime::kReThrow), value);
  Node* control = NewNode(common()->Throw());
2554
  MergeControlToLeaveFunction(control);
2555 2556
}

2557 2558 2559 2560 2561 2562 2563 2564
void BytecodeGraphBuilder::BuildHoleCheckAndThrow(
    Node* condition, Runtime::FunctionId runtime_id, Node* name) {
  Node* accumulator = environment()->LookupAccumulator();
  NewBranch(condition, BranchHint::kFalse);
  {
    SubEnvironment sub_environment(this);

    NewIfTrue();
2565
    BuildLoopExitsForFunctionExit(bytecode_analysis().GetInLivenessFor(
2566
        bytecode_iterator().current_offset()));
2567 2568
    Node* node;
    const Operator* op = javascript()->CallRuntime(runtime_id);
2569
    if (runtime_id == Runtime::kThrowAccessedUninitializedVariable) {
2570
      DCHECK_NOT_NULL(name);
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
      node = NewNode(op, name);
    } else {
      DCHECK(runtime_id == Runtime::kThrowSuperAlreadyCalledError ||
             runtime_id == Runtime::kThrowSuperNotCalled);
      node = NewNode(op);
    }
    environment()->RecordAfterState(node, Environment::kAttachFrameState);
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }
  NewIfFalse();
  environment()->BindAccumulator(accumulator);
}

void BytecodeGraphBuilder::VisitThrowReferenceErrorIfHole() {
2586 2587 2588
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
2589 2590
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
2591 2592
  BuildHoleCheckAndThrow(check_for_hole,
                         Runtime::kThrowAccessedUninitializedVariable, name);
2593 2594 2595
}

void BytecodeGraphBuilder::VisitThrowSuperNotCalledIfHole() {
2596 2597 2598 2599
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
  BuildHoleCheckAndThrow(check_for_hole, Runtime::kThrowSuperNotCalled);
2600 2601 2602
}

void BytecodeGraphBuilder::VisitThrowSuperAlreadyCalledIfNotHole() {
2603 2604 2605 2606 2607 2608 2609
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
  Node* check_for_not_hole =
      NewNode(simplified()->BooleanNot(), check_for_hole);
  BuildHoleCheckAndThrow(check_for_not_hole,
                         Runtime::kThrowSuperAlreadyCalledError);
2610 2611
}

2612 2613 2614 2615
void BytecodeGraphBuilder::BuildUnaryOp(const Operator* op) {
  PrepareEagerCheckpoint();
  Node* operand = environment()->LookupAccumulator();

2616 2617
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kUnaryOperationHintIndex);
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedUnaryOp(op, operand, slot);
  if (lowering.IsExit()) return;

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(op, operand);
  }

  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

2633
void BytecodeGraphBuilder::BuildBinaryOp(const Operator* op) {
2634
  PrepareEagerCheckpoint();
2635 2636
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2637
  Node* right = environment()->LookupAccumulator();
2638

2639 2640
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kBinaryOperationHintIndex);
2641 2642
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2643
  if (lowering.IsExit()) return;
2644 2645 2646 2647

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2648
  } else {
2649
    DCHECK(!lowering.Changed());
2650 2651 2652
    node = NewNode(op, left, right);
  }

2653
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2654 2655
}

2656 2657
// Helper function to create binary operation hint from the recorded type
// feedback.
2658 2659
BinaryOperationHint BytecodeGraphBuilder::GetBinaryOperationHint(
    int operand_index) {
2660 2661
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(operand_index);
  FeedbackNexus nexus(feedback_vector(), slot);
2662
  return nexus.GetBinaryOperationFeedback();
2663 2664
}

2665 2666 2667
// Helper function to create compare operation hint from the recorded type
// feedback.
CompareOperationHint BytecodeGraphBuilder::GetCompareOperationHint() {
2668 2669
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
  FeedbackNexus nexus(feedback_vector(), slot);
2670
  return nexus.GetCompareOperationFeedback();
2671 2672
}

2673 2674
// Helper function to create for-in mode from the recorded type feedback.
ForInMode BytecodeGraphBuilder::GetForInMode(int operand_index) {
2675 2676
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(operand_index);
  FeedbackNexus nexus(feedback_vector(), slot);
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
  switch (nexus.GetForInFeedback()) {
    case ForInHint::kNone:
    case ForInHint::kEnumCacheKeysAndIndices:
      return ForInMode::kUseEnumCacheKeysAndIndices;
    case ForInHint::kEnumCacheKeys:
      return ForInMode::kUseEnumCacheKeys;
    case ForInHint::kAny:
      return ForInMode::kGeneric;
  }
  UNREACHABLE();
}

2689 2690
CallFrequency BytecodeGraphBuilder::ComputeCallFrequency(int slot_id) const {
  if (invocation_frequency_.IsUnknown()) return CallFrequency();
2691
  FeedbackNexus nexus(feedback_vector(), FeedbackVector::ToSlot(slot_id));
2692 2693 2694 2695 2696 2697 2698
  float feedback_frequency = nexus.ComputeCallFrequency();
  if (feedback_frequency == 0.0f) {
    // This is to prevent multiplying zero and infinity.
    return CallFrequency(0.0f);
  } else {
    return CallFrequency(feedback_frequency * invocation_frequency_.value());
  }
2699 2700
}

2701
SpeculationMode BytecodeGraphBuilder::GetSpeculationMode(int slot_id) const {
2702
  FeedbackNexus nexus(feedback_vector(), FeedbackVector::ToSlot(slot_id));
2703 2704 2705
  return nexus.GetSpeculationMode();
}

2706
void BytecodeGraphBuilder::VisitBitwiseNot() {
2707 2708
  BuildUnaryOp(javascript()->BitwiseNot());
}
2709

2710 2711 2712
void BytecodeGraphBuilder::VisitDec() {
  BuildUnaryOp(javascript()->Decrement());
}
2713

2714 2715
void BytecodeGraphBuilder::VisitInc() {
  BuildUnaryOp(javascript()->Increment());
2716 2717
}

2718
void BytecodeGraphBuilder::VisitNegate() {
2719
  BuildUnaryOp(javascript()->Negate());
2720 2721
}

2722
void BytecodeGraphBuilder::VisitAdd() {
2723 2724
  BuildBinaryOp(
      javascript()->Add(GetBinaryOperationHint(kBinaryOperationHintIndex)));
2725 2726
}

2727
void BytecodeGraphBuilder::VisitSub() {
2728
  BuildBinaryOp(javascript()->Subtract());
2729 2730
}

2731
void BytecodeGraphBuilder::VisitMul() {
2732
  BuildBinaryOp(javascript()->Multiply());
2733 2734
}

2735
void BytecodeGraphBuilder::VisitDiv() { BuildBinaryOp(javascript()->Divide()); }
2736

2737
void BytecodeGraphBuilder::VisitMod() {
2738
  BuildBinaryOp(javascript()->Modulus());
2739 2740
}

2741 2742 2743 2744
void BytecodeGraphBuilder::VisitExp() {
  BuildBinaryOp(javascript()->Exponentiate());
}

2745
void BytecodeGraphBuilder::VisitBitwiseOr() {
2746
  BuildBinaryOp(javascript()->BitwiseOr());
2747 2748
}

2749
void BytecodeGraphBuilder::VisitBitwiseXor() {
2750
  BuildBinaryOp(javascript()->BitwiseXor());
2751 2752
}

2753
void BytecodeGraphBuilder::VisitBitwiseAnd() {
2754
  BuildBinaryOp(javascript()->BitwiseAnd());
2755 2756
}

2757
void BytecodeGraphBuilder::VisitShiftLeft() {
2758
  BuildBinaryOp(javascript()->ShiftLeft());
2759 2760
}

2761
void BytecodeGraphBuilder::VisitShiftRight() {
2762
  BuildBinaryOp(javascript()->ShiftRight());
2763 2764
}

2765
void BytecodeGraphBuilder::VisitShiftRightLogical() {
2766
  BuildBinaryOp(javascript()->ShiftRightLogical());
2767 2768
}

2769
void BytecodeGraphBuilder::BuildBinaryOpWithImmediate(const Operator* op) {
2770
  PrepareEagerCheckpoint();
2771
  Node* left = environment()->LookupAccumulator();
2772
  Node* right = jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
2773

2774 2775
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kBinaryOperationSmiHintIndex);
2776 2777
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2778 2779
  if (lowering.IsExit()) return;

2780 2781 2782
  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2783
  } else {
2784
    DCHECK(!lowering.Changed());
2785 2786
    node = NewNode(op, left, right);
  }
2787
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2788 2789 2790
}

void BytecodeGraphBuilder::VisitAddSmi() {
2791 2792
  BuildBinaryOpWithImmediate(
      javascript()->Add(GetBinaryOperationHint(kBinaryOperationSmiHintIndex)));
2793 2794 2795
}

void BytecodeGraphBuilder::VisitSubSmi() {
2796
  BuildBinaryOpWithImmediate(javascript()->Subtract());
2797 2798
}

2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
void BytecodeGraphBuilder::VisitMulSmi() {
  BuildBinaryOpWithImmediate(javascript()->Multiply());
}

void BytecodeGraphBuilder::VisitDivSmi() {
  BuildBinaryOpWithImmediate(javascript()->Divide());
}

void BytecodeGraphBuilder::VisitModSmi() {
  BuildBinaryOpWithImmediate(javascript()->Modulus());
}

2811 2812 2813 2814
void BytecodeGraphBuilder::VisitExpSmi() {
  BuildBinaryOpWithImmediate(javascript()->Exponentiate());
}

2815
void BytecodeGraphBuilder::VisitBitwiseOrSmi() {
2816
  BuildBinaryOpWithImmediate(javascript()->BitwiseOr());
2817 2818
}

2819 2820 2821 2822
void BytecodeGraphBuilder::VisitBitwiseXorSmi() {
  BuildBinaryOpWithImmediate(javascript()->BitwiseXor());
}

2823
void BytecodeGraphBuilder::VisitBitwiseAndSmi() {
2824
  BuildBinaryOpWithImmediate(javascript()->BitwiseAnd());
2825 2826 2827
}

void BytecodeGraphBuilder::VisitShiftLeftSmi() {
2828
  BuildBinaryOpWithImmediate(javascript()->ShiftLeft());
2829 2830 2831
}

void BytecodeGraphBuilder::VisitShiftRightSmi() {
2832
  BuildBinaryOpWithImmediate(javascript()->ShiftRight());
2833 2834
}

2835 2836 2837 2838
void BytecodeGraphBuilder::VisitShiftRightLogicalSmi() {
  BuildBinaryOpWithImmediate(javascript()->ShiftRightLogical());
}

2839
void BytecodeGraphBuilder::VisitLogicalNot() {
2840
  Node* value = environment()->LookupAccumulator();
2841
  Node* node = NewNode(simplified()->BooleanNot(), value);
2842 2843 2844 2845
  environment()->BindAccumulator(node);
}

void BytecodeGraphBuilder::VisitToBooleanLogicalNot() {
2846 2847
  Node* value =
      NewNode(simplified()->ToBoolean(), environment()->LookupAccumulator());
2848
  Node* node = NewNode(simplified()->BooleanNot(), value);
2849
  environment()->BindAccumulator(node);
2850 2851
}

2852
void BytecodeGraphBuilder::VisitTypeOf() {
2853
  Node* node =
2854
      NewNode(simplified()->TypeOf(), environment()->LookupAccumulator());
2855 2856 2857
  environment()->BindAccumulator(node);
}

2858
void BytecodeGraphBuilder::BuildDelete(LanguageMode language_mode) {
2859
  PrepareEagerCheckpoint();
2860
  Node* key = environment()->LookupAccumulator();
2861 2862
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2863 2864
  Node* mode = jsgraph()->Constant(static_cast<int32_t>(language_mode));
  Node* node = NewNode(javascript()->DeleteProperty(), object, key, mode);
2865
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2866 2867
}

2868
void BytecodeGraphBuilder::VisitDeletePropertyStrict() {
2869
  BuildDelete(LanguageMode::kStrict);
2870 2871
}

2872
void BytecodeGraphBuilder::VisitDeletePropertySloppy() {
2873
  BuildDelete(LanguageMode::kSloppy);
2874 2875
}

2876 2877 2878 2879 2880 2881 2882
void BytecodeGraphBuilder::VisitGetSuperConstructor() {
  Node* node = NewNode(javascript()->GetSuperConstructor(),
                       environment()->LookupAccumulator());
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), node,
                              Environment::kAttachFrameState);
}

2883
void BytecodeGraphBuilder::BuildCompareOp(const Operator* op) {
2884
  PrepareEagerCheckpoint();
2885 2886
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2887
  Node* right = environment()->LookupAccumulator();
2888

2889
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
2890 2891
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2892 2893
  if (lowering.IsExit()) return;

2894
  Node* node = nullptr;
2895 2896
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2897
  } else {
2898
    DCHECK(!lowering.Changed());
2899 2900
    node = NewNode(op, left, right);
  }
2901
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2902 2903
}

2904
void BytecodeGraphBuilder::VisitTestEqual() {
2905
  BuildCompareOp(javascript()->Equal(GetCompareOperationHint()));
2906 2907
}

2908
void BytecodeGraphBuilder::VisitTestEqualStrict() {
2909
  BuildCompareOp(javascript()->StrictEqual(GetCompareOperationHint()));
2910 2911
}

2912
void BytecodeGraphBuilder::VisitTestLessThan() {
2913
  BuildCompareOp(javascript()->LessThan(GetCompareOperationHint()));
2914 2915
}

2916
void BytecodeGraphBuilder::VisitTestGreaterThan() {
2917
  BuildCompareOp(javascript()->GreaterThan(GetCompareOperationHint()));
2918 2919
}

2920
void BytecodeGraphBuilder::VisitTestLessThanOrEqual() {
2921
  BuildCompareOp(javascript()->LessThanOrEqual(GetCompareOperationHint()));
2922 2923
}

2924
void BytecodeGraphBuilder::VisitTestGreaterThanOrEqual() {
2925
  BuildCompareOp(javascript()->GreaterThanOrEqual(GetCompareOperationHint()));
2926 2927
}

2928
void BytecodeGraphBuilder::VisitTestReferenceEqual() {
2929 2930 2931
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* right = environment()->LookupAccumulator();
2932 2933
  Node* result = NewNode(simplified()->ReferenceEqual(), left, right);
  environment()->BindAccumulator(result);
2934 2935
}

2936
void BytecodeGraphBuilder::VisitTestIn() {
2937
  PrepareEagerCheckpoint();
2938 2939
  Node* object = environment()->LookupAccumulator();
  Node* key =
2940
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2941 2942 2943
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(1));
  Node* node = NewNode(javascript()->HasProperty(feedback), object, key);
2944 2945 2946
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

2947
void BytecodeGraphBuilder::VisitTestInstanceOf() {
2948 2949
  int const slot_index = bytecode_iterator().GetIndexOperand(1);
  BuildCompareOp(javascript()->InstanceOf(CreateVectorSlotPair(slot_index)));
2950 2951
}

2952
void BytecodeGraphBuilder::VisitTestUndetectable() {
2953
  Node* object = environment()->LookupAccumulator();
2954 2955 2956 2957
  Node* node = NewNode(jsgraph()->simplified()->ObjectIsUndetectable(), object);
  environment()->BindAccumulator(node);
}

2958
void BytecodeGraphBuilder::VisitTestNull() {
2959
  Node* object = environment()->LookupAccumulator();
2960 2961
  Node* result = NewNode(simplified()->ReferenceEqual(), object,
                         jsgraph()->NullConstant());
2962 2963 2964 2965
  environment()->BindAccumulator(result);
}

void BytecodeGraphBuilder::VisitTestUndefined() {
2966
  Node* object = environment()->LookupAccumulator();
2967 2968
  Node* result = NewNode(simplified()->ReferenceEqual(), object,
                         jsgraph()->UndefinedConstant());
2969 2970 2971
  environment()->BindAccumulator(result);
}

2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
void BytecodeGraphBuilder::VisitTestTypeOf() {
  Node* object = environment()->LookupAccumulator();
  auto literal_flag = interpreter::TestTypeOfFlags::Decode(
      bytecode_iterator().GetFlagOperand(0));
  Node* result;
  switch (literal_flag) {
    case interpreter::TestTypeOfFlags::LiteralFlag::kNumber:
      result = NewNode(simplified()->ObjectIsNumber(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kString:
      result = NewNode(simplified()->ObjectIsString(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kSymbol:
      result = NewNode(simplified()->ObjectIsSymbol(), object);
      break;
2987 2988 2989
    case interpreter::TestTypeOfFlags::LiteralFlag::kBigInt:
      result = NewNode(simplified()->ObjectIsBigInt(), object);
      break;
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
    case interpreter::TestTypeOfFlags::LiteralFlag::kBoolean:
      result = NewNode(common()->Select(MachineRepresentation::kTagged),
                       NewNode(simplified()->ReferenceEqual(), object,
                               jsgraph()->TrueConstant()),
                       jsgraph()->TrueConstant(),
                       NewNode(simplified()->ReferenceEqual(), object,
                               jsgraph()->FalseConstant()));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kUndefined:
      result = graph()->NewNode(
          common()->Select(MachineRepresentation::kTagged),
          graph()->NewNode(simplified()->ReferenceEqual(), object,
                           jsgraph()->NullConstant()),
          jsgraph()->FalseConstant(),
          graph()->NewNode(simplified()->ObjectIsUndetectable(), object));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kFunction:
      result =
          graph()->NewNode(simplified()->ObjectIsDetectableCallable(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kObject:
      result = graph()->NewNode(
          common()->Select(MachineRepresentation::kTagged),
          graph()->NewNode(simplified()->ObjectIsNonCallable(), object),
          jsgraph()->TrueConstant(),
          graph()->NewNode(simplified()->ReferenceEqual(), object,
                           jsgraph()->NullConstant()));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kOther:
      UNREACHABLE();  // Should never be emitted.
      break;
  }
  environment()->BindAccumulator(result);
}

3025 3026
void BytecodeGraphBuilder::BuildCastOperator(const Operator* js_op) {
  Node* value = NewNode(js_op, environment()->LookupAccumulator());
3027
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), value,
3028
                              Environment::kAttachFrameState);
3029 3030
}

3031 3032 3033 3034
void BytecodeGraphBuilder::VisitToName() {
  BuildCastOperator(javascript()->ToName());
}

3035
void BytecodeGraphBuilder::VisitToObject() {
3036
  BuildCastOperator(javascript()->ToObject());
3037 3038
}

3039 3040 3041 3042 3043 3044
void BytecodeGraphBuilder::VisitToString() {
  Node* value =
      NewNode(javascript()->ToString(), environment()->LookupAccumulator());
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
}

3045
void BytecodeGraphBuilder::VisitToNumber() {
3046 3047 3048
  PrepareEagerCheckpoint();
  Node* object = environment()->LookupAccumulator();

3049
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(0);
3050 3051 3052 3053 3054 3055
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedToNumber(object, slot);

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
3056
  } else {
3057
    DCHECK(!lowering.Changed());
3058 3059 3060
    node = NewNode(javascript()->ToNumber(), object);
  }

3061
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
3062 3063
}

3064
void BytecodeGraphBuilder::VisitToNumeric() {
3065 3066 3067 3068 3069
  PrepareEagerCheckpoint();
  Node* object = environment()->LookupAccumulator();

  // If we have some kind of Number feedback, we do the same lowering as for
  // ToNumber.
3070
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(0);
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedToNumber(object, slot);

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(javascript()->ToNumeric(), object);
  }

  environment()->BindAccumulator(node, Environment::kAttachFrameState);
3083 3084
}

3085
void BytecodeGraphBuilder::VisitJump() { BuildJump(); }
3086

3087
void BytecodeGraphBuilder::VisitJumpConstant() { BuildJump(); }
3088

3089
void BytecodeGraphBuilder::VisitJumpIfTrue() { BuildJumpIfTrue(); }
3090

3091
void BytecodeGraphBuilder::VisitJumpIfTrueConstant() { BuildJumpIfTrue(); }
3092

3093
void BytecodeGraphBuilder::VisitJumpIfFalse() { BuildJumpIfFalse(); }
3094

3095
void BytecodeGraphBuilder::VisitJumpIfFalseConstant() { BuildJumpIfFalse(); }
3096

3097
void BytecodeGraphBuilder::VisitJumpIfToBooleanTrue() {
3098
  BuildJumpIfToBooleanTrue();
3099 3100
}

3101
void BytecodeGraphBuilder::VisitJumpIfToBooleanTrueConstant() {
3102
  BuildJumpIfToBooleanTrue();
3103 3104
}

3105
void BytecodeGraphBuilder::VisitJumpIfToBooleanFalse() {
3106
  BuildJumpIfToBooleanFalse();
3107 3108
}

3109
void BytecodeGraphBuilder::VisitJumpIfToBooleanFalseConstant() {
3110
  BuildJumpIfToBooleanFalse();
3111
}
3112

3113 3114 3115 3116 3117 3118
void BytecodeGraphBuilder::VisitJumpIfJSReceiver() { BuildJumpIfJSReceiver(); }

void BytecodeGraphBuilder::VisitJumpIfJSReceiverConstant() {
  BuildJumpIfJSReceiver();
}

3119
void BytecodeGraphBuilder::VisitJumpIfNull() {
3120
  BuildJumpIfEqual(jsgraph()->NullConstant());
3121 3122
}

3123
void BytecodeGraphBuilder::VisitJumpIfNullConstant() {
3124 3125 3126
  BuildJumpIfEqual(jsgraph()->NullConstant());
}

3127 3128 3129 3130 3131 3132 3133 3134
void BytecodeGraphBuilder::VisitJumpIfNotNull() {
  BuildJumpIfNotEqual(jsgraph()->NullConstant());
}

void BytecodeGraphBuilder::VisitJumpIfNotNullConstant() {
  BuildJumpIfNotEqual(jsgraph()->NullConstant());
}

3135
void BytecodeGraphBuilder::VisitJumpIfUndefined() {
3136
  BuildJumpIfEqual(jsgraph()->UndefinedConstant());
3137 3138
}

3139
void BytecodeGraphBuilder::VisitJumpIfUndefinedConstant() {
3140 3141 3142
  BuildJumpIfEqual(jsgraph()->UndefinedConstant());
}

3143 3144 3145 3146 3147 3148 3149 3150
void BytecodeGraphBuilder::VisitJumpIfNotUndefined() {
  BuildJumpIfNotEqual(jsgraph()->UndefinedConstant());
}

void BytecodeGraphBuilder::VisitJumpIfNotUndefinedConstant() {
  BuildJumpIfNotEqual(jsgraph()->UndefinedConstant());
}

3151 3152
void BytecodeGraphBuilder::VisitJumpLoop() { BuildJump(); }

3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
void BytecodeGraphBuilder::BuildSwitchOnSmi(Node* condition) {
  interpreter::JumpTableTargetOffsets offsets =
      bytecode_iterator().GetJumpTableTargetOffsets();

  NewSwitch(condition, offsets.size() + 1);
  for (const auto& entry : offsets) {
    SubEnvironment sub_environment(this);
    NewIfValue(entry.case_value);
    MergeIntoSuccessorEnvironment(entry.target_offset);
  }
  NewIfDefault();
}

3166 3167 3168 3169
void BytecodeGraphBuilder::VisitSwitchOnSmiNoFeedback() {
  PrepareEagerCheckpoint();

  Node* acc = environment()->LookupAccumulator();
3170
  Node* acc_smi = NewNode(simplified()->CheckSmi(VectorSlotPair()), acc);
3171
  BuildSwitchOnSmi(acc_smi);
3172 3173
}

3174
void BytecodeGraphBuilder::VisitStackCheck() {
3175
  PrepareEagerCheckpoint();
3176
  Node* node = NewNode(javascript()->StackCheck());
3177
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
3178 3179
}

3180 3181 3182 3183 3184 3185
void BytecodeGraphBuilder::VisitSetPendingMessage() {
  Node* previous_message = NewNode(javascript()->LoadMessage());
  NewNode(javascript()->StoreMessage(), environment()->LookupAccumulator());
  environment()->BindAccumulator(previous_message);
}

3186 3187
void BytecodeGraphBuilder::BuildReturn(const BytecodeLivenessState* liveness) {
  BuildLoopExitsForFunctionExit(liveness);
3188
  Node* pop_node = jsgraph()->ZeroConstant();
3189
  Node* control =
3190
      NewNode(common()->Return(), pop_node, environment()->LookupAccumulator());
3191
  MergeControlToLeaveFunction(control);
3192 3193
}

3194
void BytecodeGraphBuilder::VisitReturn() {
3195
  BuildReturn(bytecode_analysis().GetInLivenessFor(
3196 3197 3198
      bytecode_iterator().current_offset()));
}

3199
void BytecodeGraphBuilder::VisitDebugger() {
3200
  PrepareEagerCheckpoint();
3201 3202
  Node* call = NewNode(javascript()->Debugger());
  environment()->RecordAfterState(call, Environment::kAttachFrameState);
3203 3204
}

3205 3206 3207
// We cannot create a graph from the debugger copy of the bytecode array.
#define DEBUG_BREAK(Name, ...) \
  void BytecodeGraphBuilder::Visit##Name() { UNREACHABLE(); }
3208
DEBUG_BREAK_BYTECODE_LIST(DEBUG_BREAK)
3209 3210
#undef DEBUG_BREAK

3211 3212 3213 3214 3215
void BytecodeGraphBuilder::VisitIncBlockCounter() {
  Node* closure = GetFunctionClosure();
  Node* coverage_array_slot =
      jsgraph()->Constant(bytecode_iterator().GetIndexOperand(0));

3216 3217 3218
  // Lowered by js-intrinsic-lowering to call Builtins::kIncBlockCounter.
  const Operator* op =
      javascript()->CallRuntime(Runtime::kInlineIncBlockCounter);
3219 3220 3221 3222

  NewNode(op, closure, coverage_array_slot);
}

3223
void BytecodeGraphBuilder::VisitForInEnumerate() {
3224 3225
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3226 3227 3228 3229 3230 3231 3232 3233
  Node* enumerator = NewNode(javascript()->ForInEnumerate(), receiver);
  environment()->BindAccumulator(enumerator, Environment::kAttachFrameState);
}

void BytecodeGraphBuilder::VisitForInPrepare() {
  PrepareEagerCheckpoint();
  Node* enumerator = environment()->LookupAccumulator();

3234
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
3235 3236 3237 3238 3239
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedForInPrepare(enumerator, slot);
  if (lowering.IsExit()) return;
  DCHECK(!lowering.Changed());
  Node* node = NewNode(javascript()->ForInPrepare(GetForInMode(1)), enumerator);
3240
  environment()->BindRegistersToProjections(
3241
      bytecode_iterator().GetRegisterOperand(0), node);
3242 3243
}

3244
void BytecodeGraphBuilder::VisitForInContinue() {
3245
  PrepareEagerCheckpoint();
3246 3247
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3248
  Node* cache_length =
3249
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
3250 3251 3252
  Node* exit_cond = NewNode(simplified()->SpeculativeNumberLessThan(
                                NumberOperationHint::kSignedSmall),
                            index, cache_length);
3253
  environment()->BindAccumulator(exit_cond);
3254 3255
}

3256
void BytecodeGraphBuilder::VisitForInNext() {
3257
  PrepareEagerCheckpoint();
3258
  Node* receiver =
3259 3260 3261 3262
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int catch_reg_pair_index = bytecode_iterator().GetRegisterOperand(2).index();
3263 3264 3265 3266 3267
  Node* cache_type = environment()->LookupRegister(
      interpreter::Register(catch_reg_pair_index));
  Node* cache_array = environment()->LookupRegister(
      interpreter::Register(catch_reg_pair_index + 1));

3268 3269 3270
  // We need to rename the {index} here, as in case of OSR we loose the
  // information that the {index} is always a valid unsigned Smi value.
  index = graph()->NewNode(common()->TypeGuard(Type::UnsignedSmall()), index,
3271
                           environment()->GetEffectDependency(),
3272
                           environment()->GetControlDependency());
3273
  environment()->UpdateEffectDependency(index);
3274

3275
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(3);
3276 3277 3278 3279
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedForInNext(
      receiver, cache_array, cache_type, index, slot);
  if (lowering.IsExit()) return;

3280 3281 3282
  DCHECK(!lowering.Changed());
  Node* node = NewNode(javascript()->ForInNext(GetForInMode(3)), receiver,
                       cache_array, cache_type, index);
3283
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
3284 3285
}

3286
void BytecodeGraphBuilder::VisitForInStep() {
3287
  PrepareEagerCheckpoint();
3288 3289
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3290 3291 3292
  index = NewNode(simplified()->SpeculativeSafeIntegerAdd(
                      NumberOperationHint::kSignedSmall),
                  index, jsgraph()->OneConstant());
3293
  environment()->BindAccumulator(index, Environment::kAttachFrameState);
3294 3295
}

3296
void BytecodeGraphBuilder::VisitSuspendGenerator() {
3297 3298
  Node* generator = environment()->LookupRegister(
      bytecode_iterator().GetRegisterOperand(0));
3299 3300 3301 3302 3303
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  // We assume we are storing a range starting from index 0.
  CHECK_EQ(0, first_reg.index());
  int register_count =
      static_cast<int>(bytecode_iterator().GetRegisterCountOperand(2));
3304 3305 3306
  int parameter_count_without_receiver =
      bytecode_array()->parameter_count() - 1;

3307 3308
  Node* suspend_id = jsgraph()->SmiConstant(
      bytecode_iterator().GetUnsignedImmediateOperand(3));
3309

3310 3311 3312 3313 3314
  // The offsets used by the bytecode iterator are relative to a different base
  // than what is used in the interpreter, hence the addition.
  Node* offset =
      jsgraph()->Constant(bytecode_iterator().current_offset() +
                          (BytecodeArray::kHeaderSize - kHeapObjectTag));
3315

3316
  const BytecodeLivenessState* liveness = bytecode_analysis().GetInLivenessFor(
3317 3318 3319 3320 3321 3322
      bytecode_iterator().current_offset());

  // Maybe overallocate the value list since we don't know how many registers
  // are live.
  // TODO(leszeks): We could get this count from liveness rather than the
  // register list.
3323
  int value_input_count = 3 + parameter_count_without_receiver + register_count;
3324 3325 3326

  Node** value_inputs = local_zone()->NewArray<Node*>(value_input_count);
  value_inputs[0] = generator;
3327
  value_inputs[1] = suspend_id;
3328
  value_inputs[2] = offset;
3329 3330

  int count_written = 0;
3331 3332 3333 3334 3335 3336 3337 3338
  // Store the parameters.
  for (int i = 0; i < parameter_count_without_receiver; i++) {
    value_inputs[3 + count_written++] =
        environment()->LookupRegister(interpreter::Register::FromParameterIndex(
            i, parameter_count_without_receiver));
  }

  // Store the registers.
3339
  for (int i = 0; i < register_count; ++i) {
3340
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
3341 3342 3343
      int index_in_parameters_and_registers =
          parameter_count_without_receiver + i;
      while (count_written < index_in_parameters_and_registers) {
3344 3345 3346 3347
        value_inputs[3 + count_written++] = jsgraph()->OptimizedOutConstant();
      }
      value_inputs[3 + count_written++] =
          environment()->LookupRegister(interpreter::Register(i));
3348
      DCHECK_EQ(count_written, index_in_parameters_and_registers + 1);
3349
    }
3350 3351
  }

3352 3353 3354
  // Use the actual written count rather than the register count to create the
  // node.
  MakeNode(javascript()->GeneratorStore(count_written), 3 + count_written,
3355
           value_inputs, false);
3356 3357 3358

  // TODO(leszeks): This over-approximates the liveness at exit, only the
  // accumulator should be live by this point.
3359
  BuildReturn(bytecode_analysis().GetInLivenessFor(
3360
      bytecode_iterator().current_offset()));
3361 3362
}

3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
void BytecodeGraphBuilder::BuildSwitchOnGeneratorState(
    const ZoneVector<ResumeJumpTarget>& resume_jump_targets,
    bool allow_fallthrough_on_executing) {
  Node* generator_state = environment()->LookupGeneratorState();

  int extra_cases = allow_fallthrough_on_executing ? 2 : 1;
  NewSwitch(generator_state,
            static_cast<int>(resume_jump_targets.size() + extra_cases));
  for (const ResumeJumpTarget& target : resume_jump_targets) {
    SubEnvironment sub_environment(this);
    NewIfValue(target.suspend_id());
    if (target.is_leaf()) {
      // Mark that we are resuming executing.
      environment()->BindGeneratorState(
          jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
    }
    // Jump to the target offset, whether it's a loop header or the resume.
    MergeIntoSuccessorEnvironment(target.target_offset());
  }

  {
    SubEnvironment sub_environment(this);
    // We should never hit the default case (assuming generator state cannot be
    // corrupted), so abort if we do.
    // TODO(leszeks): Maybe only check this in debug mode, and otherwise use
    // the default to represent one of the cases above/fallthrough below?
    NewIfDefault();
    NewNode(simplified()->RuntimeAbort(AbortReason::kInvalidJumpTableIndex));
3391
    // TODO(7099): Investigate if we need LoopExit here.
3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }

  if (allow_fallthrough_on_executing) {
    // If we are executing (rather than resuming), and we allow it, just fall
    // through to the actual loop body.
    NewIfValue(JSGeneratorObject::kGeneratorExecuting);
  } else {
    // Otherwise, this environment is dead.
    set_environment(nullptr);
  }
}

void BytecodeGraphBuilder::VisitSwitchOnGeneratorState() {
  Node* generator =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3409

3410 3411 3412
  Node* generator_is_undefined =
      NewNode(simplified()->ReferenceEqual(), generator,
              jsgraph()->UndefinedConstant());
3413

3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
  NewBranch(generator_is_undefined);
  {
    SubEnvironment resume_env(this);
    NewIfFalse();

    Node* generator_state =
        NewNode(javascript()->GeneratorRestoreContinuation(), generator);
    environment()->BindGeneratorState(generator_state);

    Node* generator_context =
        NewNode(javascript()->GeneratorRestoreContext(), generator);
    environment()->SetContext(generator_context);

3427
    BuildSwitchOnGeneratorState(bytecode_analysis().resume_jump_targets(),
3428 3429
                                false);
  }
3430

3431 3432
  // Fallthrough for the first-call case.
  NewIfTrue();
3433 3434
}

3435
void BytecodeGraphBuilder::VisitResumeGenerator() {
3436 3437
  Node* generator =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3438
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
3439 3440
  // We assume we are restoring registers starting fromm index 0.
  CHECK_EQ(0, first_reg.index());
3441

3442 3443
  const BytecodeLivenessState* liveness = bytecode_analysis().GetOutLivenessFor(
      bytecode_iterator().current_offset());
3444

3445 3446 3447 3448 3449
  int parameter_count_without_receiver =
      bytecode_array()->parameter_count() - 1;

  // Mapping between registers and array indices must match that used in
  // InterpreterAssembler::ExportParametersAndRegisterFile.
3450 3451
  for (int i = 0; i < environment()->register_count(); ++i) {
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
3452 3453 3454
      Node* value = NewNode(javascript()->GeneratorRestoreRegister(
                                parameter_count_without_receiver + i),
                            generator);
3455 3456
      environment()->BindRegister(interpreter::Register(i), value);
    }
3457
  }
3458 3459 3460 3461 3462

  // Update the accumulator with the generator's input_or_debug_pos.
  Node* input_or_debug_pos =
      NewNode(javascript()->GeneratorRestoreInputOrDebugPos(), generator);
  environment()->BindAccumulator(input_or_debug_pos);
3463 3464
}

3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
void BytecodeGraphBuilder::VisitWide() {
  // Consumed by the BytecodeArrayIterator.
  UNREACHABLE();
}

void BytecodeGraphBuilder::VisitExtraWide() {
  // Consumed by the BytecodeArrayIterator.
  UNREACHABLE();
}

void BytecodeGraphBuilder::VisitIllegal() {
3476 3477
  // Not emitted in valid bytecode.
  UNREACHABLE();
3478 3479
}

3480
void BytecodeGraphBuilder::SwitchToMergeEnvironment(int current_offset) {
3481 3482
  auto it = merge_environments_.find(current_offset);
  if (it != merge_environments_.end()) {
3483
    mark_as_needing_eager_checkpoint(true);
3484
    if (environment() != nullptr) {
3485
      it->second->Merge(environment(),
3486
                        bytecode_analysis().GetInLivenessFor(current_offset));
3487
    }
3488
    set_environment(it->second);
3489 3490 3491
  }
}

3492
void BytecodeGraphBuilder::BuildLoopHeaderEnvironment(int current_offset) {
3493
  if (bytecode_analysis().IsLoopHeader(current_offset)) {
3494
    mark_as_needing_eager_checkpoint(true);
3495
    const LoopInfo& loop_info =
3496
        bytecode_analysis().GetLoopInfoFor(current_offset);
3497
    const BytecodeLivenessState* liveness =
3498
        bytecode_analysis().GetInLivenessFor(current_offset);
3499

3500 3501 3502
    const auto& resume_jump_targets = loop_info.resume_jump_targets();
    bool generate_suspend_switch = !resume_jump_targets.empty();

3503
    // Add loop header.
3504
    environment()->PrepareForLoop(loop_info.assignments(), liveness);
3505 3506 3507 3508

    // Store a copy of the environment so we can connect merged back edge inputs
    // to the loop header.
    merge_environments_[current_offset] = environment()->Copy();
3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522

    // If this loop contains resumes, create a new switch just after the loop
    // for those resumes.
    if (generate_suspend_switch) {
      BuildSwitchOnGeneratorState(loop_info.resume_jump_targets(), true);

      // TODO(leszeks): At this point we know we are executing rather than
      // resuming, so we should be able to prune off the phis in the environment
      // related to the resume path.

      // Set the generator state to a known constant.
      environment()->BindGeneratorState(
          jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
    }
3523 3524 3525
  }
}

3526
void BytecodeGraphBuilder::MergeIntoSuccessorEnvironment(int target_offset) {
3527
  BuildLoopExitsForBranch(target_offset);
3528
  Environment*& merge_environment = merge_environments_[target_offset];
3529

3530
  if (merge_environment == nullptr) {
3531 3532 3533 3534 3535
    // Append merge nodes to the environment. We may merge here with another
    // environment. So add a place holder for merge nodes. We may add redundant
    // but will be eliminated in a later pass.
    // TODO(mstarzinger): Be smarter about this!
    NewMerge();
3536
    merge_environment = environment();
3537
  } else {
3538 3539
    // Merge any values which are live coming into the successor.
    merge_environment->Merge(
3540
        environment(), bytecode_analysis().GetInLivenessFor(target_offset));
3541 3542 3543 3544
  }
  set_environment(nullptr);
}

3545 3546 3547 3548
void BytecodeGraphBuilder::MergeControlToLeaveFunction(Node* exit) {
  exit_controls_.push_back(exit);
  set_environment(nullptr);
}
3549

3550 3551 3552 3553
void BytecodeGraphBuilder::BuildLoopExitsForBranch(int target_offset) {
  int origin_offset = bytecode_iterator().current_offset();
  // Only build loop exits for forward edges.
  if (target_offset > origin_offset) {
3554
    BuildLoopExitsUntilLoop(
3555 3556
        bytecode_analysis().GetLoopOffsetFor(target_offset),
        bytecode_analysis().GetInLivenessFor(target_offset));
3557 3558 3559
  }
}

3560 3561
void BytecodeGraphBuilder::BuildLoopExitsUntilLoop(
    int loop_offset, const BytecodeLivenessState* liveness) {
3562
  int origin_offset = bytecode_iterator().current_offset();
3563
  int current_loop = bytecode_analysis().GetLoopOffsetFor(origin_offset);
3564 3565 3566 3567
  // The limit_offset is the stop offset for building loop exists, used for OSR.
  // It prevents the creations of loopexits for loops which do not exist.
  loop_offset = std::max(loop_offset, currently_peeled_loop_offset_);

3568 3569
  while (loop_offset < current_loop) {
    Node* loop_node = merge_environments_[current_loop]->GetControlDependency();
3570
    const LoopInfo& loop_info =
3571
        bytecode_analysis().GetLoopInfoFor(current_loop);
3572 3573
    environment()->PrepareForLoopExit(loop_node, loop_info.assignments(),
                                      liveness);
3574
    current_loop = loop_info.parent_offset();
3575 3576 3577
  }
}

3578 3579 3580
void BytecodeGraphBuilder::BuildLoopExitsForFunctionExit(
    const BytecodeLivenessState* liveness) {
  BuildLoopExitsUntilLoop(-1, liveness);
3581 3582
}

3583
void BytecodeGraphBuilder::BuildJump() {
3584
  MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
3585 3586
}

3587
void BytecodeGraphBuilder::BuildJumpIf(Node* condition) {
3588
  NewBranch(condition, BranchHint::kNone, IsSafetyCheck::kNoSafetyCheck);
3589 3590 3591 3592 3593
  {
    SubEnvironment sub_environment(this);
    NewIfTrue();
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
3594 3595 3596
  NewIfFalse();
}

3597
void BytecodeGraphBuilder::BuildJumpIfNot(Node* condition) {
3598
  NewBranch(condition, BranchHint::kNone, IsSafetyCheck::kNoSafetyCheck);
3599 3600 3601 3602 3603
  {
    SubEnvironment sub_environment(this);
    NewIfFalse();
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
3604 3605
  NewIfTrue();
}
3606

3607
void BytecodeGraphBuilder::BuildJumpIfEqual(Node* comperand) {
3608
  Node* accumulator = environment()->LookupAccumulator();
3609
  Node* condition =
3610
      NewNode(simplified()->ReferenceEqual(), accumulator, comperand);
3611
  BuildJumpIf(condition);
3612 3613
}

3614 3615 3616 3617 3618 3619 3620
void BytecodeGraphBuilder::BuildJumpIfNotEqual(Node* comperand) {
  Node* accumulator = environment()->LookupAccumulator();
  Node* condition =
      NewNode(simplified()->ReferenceEqual(), accumulator, comperand);
  BuildJumpIfNot(condition);
}

3621
void BytecodeGraphBuilder::BuildJumpIfFalse() {
3622
  NewBranch(environment()->LookupAccumulator(), BranchHint::kNone,
3623
            IsSafetyCheck::kNoSafetyCheck);
3624 3625 3626 3627 3628 3629 3630 3631
  {
    SubEnvironment sub_environment(this);
    NewIfFalse();
    environment()->BindAccumulator(jsgraph()->FalseConstant());
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
  NewIfTrue();
  environment()->BindAccumulator(jsgraph()->TrueConstant());
3632
}
3633

3634
void BytecodeGraphBuilder::BuildJumpIfTrue() {
3635
  NewBranch(environment()->LookupAccumulator(), BranchHint::kNone,
3636
            IsSafetyCheck::kNoSafetyCheck);
3637 3638 3639 3640 3641 3642 3643 3644
  {
    SubEnvironment sub_environment(this);
    NewIfTrue();
    environment()->BindAccumulator(jsgraph()->TrueConstant());
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
  NewIfFalse();
  environment()->BindAccumulator(jsgraph()->FalseConstant());
3645 3646 3647
}

void BytecodeGraphBuilder::BuildJumpIfToBooleanTrue() {
3648
  Node* accumulator = environment()->LookupAccumulator();
3649
  Node* condition = NewNode(simplified()->ToBoolean(), accumulator);
3650 3651 3652 3653 3654
  BuildJumpIf(condition);
}

void BytecodeGraphBuilder::BuildJumpIfToBooleanFalse() {
  Node* accumulator = environment()->LookupAccumulator();
3655
  Node* condition = NewNode(simplified()->ToBoolean(), accumulator);
3656
  BuildJumpIfNot(condition);
3657 3658
}

3659 3660
void BytecodeGraphBuilder::BuildJumpIfNotHole() {
  Node* accumulator = environment()->LookupAccumulator();
3661 3662
  Node* condition = NewNode(simplified()->ReferenceEqual(), accumulator,
                            jsgraph()->TheHoleConstant());
3663
  BuildJumpIfNot(condition);
3664
}
3665

3666 3667 3668 3669 3670 3671
void BytecodeGraphBuilder::BuildJumpIfJSReceiver() {
  Node* accumulator = environment()->LookupAccumulator();
  Node* condition = NewNode(simplified()->ObjectIsReceiver(), accumulator);
  BuildJumpIf(condition);
}

3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedUnaryOp(const Operator* op,
                                                Node* operand,
                                                FeedbackSlot slot) {
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceUnaryOperation(op, operand, effect, control,
                                                slot);
  ApplyEarlyReduction(result);
  return result;
}

3685 3686 3687 3688
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedBinaryOp(const Operator* op, Node* left,
                                                 Node* right,
                                                 FeedbackSlot slot) {
3689 3690
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3691 3692 3693 3694 3695
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceBinaryOperation(op, left, right, effect,
                                                 control, slot);
  ApplyEarlyReduction(result);
  return result;
3696 3697
}

3698 3699 3700 3701 3702
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedForInNext(Node* receiver,
                                                  Node* cache_array,
                                                  Node* cache_type, Node* index,
                                                  FeedbackSlot slot) {
3703 3704
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3705 3706 3707
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceForInNextOperation(
          receiver, cache_array, cache_type, index, effect, control, slot);
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
  ApplyEarlyReduction(result);
  return result;
}

JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedForInPrepare(Node* enumerator,
                                                     FeedbackSlot slot) {
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceForInPrepareOperation(enumerator, effect,
                                                       control, slot);
3720 3721
  ApplyEarlyReduction(result);
  return result;
3722 3723
}

3724 3725 3726
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedToNumber(Node* value,
                                                 FeedbackSlot slot) {
3727 3728
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3729 3730 3731 3732 3733
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceToNumberOperation(value, effect, control,
                                                   slot);
  ApplyEarlyReduction(result);
  return result;
3734 3735
}

3736 3737
JSTypeHintLowering::LoweringResult BytecodeGraphBuilder::TryBuildSimplifiedCall(
    const Operator* op, Node* const* args, int arg_count, FeedbackSlot slot) {
3738 3739
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3740 3741 3742 3743 3744
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceCallOperation(op, args, arg_count, effect,
                                               control, slot);
  ApplyEarlyReduction(result);
  return result;
3745 3746
}

3747 3748 3749 3750 3751
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedConstruct(const Operator* op,
                                                  Node* const* args,
                                                  int arg_count,
                                                  FeedbackSlot slot) {
3752 3753
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3754 3755 3756 3757 3758
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceConstructOperation(op, args, arg_count, effect,
                                                    control, slot);
  ApplyEarlyReduction(result);
  return result;
3759 3760
}

3761 3762 3763 3764
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedLoadNamed(const Operator* op,
                                                  Node* receiver,
                                                  FeedbackSlot slot) {
3765 3766
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3767 3768 3769 3770 3771
  JSTypeHintLowering::LoweringResult early_reduction =
      type_hint_lowering().ReduceLoadNamedOperation(op, receiver, effect,
                                                    control, slot);
  ApplyEarlyReduction(early_reduction);
  return early_reduction;
3772 3773
}

3774 3775 3776 3777
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedLoadKeyed(const Operator* op,
                                                  Node* receiver, Node* key,
                                                  FeedbackSlot slot) {
3778 3779
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3780 3781 3782 3783 3784
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceLoadKeyedOperation(op, receiver, key, effect,
                                                    control, slot);
  ApplyEarlyReduction(result);
  return result;
3785 3786
}

3787 3788 3789 3790
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedStoreNamed(const Operator* op,
                                                   Node* receiver, Node* value,
                                                   FeedbackSlot slot) {
3791 3792
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3793 3794 3795 3796 3797
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceStoreNamedOperation(op, receiver, value,
                                                     effect, control, slot);
  ApplyEarlyReduction(result);
  return result;
3798 3799
}

3800 3801 3802 3803 3804
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedStoreKeyed(const Operator* op,
                                                   Node* receiver, Node* key,
                                                   Node* value,
                                                   FeedbackSlot slot) {
3805 3806
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3807 3808 3809 3810 3811
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceStoreKeyedOperation(op, receiver, key, value,
                                                     effect, control, slot);
  ApplyEarlyReduction(result);
  return result;
3812 3813
}

3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
void BytecodeGraphBuilder::ApplyEarlyReduction(
    JSTypeHintLowering::LoweringResult reduction) {
  if (reduction.IsExit()) {
    MergeControlToLeaveFunction(reduction.control());
  } else if (reduction.IsSideEffectFree()) {
    environment()->UpdateEffectDependency(reduction.effect());
    environment()->UpdateControlDependency(reduction.control());
  } else {
    DCHECK(!reduction.Changed());
    // At the moment, we assume side-effect free reduction. To support
    // side-effects, we would have to invalidate the eager checkpoint,
    // so that deoptimization does not repeat the side effect.
3826 3827 3828
  }
}

3829 3830 3831 3832 3833 3834 3835 3836 3837
Node** BytecodeGraphBuilder::EnsureInputBufferSize(int size) {
  if (size > input_buffer_size_) {
    size = size + kInputBufferSizeIncrement + input_buffer_size_;
    input_buffer_ = local_zone()->NewArray<Node*>(size);
    input_buffer_size_ = size;
  }
  return input_buffer_;
}

3838
void BytecodeGraphBuilder::ExitThenEnterExceptionHandlers(int current_offset) {
3839
  HandlerTable table(*bytecode_array());
3840 3841 3842 3843 3844 3845 3846 3847 3848

  // Potentially exit exception handlers.
  while (!exception_handlers_.empty()) {
    int current_end = exception_handlers_.top().end_offset_;
    if (current_offset < current_end) break;  // Still covered by range.
    exception_handlers_.pop();
  }

  // Potentially enter exception handlers.
3849
  int num_entries = table.NumberOfRangeEntries();
3850
  while (current_exception_handler_ < num_entries) {
3851
    int next_start = table.GetRangeStart(current_exception_handler_);
3852
    if (current_offset < next_start) break;  // Not yet covered by range.
3853 3854 3855
    int next_end = table.GetRangeEnd(current_exception_handler_);
    int next_handler = table.GetRangeHandler(current_exception_handler_);
    int context_register = table.GetRangeData(current_exception_handler_);
3856
    exception_handlers_.push(
3857
        {next_start, next_end, next_handler, context_register});
3858 3859 3860
    current_exception_handler_++;
  }
}
3861 3862

Node* BytecodeGraphBuilder::MakeNode(const Operator* op, int value_input_count,
3863 3864
                                     Node* const* value_inputs,
                                     bool incomplete) {
3865 3866 3867
  DCHECK_EQ(op->ValueInputCount(), value_input_count);

  bool has_context = OperatorProperties::HasContextInput(op);
3868
  bool has_frame_state = OperatorProperties::HasFrameStateInput(op);
3869 3870 3871 3872 3873 3874
  bool has_control = op->ControlInputCount() == 1;
  bool has_effect = op->EffectInputCount() == 1;

  DCHECK_LT(op->ControlInputCount(), 2);
  DCHECK_LT(op->EffectInputCount(), 2);

3875
  Node* result = nullptr;
3876
  if (!has_context && !has_frame_state && !has_control && !has_effect) {
3877 3878
    result = graph()->NewNode(op, value_input_count, value_inputs, incomplete);
  } else {
3879
    bool inside_handler = !exception_handlers_.empty();
3880 3881
    int input_count_with_deps = value_input_count;
    if (has_context) ++input_count_with_deps;
3882
    if (has_frame_state) ++input_count_with_deps;
3883 3884 3885
    if (has_control) ++input_count_with_deps;
    if (has_effect) ++input_count_with_deps;
    Node** buffer = EnsureInputBufferSize(input_count_with_deps);
3886 3887 3888
    if (value_input_count > 0) {
      memcpy(buffer, value_inputs, kSystemPointerSize * value_input_count);
    }
3889 3890
    Node** current_input = buffer + value_input_count;
    if (has_context) {
3891 3892 3893
      *current_input++ = OperatorProperties::NeedsExactContext(op)
                             ? environment()->Context()
                             : jsgraph()->HeapConstant(native_context());
3894
    }
3895
    if (has_frame_state) {
3896 3897 3898
      // The frame state will be inserted later. Here we misuse the {Dead} node
      // as a sentinel to be later overwritten with the real frame state by the
      // calls to {PrepareFrameState} within individual visitor methods.
3899
      *current_input++ = jsgraph()->Dead();
3900 3901 3902 3903 3904 3905 3906 3907
    }
    if (has_effect) {
      *current_input++ = environment()->GetEffectDependency();
    }
    if (has_control) {
      *current_input++ = environment()->GetControlDependency();
    }
    result = graph()->NewNode(op, input_count_with_deps, buffer, incomplete);
3908
    // Update the current control dependency for control-producing nodes.
3909
    if (result->op()->ControlOutputCount() > 0) {
3910 3911 3912 3913 3914 3915 3916 3917 3918
      environment()->UpdateControlDependency(result);
    }
    // Update the current effect dependency for effect-producing nodes.
    if (result->op()->EffectOutputCount() > 0) {
      environment()->UpdateEffectDependency(result);
    }
    // Add implicit exception continuation for throwing nodes.
    if (!result->op()->HasProperty(Operator::kNoThrow) && inside_handler) {
      int handler_offset = exception_handlers_.top().handler_offset_;
3919 3920
      int context_index = exception_handlers_.top().context_register_;
      interpreter::Register context_register(context_index);
3921
      Environment* success_env = environment()->Copy();
3922
      const Operator* op = common()->IfException();
3923 3924
      Node* effect = environment()->GetEffectDependency();
      Node* on_exception = graph()->NewNode(op, effect, result);
3925
      Node* context = environment()->LookupRegister(context_register);
3926 3927 3928
      environment()->UpdateControlDependency(on_exception);
      environment()->UpdateEffectDependency(on_exception);
      environment()->BindAccumulator(on_exception);
3929
      environment()->SetContext(context);
3930 3931 3932 3933
      MergeIntoSuccessorEnvironment(handler_offset);
      set_environment(success_env);
    }
    // Add implicit success continuation for throwing nodes.
3934
    if (!result->op()->HasProperty(Operator::kNoThrow) && inside_handler) {
3935 3936 3937
      const Operator* if_success = common()->IfSuccess();
      Node* on_success = graph()->NewNode(if_success, result);
      environment()->UpdateControlDependency(on_success);
3938
    }
3939 3940 3941 3942
    // Ensure checkpoints are created after operations with side-effects.
    if (has_effect && !result->op()->HasProperty(Operator::kNoWrite)) {
      mark_as_needing_eager_checkpoint(true);
    }
3943 3944 3945 3946 3947 3948
  }

  return result;
}


3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966
Node* BytecodeGraphBuilder::NewPhi(int count, Node* input, Node* control) {
  const Operator* phi_op = common()->Phi(MachineRepresentation::kTagged, count);
  Node** buffer = EnsureInputBufferSize(count + 1);
  MemsetPointer(buffer, input, count);
  buffer[count] = control;
  return graph()->NewNode(phi_op, count + 1, buffer, true);
}

Node* BytecodeGraphBuilder::NewEffectPhi(int count, Node* input,
                                         Node* control) {
  const Operator* phi_op = common()->EffectPhi(count);
  Node** buffer = EnsureInputBufferSize(count + 1);
  MemsetPointer(buffer, input, count);
  buffer[count] = control;
  return graph()->NewNode(phi_op, count + 1, buffer, true);
}


3967 3968 3969 3970 3971 3972
Node* BytecodeGraphBuilder::MergeControl(Node* control, Node* other) {
  int inputs = control->op()->ControlInputCount() + 1;
  if (control->opcode() == IrOpcode::kLoop) {
    // Control node for loop exists, add input.
    const Operator* op = common()->Loop(inputs);
    control->AppendInput(graph_zone(), other);
3973
    NodeProperties::ChangeOp(control, op);
3974 3975 3976 3977
  } else if (control->opcode() == IrOpcode::kMerge) {
    // Control node for merge exists, add input.
    const Operator* op = common()->Merge(inputs);
    control->AppendInput(graph_zone(), other);
3978
    NodeProperties::ChangeOp(control, op);
3979 3980 3981
  } else {
    // Control node is a singleton, introduce a merge.
    const Operator* op = common()->Merge(inputs);
3982 3983
    Node* merge_inputs[] = {control, other};
    control = graph()->NewNode(op, arraysize(merge_inputs), merge_inputs, true);
3984 3985 3986 3987
  }
  return control;
}

3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020
Node* BytecodeGraphBuilder::MergeEffect(Node* value, Node* other,
                                        Node* control) {
  int inputs = control->op()->ControlInputCount();
  if (value->opcode() == IrOpcode::kEffectPhi &&
      NodeProperties::GetControlInput(value) == control) {
    // Phi already exists, add input.
    value->InsertInput(graph_zone(), inputs - 1, other);
    NodeProperties::ChangeOp(value, common()->EffectPhi(inputs));
  } else if (value != other) {
    // Phi does not exist yet, introduce one.
    value = NewEffectPhi(inputs, value, control);
    value->ReplaceInput(inputs - 1, other);
  }
  return value;
}

Node* BytecodeGraphBuilder::MergeValue(Node* value, Node* other,
                                       Node* control) {
  int inputs = control->op()->ControlInputCount();
  if (value->opcode() == IrOpcode::kPhi &&
      NodeProperties::GetControlInput(value) == control) {
    // Phi already exists, add input.
    value->InsertInput(graph_zone(), inputs - 1, other);
    NodeProperties::ChangeOp(
        value, common()->Phi(MachineRepresentation::kTagged, inputs));
  } else if (value != other) {
    // Phi does not exist yet, introduce one.
    value = NewPhi(inputs, value, control);
    value->ReplaceInput(inputs - 1, other);
  }
  return value;
}

4021 4022 4023
void BytecodeGraphBuilder::UpdateSourcePosition(int offset) {
  if (source_position_iterator().done()) return;
  if (source_position_iterator().code_offset() == offset) {
4024
    source_positions_->SetCurrentPosition(SourcePosition(
4025 4026 4027
        source_position_iterator().source_position().ScriptOffset(),
        start_position_.InliningId()));
    source_position_iterator().Advance();
4028
  } else {
4029
    DCHECK_GT(source_position_iterator().code_offset(), offset);
4030 4031 4032
  }
}

4033 4034 4035 4036 4037
void BuildGraphFromBytecode(JSHeapBroker* broker, Zone* local_zone,
                            Handle<BytecodeArray> bytecode_array,
                            Handle<SharedFunctionInfo> shared,
                            Handle<FeedbackVector> feedback_vector,
                            BailoutId osr_offset, JSGraph* jsgraph,
4038
                            CallFrequency const& invocation_frequency,
4039 4040 4041 4042
                            SourcePositionTable* source_positions,
                            Handle<Context> native_context, int inlining_id,
                            BytecodeGraphBuilderFlags flags) {
  BytecodeGraphBuilder builder(broker, local_zone, bytecode_array, shared,
4043 4044 4045
                               feedback_vector, osr_offset, jsgraph,
                               invocation_frequency, source_positions,
                               native_context, inlining_id, flags);
4046 4047 4048
  builder.CreateGraph();
}

4049 4050 4051
}  // namespace compiler
}  // namespace internal
}  // namespace v8