js-inlining.cc 31.4 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#include "src/compiler/js-inlining.h"

7
#include "src/ast/ast.h"
8 9
#include "src/codegen/compiler.h"
#include "src/codegen/optimized-compilation-info.h"
10
#include "src/codegen/tick-counter.h"
11
#include "src/compiler/access-builder.h"
12
#include "src/compiler/all-nodes.h"
13
#include "src/compiler/bytecode-graph-builder.h"
14
#include "src/compiler/common-operator.h"
15
#include "src/compiler/compiler-source-position-table.h"
16
#include "src/compiler/graph-reducer.h"
17
#include "src/compiler/js-heap-broker.h"
18 19
#include "src/compiler/js-operator.h"
#include "src/compiler/node-matchers.h"
20
#include "src/compiler/node-properties.h"
21
#include "src/compiler/operator-properties.h"
22
#include "src/compiler/simplified-operator.h"
23
#include "src/execution/isolate-inl.h"
24
#include "src/objects/feedback-cell-inl.h"
25
#include "src/parsing/parse-info.h"
26

27 28 29 30
#if V8_ENABLE_WEBASSEMBLY
#include "src/compiler/wasm-compiler.h"
#endif  // V8_ENABLE_WEBASSEMBLY

31 32 33 34
namespace v8 {
namespace internal {
namespace compiler {

35 36 37 38 39 40
namespace {
// This is just to avoid some corner cases, especially since we allow recursive
// inlining.
static const int kMaxDepthForInlining = 50;
}  // namespace

41 42 43 44 45
#define TRACE(x)                     \
  do {                               \
    if (FLAG_trace_turbo_inlining) { \
      StdoutStream() << x << "\n";   \
    }                                \
46 47
  } while (false)

48
// Provides convenience accessors for the common layout of nodes having either
49
// the {JSCall} or the {JSConstruct} operator.
50
class JSCallAccessor {
51
 public:
52
  explicit JSCallAccessor(Node* call) : call_(call) {
53
    DCHECK(call->opcode() == IrOpcode::kJSCall ||
54
           call->opcode() == IrOpcode::kJSConstruct);
55
  }
56

57
  Node* target() const {
58
    return call_->InputAt(JSCallOrConstructNode::TargetIndex());
59
  }
60

61 62
  Node* receiver() const {
    return JSCallNode{call_}.receiver();
63 64
  }

65
  Node* new_target() const { return JSConstructNode{call_}.new_target(); }
66

67 68
  FrameState frame_state() const {
    return FrameState{NodeProperties::GetFrameStateInput(call_)};
69
  }
70

71
  int argument_count() const {
72 73
    return (call_->opcode() == IrOpcode::kJSCall)
               ? JSCallNode{call_}.ArgumentCount()
74
               : JSConstructNode{call_}.ArgumentCount();
75 76
  }

77
  CallFrequency const& frequency() const {
78
    return (call_->opcode() == IrOpcode::kJSCall)
79
               ? JSCallNode{call_}.Parameters().frequency()
80
               : JSConstructNode{call_}.Parameters().frequency();
81 82
  }

83
 private:
84
  Node* call_;
85 86
};

87
#if V8_ENABLE_WEBASSEMBLY
88 89 90 91 92 93 94 95 96 97 98
Reduction JSInliner::InlineJSWasmCall(Node* call, Node* new_target,
                                      Node* context, Node* frame_state,
                                      StartNode start, Node* end,
                                      Node* exception_target,
                                      const NodeVector& uncaught_subcalls) {
  JSWasmCallNode n(call);
  return InlineCall(
      call, new_target, context, frame_state, start, end, exception_target,
      uncaught_subcalls,
      static_cast<int>(n.Parameters().signature()->parameter_count()));
}
99
#endif  // V8_ENABLE_WEBASSEMBLY
100

101
Reduction JSInliner::InlineCall(Node* call, Node* new_target, Node* context,
102
                                Node* frame_state, StartNode start, Node* end,
103
                                Node* exception_target,
104 105 106 107
                                const NodeVector& uncaught_subcalls,
                                int argument_count) {
  DCHECK_IMPLIES(IrOpcode::IsInlineeOpcode(call->opcode()),
                 argument_count == JSCallAccessor(call).argument_count());
108

109
  // The scheduler is smart enough to place our code; we just ensure {control}
110 111
  // becomes the control input of the start of the inlinee, and {effect} becomes
  // the effect input of the start of the inlinee.
112
  Node* control = NodeProperties::GetControlInput(call);
113
  Node* effect = NodeProperties::GetEffectInput(call);
114

115 116 117
  int const inlinee_new_target_index = start.NewTargetOutputIndex();
  int const inlinee_arity_index = start.ArgCountOutputIndex();
  int const inlinee_context_index = start.ContextOutputIndex();
118

119 120
  // {inliner_inputs} counts the target, receiver/new_target, and arguments; but
  // not feedback vector, context, effect or control.
121
  const int inliner_inputs = argument_count +
122 123
                             JSCallOrConstructNode::kExtraInputCount -
                             JSCallOrConstructNode::kFeedbackVectorInputCount;
124
  // Iterate over all uses of the start node.
125
  for (Edge edge : start->use_edges()) {
danno's avatar
danno committed
126
    Node* use = edge.from();
127 128
    switch (use->opcode()) {
      case IrOpcode::kParameter: {
129
        int index = 1 + ParameterIndexOf(use->op());
130
        DCHECK_LE(index, inlinee_context_index);
131
        if (index < inliner_inputs && index < inlinee_new_target_index) {
132 133
          // There is an input from the call, and the index is a value
          // projection but not the context, so rewire the input.
134
          Replace(use, call->InputAt(index));
135 136 137
        } else if (index == inlinee_new_target_index) {
          // The projection is requesting the new target value.
          Replace(use, new_target);
138 139
        } else if (index == inlinee_arity_index) {
          // The projection is requesting the number of arguments.
140
          Replace(use, jsgraph()->Constant(argument_count));
141
        } else if (index == inlinee_context_index) {
142
          // The projection is requesting the inlinee function context.
143
          Replace(use, context);
144
        } else {
145
          // Call has fewer arguments than required, fill with undefined.
146
          Replace(use, jsgraph()->UndefinedConstant());
147 148 149 150
        }
        break;
      }
      default:
danno's avatar
danno committed
151
        if (NodeProperties::IsEffectEdge(edge)) {
152
          edge.UpdateTo(effect);
danno's avatar
danno committed
153 154
        } else if (NodeProperties::IsControlEdge(edge)) {
          edge.UpdateTo(control);
155 156
        } else if (NodeProperties::IsFrameStateEdge(edge)) {
          edge.UpdateTo(frame_state);
157 158 159 160 161 162 163
        } else {
          UNREACHABLE();
        }
        break;
    }
  }

164 165 166 167
  if (exception_target != nullptr) {
    // Link uncaught calls in the inlinee to {exception_target}
    int subcall_count = static_cast<int>(uncaught_subcalls.size());
    if (subcall_count > 0) {
168 169 170
      TRACE("Inlinee contains " << subcall_count
                                << " calls without local exception handler; "
                                << "linking to surrounding exception handler.");
171 172 173
    }
    NodeVector on_exception_nodes(local_zone_);
    for (Node* subcall : uncaught_subcalls) {
174 175 176
      Node* on_success = graph()->NewNode(common()->IfSuccess(), subcall);
      NodeProperties::ReplaceUses(subcall, subcall, subcall, on_success);
      NodeProperties::ReplaceControlInput(on_success, subcall);
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      Node* on_exception =
          graph()->NewNode(common()->IfException(), subcall, subcall);
      on_exception_nodes.push_back(on_exception);
    }

    DCHECK_EQ(subcall_count, static_cast<int>(on_exception_nodes.size()));
    if (subcall_count > 0) {
      Node* control_output =
          graph()->NewNode(common()->Merge(subcall_count), subcall_count,
                           &on_exception_nodes.front());
      NodeVector values_effects(local_zone_);
      values_effects = on_exception_nodes;
      values_effects.push_back(control_output);
      Node* value_output = graph()->NewNode(
          common()->Phi(MachineRepresentation::kTagged, subcall_count),
          subcall_count + 1, &values_effects.front());
      Node* effect_output =
          graph()->NewNode(common()->EffectPhi(subcall_count),
                           subcall_count + 1, &values_effects.front());
      ReplaceWithValue(exception_target, value_output, effect_output,
                       control_output);
    } else {
      ReplaceWithValue(exception_target, exception_target, exception_target,
200
                       jsgraph()->Dead());
201 202 203
    }
  }

204 205 206 207 208 209
  NodeVector values(local_zone_);
  NodeVector effects(local_zone_);
  NodeVector controls(local_zone_);
  for (Node* const input : end->inputs()) {
    switch (input->opcode()) {
      case IrOpcode::kReturn:
210
        values.push_back(NodeProperties::GetValueInput(input, 1));
211 212 213
        effects.push_back(NodeProperties::GetEffectInput(input));
        controls.push_back(NodeProperties::GetControlInput(input));
        break;
214 215 216
      case IrOpcode::kDeoptimize:
      case IrOpcode::kTerminate:
      case IrOpcode::kThrow:
217 218
        NodeProperties::MergeControlToEnd(graph(), common(), input);
        Revisit(graph()->end());
219
        break;
220 221
      default:
        UNREACHABLE();
222 223
    }
  }
224 225
  DCHECK_EQ(values.size(), effects.size());
  DCHECK_EQ(values.size(), controls.size());
226 227 228 229 230

  // Depending on whether the inlinee produces a value, we either replace value
  // uses with said value or kill value uses if no value can be returned.
  if (values.size() > 0) {
    int const input_count = static_cast<int>(controls.size());
231 232
    Node* control_output = graph()->NewNode(common()->Merge(input_count),
                                            input_count, &controls.front());
233 234
    values.push_back(control_output);
    effects.push_back(control_output);
235 236
    Node* value_output = graph()->NewNode(
        common()->Phi(MachineRepresentation::kTagged, input_count),
237
        static_cast<int>(values.size()), &values.front());
238 239 240
    Node* effect_output =
        graph()->NewNode(common()->EffectPhi(input_count),
                         static_cast<int>(effects.size()), &effects.front());
241 242 243
    ReplaceWithValue(call, value_output, effect_output, control_output);
    return Changed(value_output);
  } else {
244 245
    ReplaceWithValue(call, jsgraph()->Dead(), jsgraph()->Dead(),
                     jsgraph()->Dead());
246 247
    return Changed(call);
  }
248 249
}

250 251 252 253
FrameState JSInliner::CreateArtificialFrameState(
    Node* node, FrameState outer_frame_state, int parameter_count,
    BytecodeOffset bailout_id, FrameStateType frame_state_type,
    SharedFunctionInfoRef shared, Node* context) {
254
  const int parameter_count_with_receiver =
255
      parameter_count + JSCallOrConstructNode::kReceiverOrNewTargetInputCount;
256
  const FrameStateFunctionInfo* state_info =
257
      common()->CreateFrameStateFunctionInfo(
258
          frame_state_type, parameter_count_with_receiver, 0, shared.object());
259

260
  const Operator* op = common()->FrameState(
261
      bailout_id, OutputFrameStateCombine::Ignore(), state_info);
262
  const Operator* op0 = common()->StateValues(0, SparseInputMask::Dense());
263
  Node* node0 = graph()->NewNode(op0);
264

265
  NodeVector params(local_zone_);
266 267
  params.push_back(
      node->InputAt(JSCallOrConstructNode::ReceiverOrNewTargetIndex()));
268
  for (int i = 0; i < parameter_count; i++) {
269
    params.push_back(node->InputAt(JSCallOrConstructNode::ArgumentIndex(i)));
270
  }
271 272
  const Operator* op_param = common()->StateValues(
      static_cast<int>(params.size()), SparseInputMask::Dense());
273
  Node* params_node = graph()->NewNode(
274
      op_param, static_cast<int>(params.size()), &params.front());
275
  if (context == nullptr) context = jsgraph()->UndefinedConstant();
276 277 278
  return FrameState{graph()->NewNode(
      op, params_node, node0, node0, context,
      node->InputAt(JSCallOrConstructNode::TargetIndex()), outer_frame_state)};
279 280
}

281 282
namespace {

283
bool NeedsImplicitReceiver(SharedFunctionInfoRef shared_info) {
284
  DisallowGarbageCollection no_gc;
285 286
  return !shared_info.construct_as_builtin() &&
         !IsDerivedConstructor(shared_info.kind());
287 288
}

289 290
}  // namespace

291 292 293
// Determines whether the call target of the given call {node} is statically
// known and can be used as an inlining candidate. The {SharedFunctionInfo} of
// the call target is provided (the exact closure might be unknown).
294 295
base::Optional<SharedFunctionInfoRef> JSInliner::DetermineCallTarget(
    Node* node) {
296
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
297 298
  Node* target = node->InputAt(JSCallOrConstructNode::TargetIndex());
  HeapObjectMatcher match(target);
299

300 301
  // This reducer can handle both normal function calls as well a constructor
  // calls whenever the target is a constant function object, as follows:
302 303
  //  - JSCall(target:constant, receiver, args..., vector)
  //  - JSConstruct(target:constant, new.target, args..., vector)
304
  if (match.HasResolvedValue() && match.Ref(broker()).IsJSFunction()) {
305
    JSFunctionRef function = match.Ref(broker()).AsJSFunction();
306 307

    // The function might have not been called yet.
308
    if (!function.feedback_vector(broker()->dependencies()).has_value()) {
309 310
      return base::nullopt;
    }
311

312 313 314 315 316 317 318 319
    // Disallow cross native-context inlining for now. This means that all parts
    // of the resulting code will operate on the same global object. This also
    // prevents cross context leaks, where we could inline functions from a
    // different context and hold on to that context (and closure) from the code
    // object.
    // TODO(turbofan): We might want to revisit this restriction later when we
    // have a need for this, and we know how to model different native contexts
    // in the same graph in a compositional way.
320
    if (!function.native_context().equals(broker()->target_native_context())) {
321
      return base::nullopt;
322 323
    }

324
    return function.shared();
325 326 327 328
  }

  // This reducer can also handle calls where the target is statically known to
  // be the result of a closure instantiation operation, as follows:
329 330 331
  //  - JSCall(JSCreateClosure[shared](context), receiver, args..., vector)
  //  - JSConstruct(JSCreateClosure[shared](context),
  //                new.target, args..., vector)
332
  if (match.IsJSCreateClosure()) {
333 334
    JSCreateClosureNode n(target);
    FeedbackCellRef cell = n.GetFeedbackCellRefChecked(broker());
335 336
    return cell.shared_function_info();
  } else if (match.IsCheckClosure()) {
337
    FeedbackCellRef cell = MakeRef(broker(), FeedbackCellOf(match.op()));
338
    return cell.shared_function_info();
339 340
  }

341
  return base::nullopt;
342 343 344 345 346 347 348
}

// Determines statically known information about the call target (assuming that
// the call target is known according to {DetermineCallTarget} above). The
// following static information is provided:
//  - context         : The context (as SSA value) bound by the call target.
//  - feedback_vector : The target is guaranteed to use this feedback vector.
349 350
FeedbackCellRef JSInliner::DetermineCallContext(Node* node,
                                                Node** context_out) {
351
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
352 353
  Node* target = node->InputAt(JSCallOrConstructNode::TargetIndex());
  HeapObjectMatcher match(target);
354

355
  if (match.HasResolvedValue() && match.Ref(broker()).IsJSFunction()) {
356
    JSFunctionRef function = match.Ref(broker()).AsJSFunction();
357
    // This was already ensured by DetermineCallTarget
358
    CHECK(function.feedback_vector(broker()->dependencies()).has_value());
359 360

    // The inlinee specializes to the context from the JSFunction object.
361
    *context_out = jsgraph()->Constant(function.context());
362
    return function.raw_feedback_cell(broker()->dependencies());
363 364 365 366 367
  }

  if (match.IsJSCreateClosure()) {
    // Load the feedback vector of the target by looking up its vector cell at
    // the instantiation site (we only decide to inline if it's populated).
368 369
    JSCreateClosureNode n(target);
    FeedbackCellRef cell = n.GetFeedbackCellRefChecked(broker());
370 371

    // The inlinee uses the locally provided context at instantiation.
372
    *context_out = NodeProperties::GetContextInput(match.node());
373
    return cell;
374
  } else if (match.IsCheckClosure()) {
375
    FeedbackCellRef cell = MakeRef(broker(), FeedbackCellOf(match.op()));
376 377 378 379 380 381 382 383

    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
    *context_out = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForJSFunctionContext()),
        match.node(), effect, control);
    NodeProperties::ReplaceEffectInput(node, effect);

384
    return cell;
385 386 387 388
  }

