js-inlining.cc 27.6 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
#include "src/compiler.h"
9
#include "src/compiler/all-nodes.h"
10
#include "src/compiler/bytecode-graph-builder.h"
11
#include "src/compiler/common-operator.h"
12
#include "src/compiler/compiler-source-position-table.h"
13
#include "src/compiler/graph-reducer.h"
14 15
#include "src/compiler/js-operator.h"
#include "src/compiler/node-matchers.h"
16
#include "src/compiler/node-properties.h"
17
#include "src/compiler/operator-properties.h"
18
#include "src/compiler/simplified-operator.h"
19
#include "src/isolate-inl.h"
20
#include "src/objects/feedback-cell-inl.h"
21
#include "src/optimized-compilation-info.h"
22
#include "src/parsing/parse-info.h"
23 24 25 26 27

namespace v8 {
namespace internal {
namespace compiler {

28 29 30 31 32 33
namespace {
// This is just to avoid some corner cases, especially since we allow recursive
// inlining.
static const int kMaxDepthForInlining = 50;
}  // namespace

34 35 36 37 38
#define TRACE(x)                     \
  do {                               \
    if (FLAG_trace_turbo_inlining) { \
      StdoutStream() << x << "\n";   \
    }                                \
39 40
  } while (false)

41
// Provides convenience accessors for the common layout of nodes having either
42
// the {JSCall} or the {JSConstruct} operator.
43
class JSCallAccessor {
44
 public:
45
  explicit JSCallAccessor(Node* call) : call_(call) {
46
    DCHECK(call->opcode() == IrOpcode::kJSCall ||
47
           call->opcode() == IrOpcode::kJSConstruct);
48
  }
49

50
  Node* target() {
51
    // Both, {JSCall} and {JSConstruct}, have same layout here.
52 53
    return call_->InputAt(0);
  }
54

55
  Node* receiver() {
56
    DCHECK_EQ(IrOpcode::kJSCall, call_->opcode());
57
    return call_->InputAt(1);
58 59
  }

60
  Node* new_target() {
61
    DCHECK_EQ(IrOpcode::kJSConstruct, call_->opcode());
62
    return call_->InputAt(formal_arguments() + 1);
63 64
  }

65
  Node* frame_state() {
66
    // Both, {JSCall} and {JSConstruct}, have frame state.
67
    return NodeProperties::GetFrameStateInput(call_);
68
  }
69

70
  int formal_arguments() {
71
    // Both, {JSCall} and {JSConstruct}, have two extra inputs:
72
    //  - JSConstruct: Includes target function and new target.
73
    //  - JSCall: Includes target function and receiver.
74 75 76
    return call_->op()->ValueInputCount() - 2;
  }

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

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

87
Reduction JSInliner::InlineCall(Node* call, Node* new_target, Node* context,
88 89 90
                                Node* frame_state, Node* start, Node* end,
                                Node* exception_target,
                                const NodeVector& uncaught_subcalls) {
91
  // The scheduler is smart enough to place our code; we just ensure {control}
92 93
  // becomes the control input of the start of the inlinee, and {effect} becomes
  // the effect input of the start of the inlinee.
94
  Node* control = NodeProperties::GetControlInput(call);
95
  Node* effect = NodeProperties::GetEffectInput(call);
96

97 98
  int const inlinee_new_target_index =
      static_cast<int>(start->op()->ValueOutputCount()) - 3;
99 100
  int const inlinee_arity_index =
      static_cast<int>(start->op()->ValueOutputCount()) - 2;
101 102 103
  int const inlinee_context_index =
      static_cast<int>(start->op()->ValueOutputCount()) - 1;

104 105
  // {inliner_inputs} counts JSFunction, receiver, arguments, but not
  // new target value, argument count, context, effect or control.
106
  int inliner_inputs = call->op()->ValueInputCount();
107
  // Iterate over all uses of the start node.
108
  for (Edge edge : start->use_edges()) {
danno's avatar
danno committed
109
    Node* use = edge.from();
110 111
    switch (use->opcode()) {
      case IrOpcode::kParameter: {
112
        int index = 1 + ParameterIndexOf(use->op());
113
        DCHECK_LE(index, inlinee_context_index);
114
        if (index < inliner_inputs && index < inlinee_new_target_index) {
115 116
          // There is an input from the call, and the index is a value
          // projection but not the context, so rewire the input.
117
          Replace(use, call->InputAt(index));
118 119 120
        } else if (index == inlinee_new_target_index) {
          // The projection is requesting the new target value.
          Replace(use, new_target);
121 122
        } else if (index == inlinee_arity_index) {
          // The projection is requesting the number of arguments.
123
          Replace(use, jsgraph()->Constant(inliner_inputs - 2));
124
        } else if (index == inlinee_context_index) {
125
          // The projection is requesting the inlinee function context.
126
          Replace(use, context);
127
        } else {
128
          // Call has fewer arguments than required, fill with undefined.
129
          Replace(use, jsgraph()->UndefinedConstant());
130 131 132 133
        }
        break;
      }
      default:
danno's avatar
danno committed
134
        if (NodeProperties::IsEffectEdge(edge)) {
135
          edge.UpdateTo(effect);
danno's avatar
danno committed
136 137
        } else if (NodeProperties::IsControlEdge(edge)) {
          edge.UpdateTo(control);
138 139
        } else if (NodeProperties::IsFrameStateEdge(edge)) {
          edge.UpdateTo(frame_state);
140 141 142 143 144 145 146
        } else {
          UNREACHABLE();
        }
        break;
    }
  }

147 148 149 150
  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) {
151 152 153
      TRACE("Inlinee contains " << subcall_count
                                << " calls without local exception handler; "
                                << "linking to surrounding exception handler.");
154 155 156
    }
    NodeVector on_exception_nodes(local_zone_);
    for (Node* subcall : uncaught_subcalls) {
157 158 159
      Node* on_success = graph()->NewNode(common()->IfSuccess(), subcall);
      NodeProperties::ReplaceUses(subcall, subcall, subcall, on_success);
      NodeProperties::ReplaceControlInput(on_success, subcall);
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
      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,
183
                       jsgraph()->Dead());
184 185 186
    }
  }

187 188 189 190 191 192
  NodeVector values(local_zone_);
  NodeVector effects(local_zone_);
  NodeVector controls(local_zone_);
  for (Node* const input : end->inputs()) {
    switch (input->opcode()) {
      case IrOpcode::kReturn:
193
        values.push_back(NodeProperties::GetValueInput(input, 1));
194 195 196
        effects.push_back(NodeProperties::GetEffectInput(input));
        controls.push_back(NodeProperties::GetControlInput(input));
        break;
197 198 199
      case IrOpcode::kDeoptimize:
      case IrOpcode::kTerminate:
      case IrOpcode::kThrow:
200 201
        NodeProperties::MergeControlToEnd(graph(), common(), input);
        Revisit(graph()->end());
202
        break;
203 204 205
      default:
        UNREACHABLE();
        break;
206 207
    }
  }
208 209
  DCHECK_EQ(values.size(), effects.size());
  DCHECK_EQ(values.size(), controls.size());
210 211 212 213 214