  // Must succeed.
  UNREACHABLE();
389 390
}

391
#if V8_ENABLE_WEBASSEMBLY
392 393 394 395
Reduction JSInliner::ReduceJSWasmCall(Node* node) {
  // Create the subgraph for the inlinee.
  Node* start_node;
  Node* end;
396
  size_t subgraph_min_node_id;
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  {
    Graph::SubgraphScope scope(graph());

    graph()->SetEnd(nullptr);

    JSWasmCallNode n(node);
    const JSWasmCallParameters& wasm_call_params = n.Parameters();

    // Create a nested frame state inside the frame state attached to the
    // call; this will ensure that lazy deoptimizations at this point will
    // still return the result of the Wasm function call.
    Node* continuation_frame_state =
        CreateJSWasmCallBuiltinContinuationFrameState(
            jsgraph(), n.context(), n.frame_state(),
            wasm_call_params.signature());
    JSWasmCallData js_wasm_call_data(wasm_call_params.signature());
413 414 415 416 417 418 419

    // All the nodes inserted by the inlined subgraph will have
    // id >= subgraph_min_node_id. We use this later to avoid wire nodes that
    // are not inserted by the inlinee but were already part of the graph to the
    // surrounding exception handler, if present.
    subgraph_min_node_id = graph()->NodeCount();

420 421
    BuildInlinedJSToWasmWrapper(
        graph()->zone(), jsgraph(), wasm_call_params.signature(),
422
        wasm_call_params.module(), isolate(), source_positions_,
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        StubCallMode::kCallBuiltinPointer, wasm::WasmFeatures::FromFlags(),
        &js_wasm_call_data, continuation_frame_state);

    // Extract the inlinee start/end nodes.
    start_node = graph()->start();
    end = graph()->end();
  }
  StartNode start{start_node};

  Node* exception_target = nullptr;
  NodeProperties::IsExceptionalCall(node, &exception_target);

  // If we are inlining into a surrounding exception handler, we collect all
  // potentially throwing nodes within the inlinee that are not handled locally
  // by the inlinee itself. They are later wired into the surrounding handler.
  NodeVector uncaught_subcalls(local_zone_);
  if (exception_target != nullptr) {
    // Find all uncaught 'calls' in the inlinee.
    AllNodes inlined_nodes(local_zone_, end, graph());
    for (Node* subnode : inlined_nodes.reachable) {
443 444 445
      // Ignore nodes that are not part of the inlinee.
      if (subnode->id() < subgraph_min_node_id) continue;

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      // Every possibly throwing node should get {IfSuccess} and {IfException}
      // projections, unless there already is local exception handling.
      if (subnode->op()->HasProperty(Operator::kNoThrow)) continue;
      if (!NodeProperties::IsExceptionalCall(subnode)) {
        DCHECK_EQ(2, subnode->op()->ControlOutputCount());
        uncaught_subcalls.push_back(subnode);
      }
    }
  }

  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* new_target = jsgraph()->UndefinedConstant();

  return InlineJSWasmCall(node, new_target, context, frame_state, start, end,
                          exception_target, uncaught_subcalls);
}
463
#endif  // V8_ENABLE_WEBASSEMBLY
464

465
Reduction JSInliner::ReduceJSCall(Node* node) {
466
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
467
#if V8_ENABLE_WEBASSEMBLY
468
  DCHECK_NE(node->opcode(), IrOpcode::kJSWasmCall);
469
#endif  // V8_ENABLE_WEBASSEMBLY
470
  JSCallAccessor call(node);
471 472

  // Determine the call target.
473 474
  base::Optional<SharedFunctionInfoRef> shared_info(DetermineCallTarget(node));
  if (!shared_info.has_value()) return NoChange();
475

476 477
  SharedFunctionInfoRef outer_shared_info =
      MakeRef(broker(), info_->shared_info());
478

Georg Neis's avatar
Georg Neis committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492
  SharedFunctionInfo::Inlineability inlineability =
      shared_info->GetInlineability();
  if (inlineability != SharedFunctionInfo::kIsInlineable) {
    // The function is no longer inlineable. The only way this can happen is if
    // the function had its optimization disabled in the meantime, e.g. because
    // another optimization job failed too often.
    CHECK_EQ(inlineability, SharedFunctionInfo::kHasOptimizationDisabled);
    TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
                          << " because it had its optimization disabled.");
    return NoChange();
  }
  // NOTE: Even though we bailout in the kHasOptimizationDisabled case above, we
  // won't notice if the function's optimization is disabled after this point.

493
  // Constructor must be constructable.
494
  if (node->opcode() == IrOpcode::kJSConstruct &&
495
      !IsConstructable(shared_info->kind())) {
496
    TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
497
                          << " because constructor is not constructable.");
498
    return NoChange();
499 500
  }

501 502
  // Class constructors are callable, but [[Call]] will raise an exception.
  // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList ).
503
  if (node->opcode() == IrOpcode::kJSCall &&
504
      IsClassConstructor(shared_info->kind())) {
505
    TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
506
                          << " because callee is a class constructor.");
507 508 509
    return NoChange();
  }

510 511 512
  // To ensure inlining always terminates, we have an upper limit on inlining
  // the nested calls.
  int nesting_level = 0;
513
  for (Node* frame_state = call.frame_state();
514
       frame_state->opcode() == IrOpcode::kFrameState;
515
       frame_state = FrameState{frame_state}.outer_frame_state()) {
516 517
    nesting_level++;
    if (nesting_level > kMaxDepthForInlining) {
518
      TRACE("Not inlining "
519
            << *shared_info << " into " << outer_shared_info
520 521
            << " because call has exceeded the maximum depth for function "
               "inlining.");
522 523 524 525
      return NoChange();
    }
  }

526
  Node* exception_target = nullptr;
527
  NodeProperties::IsExceptionalCall(node, &exception_target);
528

529
  // JSInliningHeuristic has already filtered candidates without a BytecodeArray
530 531 532 533
  // based on SharedFunctionInfoRef::GetInlineability. For the inlineable ones
  // (kIsInlineable), the broker holds a reference to the bytecode array, which
  // prevents it from getting flushed.  Therefore, the following check should
  // always hold true.