  // 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());
215 216
    Node* control_output = graph()->NewNode(common()->Merge(input_count),
                                            input_count, &controls.front());
217 218
    values.push_back(control_output);
    effects.push_back(control_output);
219 220
    Node* value_output = graph()->NewNode(
        common()->Phi(MachineRepresentation::kTagged, input_count),
221
        static_cast<int>(values.size()), &values.front());
222 223 224
    Node* effect_output =
        graph()->NewNode(common()->EffectPhi(input_count),
                         static_cast<int>(effects.size()), &effects.front());
225 226 227
    ReplaceWithValue(call, value_output, effect_output, control_output);
    return Changed(value_output);
  } else {
228 229
    ReplaceWithValue(call, jsgraph()->Dead(), jsgraph()->Dead(),
                     jsgraph()->Dead());
230 231
    return Changed(call);
  }
232 233
}

234 235
Node* JSInliner::CreateArtificialFrameState(Node* node, Node* outer_frame_state,
                                            int parameter_count,
236
                                            BailoutId bailout_id,
237
                                            FrameStateType frame_state_type,
238
                                            SharedFunctionInfoRef shared,
239
                                            Node* context) {
240
  const FrameStateFunctionInfo* state_info =
241 242
      common()->CreateFrameStateFunctionInfo(
          frame_state_type, parameter_count + 1, 0, shared.object());
243

244
  const Operator* op = common()->FrameState(
245
      bailout_id, OutputFrameStateCombine::Ignore(), state_info);
246
  const Operator* op0 = common()->StateValues(0, SparseInputMask::Dense());
247
  Node* node0 = graph()->NewNode(op0);
248
  NodeVector params(local_zone_);
249 250
  for (int parameter = 0; parameter < parameter_count + 1; ++parameter) {
    params.push_back(node->InputAt(1 + parameter));
251
  }
252 253
  const Operator* op_param = common()->StateValues(
      static_cast<int>(params.size()), SparseInputMask::Dense());
254
  Node* params_node = graph()->NewNode(
255
      op_param, static_cast<int>(params.size()), &params.front());
256 257 258 259 260
  if (!context) {
    context = jsgraph()->UndefinedConstant();
  }
  return graph()->NewNode(op, params_node, node0, node0, context,
                          node->InputAt(0), outer_frame_state);
261 262
}