534
  CHECK(shared_info->is_compiled());
535

536 537 538 539 540 541 542 543 544 545 546 547
  if (info_->source_positions() &&
      !shared_info->object()->AreSourcePositionsAvailable(
          broker()->local_isolate_or_isolate())) {
    // This case is expected to be very rare, since we generate source
    // positions for all functions when debugging or profiling are turned
    // on (see Isolate::NeedsDetailedOptimizedCodeLineInfo). Source
    // positions should only be missing here if there is a race between 1)
    // enabling/disabling the debugger/profiler, and 2) this compile job.
    // In that case, we simply don't inline.
    TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
                          << " because source positions are missing.");
    return NoChange();
548 549
  }

550
  // Determine the target's feedback vector and its context.
551
  Node* context;
552
  FeedbackCellRef feedback_cell = DetermineCallContext(node, &context);
553

554 555 556
  TRACE("Inlining " << *shared_info << " into " << outer_shared_info
                    << ((exception_target != nullptr) ? " (inside try-block)"
                                                      : ""));
557 558 559 560
  // ----------------------------------------------------------------
  // After this point, we've made a decision to inline this function.
  // We shall not bailout from inlining if we got here.

561
  BytecodeArrayRef bytecode_array = shared_info->GetBytecodeArray();
562

563
  // Remember that we inlined this function.
564 565 566
  int inlining_id =
      info_->AddInlinedFunction(shared_info->object(), bytecode_array.object(),
                                source_positions_->GetSourcePosition(node));
567

568
  // Create the subgraph for the inlinee.
569
  Node* start_node;
570
  Node* end;
571
  {
572 573
    // Run the BytecodeGraphBuilder to create the subgraph.
    Graph::SubgraphScope scope(graph());
574
    BytecodeGraphBuilderFlags flags(
575
        BytecodeGraphBuilderFlag::kSkipFirstStackAndTierupCheck);
576
    if (info_->analyze_environment_liveness()) {
577 578
      flags |= BytecodeGraphBuilderFlag::kAnalyzeEnvironmentLiveness;
    }
579
    if (info_->bailout_on_uninitialized()) {
580
      flags |= BytecodeGraphBuilderFlag::kBailoutOnUninitialized;
581
    }
582
    {
583
      CallFrequency frequency = call.frequency();
584
      BuildGraphFromBytecode(broker(), zone(), *shared_info, feedback_cell,
585
                             BytecodeOffset::None(), jsgraph(), frequency,
586 587
                             source_positions_, inlining_id, info_->code_kind(),
                             flags, &info_->tick_counter());
588
    }
589

590
    // Extract the inlinee start/end nodes.
591
    start_node = graph()->start();
592 593
    end = graph()->end();
  }