263 264 265
namespace {

// TODO(mstarzinger,verwaest): Move this predicate onto SharedFunctionInfo?
266
bool NeedsImplicitReceiver(SharedFunctionInfoRef shared_info) {
267
  DisallowHeapAllocation no_gc;
268 269
  return !shared_info.construct_as_builtin() &&
         !IsDerivedConstructor(shared_info.kind());
270 271
}

272 273
}  // namespace

274 275 276
// 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).
277 278
base::Optional<SharedFunctionInfoRef> JSInliner::DetermineCallTarget(
    Node* node) {
279 280
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
  HeapObjectMatcher match(node->InputAt(0));
281

282 283
  // This reducer can handle both normal function calls as well a constructor
  // calls whenever the target is a constant function object, as follows:
284
  //  - JSCall(target:constant, receiver, args...)
285
  //  - JSConstruct(target:constant, args..., new.target)
286 287
  if (match.HasValue() && match.Ref(broker()).IsJSFunction()) {
    JSFunctionRef function = match.Ref(broker()).AsJSFunction();
288 289 290 291 292

    // The function might have not been called yet.
    if (!function.has_feedback_vector()) {
      return base::nullopt;
    }
293

294 295 296 297 298 299 300 301
    // 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.
302 303
    if (!function.native_context().equals(broker()->native_context())) {
      return base::nullopt;
304 305
    }

306
    return function.shared();
307 308 309 310 311 312 313 314 315 316 317
  }

  // This reducer can also handle calls where the target is statically known to
  // be the result of a closure instantiation operation, as follows:
  //  - JSCall(JSCreateClosure[shared](context), receiver, args...)
  //  - JSConstruct(JSCreateClosure[shared](context), args..., new.target)
  if (match.IsJSCreateClosure()) {
    CreateClosureParameters const& p = CreateClosureParametersOf(match.op());

    // TODO(turbofan): We might consider to eagerly create the feedback vector
    // in such a case (in {DetermineCallContext} below) eventually.
318 319
    FeedbackCellRef cell(FeedbackCellRef(broker(), p.feedback_cell()));
    if (!cell.value().IsFeedbackVector()) return base::nullopt;
320

321
    return SharedFunctionInfoRef(broker(), p.shared_info());
322 323
  }

324
  return base::nullopt;
325 326 327 328 329 330 331
}

// 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.
332 333
FeedbackVectorRef JSInliner::DetermineCallContext(Node* node,
                                                  Node*& context_out) {
334
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
335
  HeapObjectMatcher match(node->InputAt(0));
336

337 338
  if (match.HasValue() && match.Ref(broker()).IsJSFunction()) {
    JSFunctionRef function = match.Ref(broker()).AsJSFunction();
339
    // This was already ensured by DetermineCallTarget
340
    CHECK(function.has_feedback_vector());
341 342

    // The inlinee specializes to the context from the JSFunction object.
343 344
    context_out = jsgraph()->Constant(function.context());
    return function.feedback_vector();
345 346 347 348 349 350 351
  }

  if (match.IsJSCreateClosure()) {
    CreateClosureParameters const& p = CreateClosureParametersOf(match.op());

    // 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).
352
    FeedbackCellRef cell(FeedbackCellRef(broker(), p.feedback_cell()));
353 354 355

    // The inlinee uses the locally provided context at instantiation.
    context_out = NodeProperties::GetContextInput(match.node());
356
    return cell.value().AsFeedbackVector();
357 358 359 360
  }

  // Must succeed.
  UNREACHABLE();
361 362
}

363
Reduction JSInliner::ReduceJSCall(Node* node) {
364 365
  DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
  JSCallAccessor call(node);
366 367

  // Determine the call target.
368 369
  base::Optional<SharedFunctionInfoRef> shared_info(DetermineCallTarget(node));
  if (!shared_info.has_value()) return NoChange();
370

371
  DCHECK(shared_info.value().IsInlineable());
372

373
  // Constructor must be constructable.
374
  if (node->opcode() == IrOpcode::kJSConstruct &&
375
      !IsConstructable(shared_info->kind())) {
376 377 378 379
    TRACE(
        "Not inlining " << shared_info->object().address() << " into "
                        << info_->shared_info()->DebugName()->ToCString().get()
                        << " because constructor is not constructable.");
380
    return NoChange();
381 382
  }

383 384
  // Class constructors are callable, but [[Call]] will raise an exception.
  // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList ).
385
  if (node->opcode() == IrOpcode::kJSCall &&
386
      IsClassConstructor(shared_info->kind())) {
387 388 389 390
    TRACE(
        "Not inlining " << shared_info->object().address() << " into "
                        << info_->shared_info()->DebugName()->ToCString().get()
                        << " because callee is a class constructor.");
391 392 393
    return NoChange();
  }

394 395 396
  // To ensure inlining always terminates, we have an upper limit on inlining
  // the nested calls.
  int nesting_level = 0;
397
  for (Node* frame_state = call.frame_state();
398 399
       frame_state->opcode() == IrOpcode::kFrameState;
       frame_state = frame_state->InputAt(kFrameStateOuterStateInput)) {
400 401
    nesting_level++;
    if (nesting_level > kMaxDepthForInlining) {
402 403 404 405 406
      TRACE("Not inlining "
            << shared_info->object().address() << " into "
            << info_->shared_info()->DebugName()->ToCString().get()
            << " because call has exceeded the maximum depth for function "
               "inlining.");
407 408 409 410
      return NoChange();
    }
  }

411 412 413
  // Calls surrounded by a local try-block are only inlined if the
  // appropriate flag is active. We also discover the {IfException}
  // projection this way.
414
  Node* exception_target = nullptr;
415 416
  if (NodeProperties::IsExceptionalCall(node, &exception_target) &&
      !FLAG_inline_into_try) {
417 418 419 420 421
    TRACE("Try block surrounds #"
          << exception_target->id() << ":" << exception_target->op()->mnemonic()
          << " and --no-inline-into-try active, so not inlining "
          << shared_info->object().address() << " into "
          << info_->shared_info()->DebugName()->ToCString().get());
422
    return NoChange();
423 424
  }

425 426 427 428 429 430
  // JSInliningHeuristic has already filtered candidates without a
  // BytecodeArray by calling SharedFunctionInfoRef::IsInlineable. For the ones
  // passing the IsInlineable check, The broker holds a reference to the
  // bytecode array, which prevents it from getting flushed.
  // Therefore, the following check should always hold true.
  CHECK(shared_info.value().is_compiled());
431

432
  if (!FLAG_concurrent_inlining && info_->is_source_positions_enabled()) {
433 434
    SharedFunctionInfo::EnsureSourcePositionsAvailable(isolate(),
                                                       shared_info->object());
435 436
  }

437 438 439 440
  TRACE("Inlining " << shared_info->object().address() << " into "
                    << info_->shared_info()->DebugName()->ToCString().get()
                    << ((exception_target != nullptr) ? " (inside try-block)"
                                                      : ""));
441 442
  // Determine the targets feedback vector and its context.
  Node* context;
443
  FeedbackVectorRef feedback_vector = DetermineCallContext(node, context);
444

445
  if (FLAG_concurrent_inlining) {
446 447 448 449
    if (!shared_info.value().IsSerializedForCompilation(feedback_vector)) {
      TRACE("Missed opportunity to inline a function ("
            << Brief(*shared_info.value().object()) << " with "
            << Brief(*feedback_vector.object()) << ")");
450
      return NoChange();
451 452 453
    }
  }

454 455 456 457
  // ----------------------------------------------------------------
  // After this point, we've made a decision to inline this function.
  // We shall not bailout from inlining if we got here.

458
  BytecodeArrayRef bytecode_array = shared_info.value().GetBytecodeArray();
459

460 461
  // Remember that we inlined this function.
  int inlining_id = info_->AddInlinedFunction(
462 463
      shared_info.value().object(), bytecode_array.object(),
      source_positions_->GetSourcePosition(node));
464

465 466 467
  // Create the subgraph for the inlinee.
  Node* start;
  Node* end;
468
  {
469 470
    // Run the BytecodeGraphBuilder to create the subgraph.
    Graph::SubgraphScope scope(graph());
471 472 473 474 475
    BytecodeGraphBuilderFlags flags(
        BytecodeGraphBuilderFlag::kSkipFirstStackCheck);
    if (info_->is_analyze_environment_liveness()) {
      flags |= BytecodeGraphBuilderFlag::kAnalyzeEnvironmentLiveness;
    }
476
    if (info_->is_bailout_on_uninitialized()) {
477
      flags |= BytecodeGraphBuilderFlag::kBailoutOnUninitialized;
478
    }
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    {
      // TODO(mslekova): Remove the following once bytecode graph builder
      // is brokerized. Also, remove the context argument from
      // BuildGraphFromBytecode and extract it from the broker there.
      AllowHandleDereference allow_handle_deref;
      AllowHandleAllocation allow_handle_alloc;
      AllowHeapAllocation allow_heap_alloc;
      AllowCodeDependencyChange allow_code_dep_change;
      Handle<Context> native_context =
          handle(info_->native_context(), isolate());

      BuildGraphFromBytecode(broker(), zone(), bytecode_array.object(),
                             shared_info.value().object(),
                             feedback_vector.object(), BailoutId::None(),
                             jsgraph(), call.frequency(), source_positions_,
                             native_context, inlining_id, flags);
    }
496

497 498 499 500 501
    // Extract the inlinee start/end nodes.
    start = graph()->start();
    end = graph()->end();
  }

502 503 504
  // 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.
505
  NodeVector uncaught_subcalls(local_zone_);
506 507 508 509
  if (exception_target != nullptr) {
    // Find all uncaught 'calls' in the inlinee.
    AllNodes inlined_nodes(local_zone_, end, graph());
    for (Node* subnode : inlined_nodes.reachable) {
510 511 512 513
      // 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)) {
514 515 516 517 518 519
        DCHECK_EQ(2, subnode->op()->ControlOutputCount());
        uncaught_subcalls.push_back(subnode);
      }
    }
  }