594
  StartNode start{start_node};
595

596 597 598
  // If we are inlining into a surrounding exception handler, we collect all
  // potentially throwing nodes within the inlinee that are not handled locally
  // by the inlinee itself. They are later wired into the surrounding handler.
599
  NodeVector uncaught_subcalls(local_zone_);
600 601 602 603
  if (exception_target != nullptr) {
    // Find all uncaught 'calls' in the inlinee.
    AllNodes inlined_nodes(local_zone_, end, graph());
    for (Node* subnode : inlined_nodes.reachable) {
604 605 606 607
      // Every possibly throwing node should get {IfSuccess} and {IfException}
      // projections, unless there already is local exception handling.
      if (subnode->op()->HasProperty(Operator::kNoThrow)) continue;
      if (!NodeProperties::IsExceptionalCall(subnode)) {
608 609 610 611 612 613
        DCHECK_EQ(2, subnode->op()->ControlOutputCount());
        uncaught_subcalls.push_back(subnode);
      }
    }
  }

614
  FrameState frame_state = call.frame_state();
615
  Node* new_target = jsgraph()->UndefinedConstant();
616

617 618
  // Inline {JSConstruct} requires some additional magic.
  if (node->opcode() == IrOpcode::kJSConstruct) {
619
    STATIC_ASSERT(JSCallOrConstructNode::kHaveIdenticalLayouts);
620
    JSConstructNode n(node);
621 622

    new_target = n.new_target();
623

624 625 626 627
    // Insert nodes around the call that model the behavior required for a
    // constructor dispatch (allocate implicit receiver and check return value).
    // This models the behavior usually accomplished by our {JSConstructStub}.
    // Note that the context has to be the callers context (input to call node).
628 629 630 631
    // Also note that by splitting off the {JSCreate} piece of the constructor
    // call, we create an observable deoptimization point after the receiver
    // instantiation but before the invocation (i.e. inside {JSConstructStub}
    // where execution continues at {construct_stub_create_deopt_pc_offset}).
632
    Node* receiver = jsgraph()->TheHoleConstant();  // Implicit receiver.
633
    Node* caller_context = NodeProperties::GetContextInput(node);
634
    if (NeedsImplicitReceiver(*shared_info)) {
635 636
      Effect effect = n.effect();
      Control control = n.control();
637
      Node* frame_state_inside = CreateArtificialFrameState(
638
          node, frame_state, n.ArgumentCount(),
639
          BytecodeOffset::ConstructStubCreate(), FrameStateType::kConstructStub,
640
          *shared_info, caller_context);
641 642
      Node* create =
          graph()->NewNode(javascript()->Create(), call.target(), new_target,
643
                           caller_context, frame_state_inside, effect, control);
644 645
      uncaught_subcalls.push_back(create);  // Adds {IfSuccess} & {IfException}.
      NodeProperties::ReplaceControlInput(node, create);
646
      NodeProperties::ReplaceEffectInput(node, create);
647 648 649 650 651
      // Placeholder to hold {node}'s value dependencies while {node} is
      // replaced.
      Node* dummy = graph()->NewNode(common()->Dead());
      NodeProperties::ReplaceUses(node, dummy, node, node, node);
      Node* result;
652 653 654 655 656 657 658
      // Insert a check of the return value to determine whether the return
      // value or the implicit receiver should be selected as a result of the
      // call.
      Node* check = graph()->NewNode(simplified()->ObjectIsReceiver(), node);
      result =
          graph()->NewNode(common()->Select(MachineRepresentation::kTagged),
                           check, node, create);
659
      receiver = create;  // The implicit receiver.
660
      ReplaceWithValue(dummy, result);
661 662 663 664 665 666 667 668 669 670 671
    } else if (IsDerivedConstructor(shared_info->kind())) {
      Node* node_success =
          NodeProperties::FindSuccessfulControlProjection(node);
      Node* is_receiver =
          graph()->NewNode(simplified()->ObjectIsReceiver(), node);
      Node* branch_is_receiver =
          graph()->NewNode(common()->Branch(), is_receiver, node_success);
      Node* branch_is_receiver_true =
          graph()->NewNode(common()->IfTrue(), branch_is_receiver);
      Node* branch_is_receiver_false =
          graph()->NewNode(common()->IfFalse(), branch_is_receiver);
672 673 674 675 676
      branch_is_receiver_false = graph()->NewNode(
          javascript()->CallRuntime(
              Runtime::kThrowConstructorReturnedNonObject),
          caller_context, NodeProperties::GetFrameStateInput(node), node,
          branch_is_receiver_false);
677 678 679 680 681 682 683
      uncaught_subcalls.push_back(branch_is_receiver_false);
      branch_is_receiver_false =
          graph()->NewNode(common()->Throw(), branch_is_receiver_false,
                           branch_is_receiver_false);
      NodeProperties::MergeControlToEnd(graph(), common(),
                                        branch_is_receiver_false);

684 685 686
      ReplaceWithValue(node_success, node_success, node_success,
                       branch_is_receiver_true);
      // Fix input destroyed by the above {ReplaceWithValue} call.
687
      NodeProperties::ReplaceControlInput(branch_is_receiver, node_success, 0);
688
    }
689
    node->ReplaceInput(JSCallNode::ReceiverIndex(), receiver);
690 691
    // Insert a construct stub frame into the chain of frame states. This will
    // reconstruct the proper frame when deoptimizing within the constructor.
692
    frame_state = CreateArtificialFrameState(
693 694
        node, frame_state, n.ArgumentCount(),
        BytecodeOffset::ConstructStubInvoke(), FrameStateType::kConstructStub,
695
        *shared_info, caller_context);
696 697
  }