520
  Node* frame_state = call.frame_state();
521
  Node* new_target = jsgraph()->UndefinedConstant();
522

523 524
  // Inline {JSConstruct} requires some additional magic.
  if (node->opcode() == IrOpcode::kJSConstruct) {
525 526 527 528 529 530 531
    // Swizzle the inputs of the {JSConstruct} node to look like inputs to a
    // normal {JSCall} node so that the rest of the inlining machinery
    // behaves as if we were dealing with a regular function invocation.
    new_target = call.new_target();  // Retrieve new target value input.
    node->RemoveInput(call.formal_arguments() + 1);  // Drop new target.
    node->InsertInput(graph()->zone(), 1, new_target);

532 533 534 535
    // 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).
536 537 538 539
    // 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}).
540
    Node* receiver = jsgraph()->TheHoleConstant();  // Implicit receiver.
541
    Node* context = NodeProperties::GetContextInput(node);
542
    if (NeedsImplicitReceiver(shared_info.value())) {
543
      Node* effect = NodeProperties::GetEffectInput(node);
544
      Node* control = NodeProperties::GetControlInput(node);
545 546 547
      Node* frame_state_inside = CreateArtificialFrameState(
          node, frame_state, call.formal_arguments(),
          BailoutId::ConstructStubCreate(), FrameStateType::kConstructStub,
548
          shared_info.value(), context);
549 550 551
      Node* create =
          graph()->NewNode(javascript()->Create(), call.target(), new_target,
                           context, frame_state_inside, effect, control);
552 553
      uncaught_subcalls.push_back(create);  // Adds {IfSuccess} & {IfException}.
      NodeProperties::ReplaceControlInput(node, create);
554
      NodeProperties::ReplaceEffectInput(node, create);
555 556 557 558 559
      // 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;
560 561 562 563 564 565 566
      // 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);
567
      receiver = create;  // The implicit receiver.
568
      ReplaceWithValue(dummy, result);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    } 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);
      branch_is_receiver_false =
          graph()->NewNode(javascript()->CallRuntime(
                               Runtime::kThrowConstructorReturnedNonObject),
                           context, NodeProperties::GetFrameStateInput(node),
                           node, branch_is_receiver_false);
      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);