698
  // Insert a JSConvertReceiver node for sloppy callees. Note that the context
699
  // passed into this node has to be the callees context (loaded above).
700
  if (node->opcode() == IrOpcode::kJSCall &&
701
      is_sloppy(shared_info->language_mode()) && !shared_info->native()) {
702
    Effect effect{NodeProperties::GetEffectInput(node)};
703
    if (NodeProperties::CanBePrimitive(broker(), call.receiver(), effect)) {
704
      CallParameters const& p = CallParametersOf(node->op());
705 706
      Node* global_proxy = jsgraph()->Constant(
          broker()->target_native_context().global_proxy_object());
707 708 709
      Node* receiver = effect =
          graph()->NewNode(simplified()->ConvertReceiver(p.convert_mode()),
                           call.receiver(), global_proxy, effect, start);
710 711
      NodeProperties::ReplaceValueInput(node, receiver,
                                        JSCallNode::ReceiverIndex());
712 713
      NodeProperties::ReplaceEffectInput(node, effect);
    }
714 715
  }

716
  // Insert argument adaptor frame if required. The callees formal parameter
717
  // count have to match the number of arguments passed
718
  // to the call.
719 720
  int parameter_count =
      shared_info->internal_formal_parameter_count_without_receiver();
721
  DCHECK_EQ(parameter_count, start.FormalParameterCountWithoutReceiver());
722
  if (call.argument_count() != parameter_count) {
723
    frame_state = CreateArtificialFrameState(
724
        node, frame_state, call.argument_count(), BytecodeOffset::None(),
725
        FrameStateType::kArgumentsAdaptor, *shared_info);
726 727
  }

728
  return InlineCall(node, new_target, context, frame_state, start, end,
729
                    exception_target, uncaught_subcalls, call.argument_count());
730
}
731

732 733
Graph* JSInliner::graph() const { return jsgraph()->graph(); }

734 735 736 737 738 739
JSOperatorBuilder* JSInliner::javascript() const {
  return jsgraph()->javascript();
}

CommonOperatorBuilder* JSInliner::common() const { return jsgraph()->common(); }

740 741 742 743
SimplifiedOperatorBuilder* JSInliner::simplified() const {
  return jsgraph()->simplified();
}

744 745
#undef TRACE

746 747 748
}  // namespace compiler
}  // namespace internal
}  // namespace v8