592 593 594
      ReplaceWithValue(node_success, node_success, node_success,
                       branch_is_receiver_true);
      // Fix input destroyed by the above {ReplaceWithValue} call.
595
      NodeProperties::ReplaceControlInput(branch_is_receiver, node_success, 0);
596
    }
597
    node->ReplaceInput(1, receiver);
598 599
    // Insert a construct stub frame into the chain of frame states. This will
    // reconstruct the proper frame when deoptimizing within the constructor.
600 601 602
    frame_state = CreateArtificialFrameState(
        node, frame_state, call.formal_arguments(),
        BailoutId::ConstructStubInvoke(), FrameStateType::kConstructStub,
603
        shared_info.value(), context);
604 605
  }

606
  // Insert a JSConvertReceiver node for sloppy callees. Note that the context
607
  // passed into this node has to be the callees context (loaded above).
608
  if (node->opcode() == IrOpcode::kJSCall &&
609
      is_sloppy(shared_info->language_mode()) && !shared_info->native()) {
610
    Node* effect = NodeProperties::GetEffectInput(node);
611
    if (NodeProperties::CanBePrimitive(broker(), call.receiver(), effect)) {
612
      CallParameters const& p = CallParametersOf(node->op());
613 614
      Node* global_proxy =
          jsgraph()->Constant(broker()->native_context().global_proxy_object());
615 616 617 618
      Node* receiver = effect =
          graph()->NewNode(simplified()->ConvertReceiver(p.convert_mode()),
                           call.receiver(), global_proxy, effect, start);
      NodeProperties::ReplaceValueInput(node, receiver, 1);
619 620
      NodeProperties::ReplaceEffectInput(node, effect);
    }
621 622
  }

623
  // Insert argument adaptor frame if required. The callees formal parameter
624 625 626
  // count (i.e. value outputs of start node minus target, receiver, new target,
  // arguments count and context) have to match the number of arguments passed
  // to the call.
627
  int parameter_count = shared_info->internal_formal_parameter_count();
628
  DCHECK_EQ(parameter_count, start->op()->ValueOutputCount() - 5);
629
  if (call.formal_arguments() != parameter_count) {
630
    frame_state = CreateArtificialFrameState(
631
        node, frame_state, call.formal_arguments(), BailoutId::None(),
632
        FrameStateType::kArgumentsAdaptor, shared_info.value());
633 634
  }

635 636
  return InlineCall(node, new_target, context, frame_state, start, end,
                    exception_target, uncaught_subcalls);
637
}
638

639 640
Graph* JSInliner::graph() const { return jsgraph()->graph(); }

641 642 643 644 645 646
JSOperatorBuilder* JSInliner::javascript() const {
  return jsgraph()->javascript();
}

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

647 648 649 650
SimplifiedOperatorBuilder* JSInliner::simplified() const {
  return jsgraph()->simplified();
}

651 652
#undef TRACE

653 654 655
}  // namespace compiler
}  // namespace internal
}  // namespace v8