v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
js-inlining.cc
Go to the documentation of this file.
1// Copyright 2014 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
6
7#include <optional>
8
24
25#if V8_ENABLE_WEBASSEMBLY
29#endif // V8_ENABLE_WEBASSEMBLY
30
31namespace v8 {
32namespace internal {
33namespace compiler {
34
35namespace {
36// This is just to avoid some corner cases, especially since we allow recursive
37// inlining.
38static const int kMaxDepthForInlining = 50;
39} // namespace
40
41#define TRACE(x) \
42 do { \
43 if (v8_flags.trace_turbo_inlining) { \
44 StdoutStream() << x << "\n"; \
45 } \
46 } while (false)
47
48// Provides convenience accessors for the common layout of nodes having either
49// the {JSCall} or the {JSConstruct} operator.
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 Node* receiver() const { return JSCallNode{call_}.receiver(); }
62
63 Node* new_target() const { return JSConstructNode{call_}.new_target(); }
64
68
69 int argument_count() const {
70 return (call_->opcode() == IrOpcode::kJSCall)
73 }
74
75 CallFrequency const& frequency() const {
76 return (call_->opcode() == IrOpcode::kJSCall)
77 ? JSCallNode{call_}.Parameters().frequency()
78 : JSConstructNode{call_}.Parameters().frequency();
79 }
80
81 private:
83};
84
85#if V8_ENABLE_WEBASSEMBLY
86Reduction JSInliner::InlineJSWasmCall(Node* call, Node* new_target,
87 Node* context, Node* frame_state,
89 Node* exception_target,
90 const NodeVector& uncaught_subcalls) {
91 JSWasmCallNode n(call);
92 return InlineCall(
93 call, new_target, context, frame_state, start, end, exception_target,
94 uncaught_subcalls,
95 static_cast<int>(n.Parameters().signature()->parameter_count()));
96}
97#endif // V8_ENABLE_WEBASSEMBLY
98
100 Node* frame_state, StartNode start, Node* end,
101 Node* exception_target,
102 const NodeVector& uncaught_subcalls,
103 int argument_count) {
105 argument_count == JSCallAccessor(call).argument_count());
106
107 // The scheduler is smart enough to place our code; we just ensure {control}
108 // becomes the control input of the start of the inlinee, and {effect} becomes
109 // the effect input of the start of the inlinee.
110 Node* control = NodeProperties::GetControlInput(call);
111 Node* effect = NodeProperties::GetEffectInput(call);
112
113 int const inlinee_new_target_index = start.NewTargetOutputIndex();
114 int const inlinee_arity_index = start.ArgCountOutputIndex();
115 int const inlinee_context_index = start.ContextOutputIndex();
116
117 // {inliner_inputs} counts the target, receiver/new_target, and arguments; but
118 // not feedback vector, context, effect or control.
119 const int inliner_inputs = argument_count +
122 // Iterate over all uses of the start node.
123 for (Edge edge : start->use_edges()) {
124 Node* use = edge.from();
125 switch (use->opcode()) {
126 case IrOpcode::kParameter: {
127 int index = 1 + ParameterIndexOf(use->op());
128 DCHECK_LE(index, inlinee_context_index);
129 if (index < inliner_inputs && index < inlinee_new_target_index) {
130 // There is an input from the call, and the index is a value
131 // projection but not the context, so rewire the input.
132 Replace(use, call->InputAt(index));
133 } else if (index == inlinee_new_target_index) {
134 // The projection is requesting the new target value.
135 Replace(use, new_target);
136 } else if (index == inlinee_arity_index) {
137 // The projection is requesting the number of arguments.
138 Replace(use, jsgraph()->ConstantNoHole(argument_count));
139 } else if (index == inlinee_context_index) {
140 // The projection is requesting the inlinee function context.
141 Replace(use, context);
142 } else {
143#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
144 // Using the dispatch handle here isn't currently supported.
145 DCHECK_NE(index, start.DispatchHandleOutputIndex());
146#endif
147 // Call has fewer arguments than required, fill with undefined.
148 Replace(use, jsgraph()->UndefinedConstant());
149 }
150 break;
151 }
152 default:
154 edge.UpdateTo(effect);
155 } else if (NodeProperties::IsControlEdge(edge)) {
156 edge.UpdateTo(control);
157 } else if (NodeProperties::IsFrameStateEdge(edge)) {
158 edge.UpdateTo(frame_state);
159 } else {
160 UNREACHABLE();
161 }
162 break;
163 }
164 }
165
166 if (exception_target != nullptr) {
167 // Link uncaught calls in the inlinee to {exception_target}
168 int subcall_count = static_cast<int>(uncaught_subcalls.size());
169 if (subcall_count > 0) {
170 TRACE("Inlinee contains " << subcall_count
171 << " calls without local exception handler; "
172 << "linking to surrounding exception handler.");
173 }
174 NodeVector on_exception_nodes(local_zone_);
175 for (Node* subcall : uncaught_subcalls) {
176 Node* on_success = graph()->NewNode(common()->IfSuccess(), subcall);
177 NodeProperties::ReplaceUses(subcall, subcall, subcall, on_success);
178 NodeProperties::ReplaceControlInput(on_success, subcall);
179 Node* on_exception =
180 graph()->NewNode(common()->IfException(), subcall, subcall);
181 on_exception_nodes.push_back(on_exception);
182 }
183
184 DCHECK_EQ(subcall_count, static_cast<int>(on_exception_nodes.size()));
185 if (subcall_count > 0) {
186 Node* control_output =
187 graph()->NewNode(common()->Merge(subcall_count), subcall_count,
188 &on_exception_nodes.front());
189 NodeVector values_effects(local_zone_);
190 values_effects = on_exception_nodes;
191 values_effects.push_back(control_output);
192 Node* value_output = graph()->NewNode(
193 common()->Phi(MachineRepresentation::kTagged, subcall_count),
194 subcall_count + 1, &values_effects.front());
195 Node* effect_output =
196 graph()->NewNode(common()->EffectPhi(subcall_count),
197 subcall_count + 1, &values_effects.front());
198 ReplaceWithValue(exception_target, value_output, effect_output,
199 control_output);
200 } else {
201 ReplaceWithValue(exception_target, exception_target, exception_target,
202 jsgraph()->Dead());
203 }
204 }
205
206 NodeVector values(local_zone_);
207 NodeVector effects(local_zone_);
208 NodeVector controls(local_zone_);
209 for (Node* const input : end->inputs()) {
210 switch (input->opcode()) {
211 case IrOpcode::kReturn:
212 values.push_back(NodeProperties::GetValueInput(input, 1));
215 break;
216 case IrOpcode::kDeoptimize:
217 case IrOpcode::kTerminate:
218 case IrOpcode::kThrow:
219 MergeControlToEnd(graph(), common(), input);
220 break;
221 default:
222 UNREACHABLE();
223 }
224 }
225 DCHECK_EQ(values.size(), effects.size());
226 DCHECK_EQ(values.size(), controls.size());
227
228 // Depending on whether the inlinee produces a value, we either replace value
229 // uses with said value or kill value uses if no value can be returned.
230 if (!values.empty()) {
231 int const input_count = static_cast<int>(controls.size());
232 Node* control_output = graph()->NewNode(common()->Merge(input_count),
233 input_count, &controls.front());
234 values.push_back(control_output);
235 effects.push_back(control_output);
236 Node* value_output = graph()->NewNode(
237 common()->Phi(MachineRepresentation::kTagged, input_count),
238 static_cast<int>(values.size()), &values.front());
239 Node* effect_output =
240 graph()->NewNode(common()->EffectPhi(input_count),
241 static_cast<int>(effects.size()), &effects.front());
242 ReplaceWithValue(call, value_output, effect_output, control_output);
243 return Changed(value_output);
244 } else {
245 ReplaceWithValue(call, jsgraph()->Dead(), jsgraph()->Dead(),
246 jsgraph()->Dead());
247 return Changed(call);
248 }
249}
250
252 Node* node, FrameState outer_frame_state, int argument_count,
253 FrameStateType frame_state_type, SharedFunctionInfoRef shared,
254 OptionalBytecodeArrayRef maybe_bytecode_array, Node* context,
255 Node* callee) {
256 const int argument_count_with_receiver =
258 CHECK_LE(argument_count_with_receiver, kMaxUInt16);
259 IndirectHandle<BytecodeArray> bytecode_array_handle = {};
260 if (maybe_bytecode_array.has_value()) {
261 bytecode_array_handle = maybe_bytecode_array->object();
262 }
263 const FrameStateFunctionInfo* state_info =
265 frame_state_type, argument_count_with_receiver, 0, 0, shared.object(),
266 bytecode_array_handle);
267
268 const Operator* op = common()->FrameState(
271 Node* node0 = graph()->NewNode(op0);
272
273 Node* params_node = nullptr;
274#if V8_ENABLE_WEBASSEMBLY
275 const bool skip_params =
276 frame_state_type == FrameStateType::kWasmInlinedIntoJS;
277#else
278 const bool skip_params = false;
279#endif
280 if (skip_params) {
281 // For wasm inlined into JS the frame state doesn't need to be used for
282 // deopts. Also, due to different calling conventions, there isn't a
283 // receiver at input 1. We still need to store an undefined node here as the
284 // code requires this state values to have at least 1 entry.
285 // TODO(mliedtke): Can we clean up the FrameState handling, so that wasm
286 // inline FrameStates are closer to JS FrameStates without affecting
287 // performance?
288 const Operator* op_param =
290 params_node = graph()->NewNode(op_param, jsgraph()->UndefinedConstant());
291 } else {
292 NodeVector params(local_zone_);
293 params.push_back(
294 node->InputAt(JSCallOrConstructNode::ReceiverOrNewTargetIndex()));
295 for (int i = 0; i < argument_count; i++) {
296 params.push_back(node->InputAt(JSCallOrConstructNode::ArgumentIndex(i)));
297 }
298 const Operator* op_param = common()->StateValues(
299 static_cast<int>(params.size()), SparseInputMask::Dense());
300 params_node = graph()->NewNode(op_param, static_cast<int>(params.size()),
301 &params.front());
302 }
303 if (context == nullptr) context = jsgraph()->UndefinedConstant();
304 if (callee == nullptr) {
305 callee = node->InputAt(JSCallOrConstructNode::TargetIndex());
306 }
307 return FrameState{graph()->NewNode(op, params_node, node0, node0, context,
308 callee, outer_frame_state)};
309}
310
311namespace {
312
313bool NeedsImplicitReceiver(SharedFunctionInfoRef shared_info) {
315 return !shared_info.construct_as_builtin() &&
316 !IsDerivedConstructor(shared_info.kind());
317}
318
319} // namespace
320
321// Determines whether the call target of the given call {node} is statically
322// known and can be used as an inlining candidate. The {SharedFunctionInfo} of
323// the call target is provided (the exact closure might be unknown).
324OptionalSharedFunctionInfoRef JSInliner::DetermineCallTarget(Node* node) {
325 DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
326 Node* target = node->InputAt(JSCallOrConstructNode::TargetIndex());
327 HeapObjectMatcher match(target);
328
329 // This reducer can handle both normal function calls as well a constructor
330 // calls whenever the target is a constant function object, as follows:
331 // - JSCall(target:constant, receiver, args..., vector)
332 // - JSConstruct(target:constant, new.target, args..., vector)
333 if (match.HasResolvedValue() && match.Ref(broker()).IsJSFunction()) {
334 JSFunctionRef function = match.Ref(broker()).AsJSFunction();
335
336 // The function might have not been called yet.
337 if (!function.feedback_vector(broker()).has_value()) {
338 return std::nullopt;
339 }
340
341 // Disallow cross native-context inlining for now. This means that all parts
342 // of the resulting code will operate on the same global object. This also
343 // prevents cross context leaks, where we could inline functions from a
344 // different context and hold on to that context (and closure) from the code
345 // object.
346 // TODO(turbofan): We might want to revisit this restriction later when we
347 // have a need for this, and we know how to model different native contexts
348 // in the same graph in a compositional way.
349 if (!function.native_context(broker()).equals(
350 broker()->target_native_context())) {
351 return std::nullopt;
352 }
353
354 return function.shared(broker());
355 }
356
357 // This reducer can also handle calls where the target is statically known to
358 // be the result of a closure instantiation operation, as follows:
359 // - JSCall(JSCreateClosure[shared](context), receiver, args..., vector)
360 // - JSConstruct(JSCreateClosure[shared](context),
361 // new.target, args..., vector)
362 if (match.IsJSCreateClosure()) {
363 JSCreateClosureNode n(target);
364 FeedbackCellRef cell = n.GetFeedbackCellRefChecked(broker());
365 return cell.shared_function_info(broker());
366 } else if (match.IsCheckClosure()) {
367 FeedbackCellRef cell = MakeRef(broker(), FeedbackCellOf(match.op()));
368 return cell.shared_function_info(broker());
369 }
370
371 return std::nullopt;
372}
373
374// Determines statically known information about the call target (assuming that
375// the call target is known according to {DetermineCallTarget} above). The
376// following static information is provided:
377// - context : The context (as SSA value) bound by the call target.
378// - feedback_vector : The target is guaranteed to use this feedback vector.
380 Node** context_out) {
381 DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
382 Node* target = node->InputAt(JSCallOrConstructNode::TargetIndex());
383 HeapObjectMatcher match(target);
384
385 if (match.HasResolvedValue() && match.Ref(broker()).IsJSFunction()) {
386 JSFunctionRef function = match.Ref(broker()).AsJSFunction();
387 // This was already ensured by DetermineCallTarget
388 CHECK(function.feedback_vector(broker()).has_value());
389
390 // The inlinee specializes to the context from the JSFunction object.
391 *context_out =
392 jsgraph()->ConstantNoHole(function.context(broker()), broker());
393 return function.raw_feedback_cell(broker());
394 }
395
396 if (match.IsJSCreateClosure()) {
397 // Load the feedback vector of the target by looking up its vector cell at
398 // the instantiation site (we only decide to inline if it's populated).
399 JSCreateClosureNode n(target);
400 FeedbackCellRef cell = n.GetFeedbackCellRefChecked(broker());
401
402 // The inlinee uses the locally provided context at instantiation.
403 *context_out = NodeProperties::GetContextInput(match.node());
404 return cell;
405 } else if (match.IsCheckClosure()) {
406 FeedbackCellRef cell = MakeRef(broker(), FeedbackCellOf(match.op()));
407
408 Node* effect = NodeProperties::GetEffectInput(node);
409 Node* control = NodeProperties::GetControlInput(node);
410 *context_out = effect = graph()->NewNode(
412 match.node(), effect, control);
414
415 return cell;
416 }
417
418 // Must succeed.
419 UNREACHABLE();
420}
421
422#if V8_ENABLE_WEBASSEMBLY
423JSInliner::WasmInlineResult JSInliner::TryWasmInlining(
424 const JSWasmCallNode& call_node) {
425 const JSWasmCallParameters& wasm_call_params = call_node.Parameters();
426 wasm::NativeModule* native_module = wasm_call_params.native_module();
427 const int fct_index = wasm_call_params.function_index();
428 TRACE("Considering wasm function ["
429 << fct_index << "] "
430 << WasmFunctionNameForTrace(native_module, fct_index) << " of module "
431 << wasm_call_params.module() << " for inlining");
432
433 if (native_module->module() != wasm_module_) {
434 // Inlining of multiple wasm modules into the same JS function is not
435 // supported.
436 TRACE("- not inlining: another wasm module is already used for inlining");
437 return {};
438 }
439 if (NodeProperties::IsExceptionalCall(call_node)) {
440 // TODO(14034): It would be useful to also support inlining of wasm
441 // functions if they are surrounded by a try block which requires further
442 // work, so that the wasm trap gets forwarded to the corresponding catch
443 // block.
444 TRACE("- not inlining: wasm inlining into try catch is not supported");
445 return {};
446 }
447
448 const wasm::FunctionSig* sig = wasm_module_->functions[fct_index].sig;
449 TFGraph::SubgraphScope graph_scope(graph());
450 WasmGraphBuilder builder(nullptr, zone(), jsgraph(), sig, source_positions_,
452 native_module->enabled_features());
453 SourcePosition call_pos = source_positions_->GetSourcePosition(call_node);
454 // Calculate hypothetical inlining id, so if we can't inline, we do not add
455 // the wasm function to the list of inlined functions.
456 int inlining_id = static_cast<int>(info_->inlined_functions().size());
457 bool can_inline_body =
458 builder.TryWasmInlining(fct_index, native_module, inlining_id);
459 if (can_inline_body) {
460 int actual_id =
461 info_->AddInlinedFunction(wasm_call_params.shared_fct_info().object(),
462 Handle<BytecodeArray>(), call_pos);
463 CHECK_EQ(inlining_id, actual_id);
464 }
465 return {can_inline_body, graph()->start(), graph()->end()};
466}
467
468Reduction JSInliner::ReduceJSWasmCall(Node* node) {
469 JSWasmCallNode call_node(node);
470 const JSWasmCallParameters& wasm_call_params = call_node.Parameters();
471 int fct_index = wasm_call_params.function_index();
472 wasm::NativeModule* native_module = wasm_call_params.native_module();
473 const wasm::CanonicalSig* sig = wasm_call_params.signature();
474
475 // Try "full" inlining of very simple wasm functions (mainly getters / setters
476 // for wasm gc objects).
477 WasmInlineResult inline_result;
478 if (inline_wasm_fct_if_supported_ && fct_index != -1 && native_module &&
479 // Disable inlining for asm.js functions because we haven't tested it
480 // and most asm.js opcodes aren't supported anyway.
481 !is_asmjs_module(native_module->module())) {
482 inline_result = TryWasmInlining(call_node);
483 }
484
485 // Create the subgraph for the wrapper inlinee.
486 Node* wrapper_start_node;
487 Node* wrapper_end_node;
488 size_t subgraph_min_node_id;
489 {
490 TFGraph::SubgraphScope scope(graph());
491 graph()->SetEnd(nullptr);
492
493 // Create a nested frame state inside the frame state attached to the
494 // call; this will ensure that lazy deoptimizations at this point will
495 // still return the result of the Wasm function call.
496 Node* continuation_frame_state =
497 CreateJSWasmCallBuiltinContinuationFrameState(
498 jsgraph(), call_node.context(), call_node.frame_state(), sig);
499
500 // All the nodes inserted by the inlined subgraph will have
501 // id >= subgraph_min_node_id. We use this later to avoid wire nodes that
502 // are not inserted by the inlinee but were already part of the graph to the
503 // surrounding exception handler, if present.
504 subgraph_min_node_id = graph()->NodeCount();
505
506 // If we inline the body with Turboshaft later (instead of with TurboFan
507 // here), we don't know yet whether we can inline the body or not. Hence,
508 // don't set the thread-in-wasm flag now, and instead do that if _not_
509 // inlining later in Turboshaft.
510 bool set_in_wasm_flag = !(inline_result.can_inline_body ||
511 v8_flags.turboshaft_wasm_in_js_inlining);
513 source_positions_, continuation_frame_state,
514 set_in_wasm_flag);
515
516 // Extract the inlinee start/end nodes.
517 wrapper_start_node = graph()->start();
518 wrapper_end_node = graph()->end();
519 }
520 StartNode start{wrapper_start_node};
521
522 Node* exception_target = nullptr;
523 NodeProperties::IsExceptionalCall(node, &exception_target);
524
525 // If we are inlining into a surrounding exception handler, we collect all
526 // potentially throwing nodes within the inlinee that are not handled locally
527 // by the inlinee itself. They are later wired into the surrounding handler.
528 NodeVector uncaught_subcalls(local_zone_);
529 if (exception_target != nullptr) {
530 // Find all uncaught 'calls' in the inlinee.
531 AllNodes inlined_nodes(local_zone_, wrapper_end_node, graph());
532 for (Node* subnode : inlined_nodes.reachable) {
533 // Ignore nodes that are not part of the inlinee.
534 if (subnode->id() < subgraph_min_node_id) continue;
535
536 // Every possibly throwing node should get {IfSuccess} and {IfException}
537 // projections, unless there already is local exception handling.
538 if (subnode->op()->HasProperty(Operator::kNoThrow)) continue;
539 if (!NodeProperties::IsExceptionalCall(subnode)) {
540 DCHECK_EQ(2, subnode->op()->ControlOutputCount());
541 uncaught_subcalls.push_back(subnode);
542 }
543 }
544 }
545
546 // Search in inlined nodes for call to inline wasm.
547 // Note: We can only inline wasm functions of a single wasm module into any
548 // given JavaScript function (due to the WasmGCLowering being dependent on
549 // module-specific type indices).
550 Node* wasm_fct_call = nullptr;
551 if (inline_result.can_inline_body ||
552 v8_flags.turboshaft_wasm_in_js_inlining) {
553 AllNodes inlined_nodes(local_zone_, wrapper_end_node, graph());
554 for (Node* subnode : inlined_nodes.reachable) {
555 // Ignore nodes that are not part of the inlinee.
556 if (subnode->id() < subgraph_min_node_id) continue;
557
558 if (subnode->opcode() == IrOpcode::kCall &&
559 CallDescriptorOf(subnode->op())->IsAnyWasmFunctionCall()) {
560 wasm_fct_call = subnode;
561 break;
562 }
563 }
564 DCHECK_IMPLIES(inline_result.can_inline_body, wasm_fct_call != nullptr);
565
566 // Attach information about Wasm call target for Turboshaft Wasm-in-JS-
567 // inlining (see https://crbug.com/353475584) in sidetable.
568 if (v8_flags.turboshaft_wasm_in_js_inlining && wasm_fct_call) {
569 auto [it, inserted] = js_wasm_calls_sidetable_->insert(
570 {wasm_fct_call->id(), &wasm_call_params});
571 USE(it);
572 DCHECK(inserted);
573 }
574 }
575
576 Node* context = NodeProperties::GetContextInput(node);
577 Node* frame_state = NodeProperties::GetFrameStateInput(node);
578 Node* new_target = jsgraph()->UndefinedConstant();
579
580 // Inline the wasm wrapper.
581 Reduction r =
582 InlineJSWasmCall(node, new_target, context, frame_state, start,
583 wrapper_end_node, exception_target, uncaught_subcalls);
584 // Inline the wrapped wasm body if supported.
585 if (inline_result.can_inline_body) {
586 InlineWasmFunction(wasm_fct_call, inline_result.body_start,
587 inline_result.body_end, call_node.frame_state(),
588 wasm_call_params.shared_fct_info(),
589 call_node.ArgumentCount(), context);
590 }
591 return r;
592}
593
594void JSInliner::InlineWasmFunction(Node* call, Node* inlinee_start,
595 Node* inlinee_end, Node* frame_state,
596 SharedFunctionInfoRef shared_fct_info,
597 int argument_count, Node* context) {
598 // TODO(14034): This is very similar to what is done for wasm inlining inside
599 // another wasm function. Can we reuse some of its code?
600 // 1) Rewire function entry.
601 Node* control = NodeProperties::GetControlInput(call);
602 Node* effect = NodeProperties::GetEffectInput(call);
603
604 // Add checkpoint with artificial Framestate for inlined wasm function.
605 // Treat the call as having no arguments. The arguments are not needed for
606 // stack trace creation and it costs runtime to save them at the checkpoint.
607 argument_count = 0;
608 // We do not have a proper callee JSFunction object.
609 Node* callee = jsgraph()->UndefinedConstant();
610 Node* frame_state_inside = CreateArtificialFrameState(
611 call, FrameState{frame_state}, argument_count,
612 FrameStateType::kWasmInlinedIntoJS, shared_fct_info, {}, context, callee);
613 Node* check_point = graph()->NewNode(common()->Checkpoint(),
614 frame_state_inside, effect, control);
615 effect = check_point;
616
617 for (Edge edge : inlinee_start->use_edges()) {
618 Node* use = edge.from();
619 if (use == nullptr) continue;
620 switch (use->opcode()) {
621 case IrOpcode::kParameter: {
622 // Index 0 is the callee node.
623 int index = 1 + ParameterIndexOf(use->op());
624 Node* arg = NodeProperties::GetValueInput(call, index);
625 Replace(use, arg);
626 break;
627 }
628 default:
630 edge.UpdateTo(effect);
631 } else if (NodeProperties::IsControlEdge(edge)) {
632 // Projections pointing to the inlinee start are floating
633 // control. They should point to the graph's start.
634 edge.UpdateTo(use->opcode() == IrOpcode::kProjection
635 ? graph()->start()
636 : control);
637 } else {
638 UNREACHABLE();
639 }
640 Revisit(edge.from());
641 break;
642 }
643 }
644
645 // 2) Handle all graph terminators for the callee.
646 // Special case here: There is only one call terminator.
647 DCHECK_EQ(inlinee_end->inputs().count(), 1);
648 Node* terminator = *inlinee_end->inputs().begin();
649 DCHECK_EQ(terminator->opcode(), IrOpcode::kReturn);
650 inlinee_end->Kill();
651
652 // 3) Rewire unhandled calls to the handler.
653 // This is not supported yet resulting in exceptional calls being treated
654 // as non-inlineable.
656
657 // 4) Handle return values.
658 int return_values = terminator->InputCount();
659 DCHECK_GE(return_values, 3);
660 DCHECK_LE(return_values, 4);
661 // Subtract effect, control and drop count.
662 int return_count = return_values - 3;
663 Node* effect_output = terminator->InputAt(return_count + 1);
664 Node* control_output = terminator->InputAt(return_count + 2);
665 for (Edge use_edge : call->use_edges()) {
666 if (NodeProperties::IsValueEdge(use_edge)) {
667 Node* use = use_edge.from();
668 // There is at most one value edge.
669 ReplaceWithValue(use, return_count == 1 ? terminator->InputAt(1)
671 }
672 }
673 // All value inputs are replaced by the above loop, so it is ok to use
674 // Dead() as a dummy for value replacement.
675 ReplaceWithValue(call, jsgraph()->Dead(), effect_output, control_output);
676}
677
678#endif // V8_ENABLE_WEBASSEMBLY
679
681 DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
682#if V8_ENABLE_WEBASSEMBLY
683 DCHECK_NE(node->opcode(), IrOpcode::kJSWasmCall);
684#endif // V8_ENABLE_WEBASSEMBLY
685 JSCallAccessor call(node);
686
687 // Determine the call target.
688 OptionalSharedFunctionInfoRef shared_info(DetermineCallTarget(node));
689 if (!shared_info.has_value()) return NoChange();
690
691 SharedFunctionInfoRef outer_shared_info =
693
695 shared_info->GetInlineability(broker());
696 if (inlineability != SharedFunctionInfo::kIsInlineable) {
697 // The function is no longer inlineable. The only way this can happen is if
698 // the function had its optimization disabled in the meantime, e.g. because
699 // another optimization job failed too often.
701 TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
702 << " because it had its optimization disabled.");
703 return NoChange();
704 }
705 // NOTE: Even though we bailout in the kHasOptimizationDisabled case above, we
706 // won't notice if the function's optimization is disabled after this point.
707
708 // Constructor must be constructable.
709 if (node->opcode() == IrOpcode::kJSConstruct &&
710 !IsConstructable(shared_info->kind())) {
711 TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
712 << " because constructor is not constructable.");
713 return NoChange();
714 }
715
716 // Class constructors are callable, but [[Call]] will raise an exception.
717 // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList ).
718 if (node->opcode() == IrOpcode::kJSCall &&
719 IsClassConstructor(shared_info->kind())) {
720 TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
721 << " because callee is a class constructor.");
722 return NoChange();
723 }
724
725 // To ensure inlining always terminates, we have an upper limit on inlining
726 // the nested calls.
727 int nesting_level = 0;
728 for (Node* frame_state = call.frame_state();
729 frame_state->opcode() == IrOpcode::kFrameState;
730 frame_state = FrameState{frame_state}.outer_frame_state()) {
731 nesting_level++;
732 if (nesting_level > kMaxDepthForInlining) {
733 TRACE("Not inlining "
734 << *shared_info << " into " << outer_shared_info
735 << " because call has exceeded the maximum depth for function "
736 "inlining.");
737 return NoChange();
738 }
739 }
740
741 Node* exception_target = nullptr;
742 NodeProperties::IsExceptionalCall(node, &exception_target);
743
744 // JSInliningHeuristic has already filtered candidates without a BytecodeArray
745 // based on SharedFunctionInfoRef::GetInlineability. For the inlineable ones
746 // (kIsInlineable), the broker holds a reference to the bytecode array, which
747 // prevents it from getting flushed. Therefore, the following check should
748 // always hold true.
749 CHECK(shared_info->is_compiled());
750
751 if (info_->source_positions() &&
752 !shared_info->object()->AreSourcePositionsAvailable(
753 broker()->local_isolate_or_isolate())) {
754 // This case is expected to be very rare, since we generate source
755 // positions for all functions when debugging or profiling are turned
756 // on (see Isolate::NeedsDetailedOptimizedCodeLineInfo). Source
757 // positions should only be missing here if there is a race between 1)
758 // enabling/disabling the debugger/profiler, and 2) this compile job.
759 // In that case, we simply don't inline.
760 TRACE("Not inlining " << *shared_info << " into " << outer_shared_info
761 << " because source positions are missing.");
762 return NoChange();
763 }
764
765 // Determine the target's feedback vector and its context.
766 Node* context;
767 FeedbackCellRef feedback_cell = DetermineCallContext(node, &context);
768
769 TRACE("Inlining " << *shared_info << " into " << outer_shared_info
770 << ((exception_target != nullptr) ? " (inside try-block)"
771 : ""));
772 // ----------------------------------------------------------------
773 // After this point, we've made a decision to inline this function.
774 // We shall not bailout from inlining if we got here.
775
776 BytecodeArrayRef bytecode_array = shared_info->GetBytecodeArray(broker());
777
778 // Remember that we inlined this function.
779 int inlining_id =
780 info_->AddInlinedFunction(shared_info->object(), bytecode_array.object(),
782 if (v8_flags.profile_guided_optimization &&
783 feedback_cell.feedback_vector(broker()).has_value() &&
784 feedback_cell.feedback_vector(broker())
785 .value()
786 .object()
787 ->invocation_count_before_stable(kRelaxedLoad) >
788 v8_flags.invocation_count_for_early_optimization) {
789 info_->set_could_not_inline_all_candidates();
790 }
791
792 // Create the subgraph for the inlinee.
793 Node* start_node;
794 Node* end;
795 {
796 // Run the BytecodeGraphBuilder to create the subgraph.
800 if (info_->analyze_environment_liveness()) {
802 }
803 if (info_->bailout_on_uninitialized()) {
805 }
806 {
807 CallFrequency frequency = call.frequency();
808 BuildGraphFromBytecode(broker(), zone(), *shared_info, bytecode_array,
809 feedback_cell, BytecodeOffset::None(), jsgraph(),
811 inlining_id, info_->code_kind(), flags,
812 &info_->tick_counter());
813 }
814
815 // Extract the inlinee start/end nodes.
816 start_node = graph()->start();
817 end = graph()->end();
818 }
819 StartNode start{start_node};
820
821 // If we are inlining into a surrounding exception handler, we collect all
822 // potentially throwing nodes within the inlinee that are not handled locally
823 // by the inlinee itself. They are later wired into the surrounding handler.
824 NodeVector uncaught_subcalls(local_zone_);
825 if (exception_target != nullptr) {
826 // Find all uncaught 'calls' in the inlinee.
827 AllNodes inlined_nodes(local_zone_, end, graph());
828 for (Node* subnode : inlined_nodes.reachable) {
829 // Every possibly throwing node should get {IfSuccess} and {IfException}
830 // projections, unless there already is local exception handling.
831 if (subnode->op()->HasProperty(Operator::kNoThrow)) continue;
832 if (!NodeProperties::IsExceptionalCall(subnode)) {
833 DCHECK_EQ(2, subnode->op()->ControlOutputCount());
834 uncaught_subcalls.push_back(subnode);
835 }
836 }
837 }
838
839 FrameState frame_state = call.frame_state();
840 Node* new_target = jsgraph()->UndefinedConstant();
841
842 // Inline {JSConstruct} requires some additional magic.
843 if (node->opcode() == IrOpcode::kJSConstruct) {
845 JSConstructNode n(node);
846
847 new_target = n.new_target();
848
849 // Insert nodes around the call that model the behavior required for a
850 // constructor dispatch (allocate implicit receiver and check return value).
851 // This models the behavior usually accomplished by our {JSConstructStub}.
852 // Note that the context has to be the callers context (input to call node).
853 // Also note that by splitting off the {JSCreate} piece of the constructor
854 // call, we create an observable deoptimization point after the receiver
855 // instantiation but before the invocation (i.e. inside {JSConstructStub}
856 // where execution continues at {construct_stub_create_deopt_pc_offset}).
857 Node* receiver = jsgraph()->TheHoleConstant(); // Implicit receiver.
858 Node* caller_context = NodeProperties::GetContextInput(node);
859 if (NeedsImplicitReceiver(*shared_info)) {
860 Effect effect = n.effect();
861 Control control = n.control();
862 Node* frame_state_inside;
864 if (m.HasResolvedValue() && m.Ref(broker()).IsJSFunction()) {
865 // If {new_target} is a JSFunction, then we cannot deopt in the
866 // NewObject call. Therefore we do not need the artificial frame state.
867 frame_state_inside = frame_state;
868 } else {
869 frame_state_inside = CreateArtificialFrameState(
870 node, frame_state, n.ArgumentCount(),
871 FrameStateType::kConstructCreateStub, *shared_info, bytecode_array,
872 caller_context);
873 }
874 Node* create =
875 graph()->NewNode(javascript()->Create(), call.target(), new_target,
876 caller_context, frame_state_inside, effect, control);
877 uncaught_subcalls.push_back(create); // Adds {IfSuccess} & {IfException}.
880 // Placeholder to hold {node}'s value dependencies while {node} is
881 // replaced.
882 Node* dummy = graph()->NewNode(common()->Dead());
883 NodeProperties::ReplaceUses(node, dummy, node, node, node);
884 Node* result;
885 // Insert a check of the return value to determine whether the return
886 // value or the implicit receiver should be selected as a result of the
887 // call.
888 Node* check = graph()->NewNode(simplified()->ObjectIsReceiver(), node);
889 result =
891 check, node, create);
892 receiver = create; // The implicit receiver.
893 ReplaceWithValue(dummy, result);
894 } else if (IsDerivedConstructor(shared_info->kind())) {
895 Node* node_success =
897 Node* is_receiver =
898 graph()->NewNode(simplified()->ObjectIsReceiver(), node);
899 Node* branch_is_receiver =
900 graph()->NewNode(common()->Branch(), is_receiver, node_success);
901 Node* branch_is_receiver_true =
902 graph()->NewNode(common()->IfTrue(), branch_is_receiver);
903 Node* branch_is_receiver_false =
904 graph()->NewNode(common()->IfFalse(), branch_is_receiver);
905 branch_is_receiver_false = graph()->NewNode(
907 Runtime::kThrowConstructorReturnedNonObject),
908 caller_context, NodeProperties::GetFrameStateInput(node), node,
909 branch_is_receiver_false);
910 uncaught_subcalls.push_back(branch_is_receiver_false);
911 branch_is_receiver_false =
912 graph()->NewNode(common()->Throw(), branch_is_receiver_false,
913 branch_is_receiver_false);
914 MergeControlToEnd(graph(), common(), branch_is_receiver_false);
915
916 ReplaceWithValue(node_success, node_success, node_success,
917 branch_is_receiver_true);
918 // Fix input destroyed by the above {ReplaceWithValue} call.
919 NodeProperties::ReplaceControlInput(branch_is_receiver, node_success, 0);
920 }
921 node->ReplaceInput(JSCallNode::ReceiverIndex(), receiver);
922 // Insert a construct stub frame into the chain of frame states. This will
923 // reconstruct the proper frame when deoptimizing within the constructor.
924 frame_state = CreateArtificialFrameState(
925 node, frame_state, 0, FrameStateType::kConstructInvokeStub,
926 *shared_info, bytecode_array, caller_context);
927 }
928
929 // Insert a JSConvertReceiver node for sloppy callees. Note that the context
930 // passed into this node has to be the callees context (loaded above).
931 if (node->opcode() == IrOpcode::kJSCall &&
932 is_sloppy(shared_info->language_mode()) && !shared_info->native()) {
934 if (NodeProperties::CanBePrimitive(broker(), call.receiver(), effect)) {
935 CallParameters const& p = CallParametersOf(node->op());
936 Node* global_proxy = jsgraph()->ConstantNoHole(
937 broker()->target_native_context().global_proxy_object(broker()),
938 broker());
939 Node* receiver = effect = graph()->NewNode(
940 simplified()->ConvertReceiver(p.convert_mode()), call.receiver(),
941 jsgraph()->ConstantNoHole(broker()->target_native_context(),
942 broker()),
943 global_proxy, effect, start);
945 JSCallNode::ReceiverIndex());
947 }
948 }
949
950 // Insert inlined extra arguments if required. The callees formal parameter
951 // count have to match the number of arguments passed to the call.
954 shared_info->internal_formal_parameter_count_without_receiver());
955 DCHECK_EQ(parameter_count, start.FormalParameterCountWithoutReceiver());
956 if (call.argument_count() != parameter_count) {
957 frame_state = CreateArtificialFrameState(
958 node, frame_state, call.argument_count(),
959 FrameStateType::kInlinedExtraArguments, *shared_info, bytecode_array);
960 }
961
962 return InlineCall(node, new_target, context, frame_state, start, end,
963 exception_target, uncaught_subcalls, call.argument_count());
964}
965
966TFGraph* JSInliner::graph() const { return jsgraph()->graph(); }
967
971
973
977
978#undef TRACE
979
980} // namespace compiler
981} // namespace internal
982} // namespace v8
int16_t parameter_count
Definition builtins.cc:67
static constexpr BytecodeOffset None()
Definition utils.h:675
int AddInlinedFunction(IndirectHandle< SharedFunctionInfo > inlined_function, IndirectHandle< BytecodeArray > inlined_bytecode, SourcePosition pos)
IndirectHandle< SharedFunctionInfo > shared_info() const
void push_back(const T &value)
void ReplaceWithValue(Node *node, Node *value, Node *effect=nullptr, Node *control=nullptr)
void MergeControlToEnd(TFGraph *graph, CommonOperatorBuilder *common, Node *node)
static Reduction Replace(Node *node)
IndirectHandle< BytecodeArray > object() const
ConvertReceiverMode convert_mode() const
const Operator * StateValues(int arguments, SparseInputMask bitmask)
const Operator * FrameState(BytecodeOffset bailout_id, OutputFrameStateCombine state_combine, const FrameStateFunctionInfo *function_info)
const FrameStateFunctionInfo * CreateFrameStateFunctionInfo(FrameStateType type, uint16_t parameter_count, uint16_t max_arguments, int local_count, IndirectHandle< SharedFunctionInfo > shared_info, IndirectHandle< BytecodeArray > bytecode_array)
OptionalSharedFunctionInfoRef shared_function_info(JSHeapBroker *broker) const
OptionalFeedbackVectorRef feedback_vector(JSHeapBroker *broker) const
static bool IsInlineeOpcode(Value value)
Definition opcodes.h:1421
CallFrequency const & frequency() const
const CallParameters & Parameters() const
static constexpr int ArgumentIndex(int i)
const ConstructParameters & Parameters() const
JSOperatorBuilder * javascript() const
Definition js-graph.h:104
SimplifiedOperatorBuilder * simplified() const
Definition js-graph.h:105
Node * ConstantNoHole(ObjectRef ref, JSHeapBroker *broker)
Definition js-graph.cc:51
Reduction ReduceJSCall(Node *node)
JSHeapBroker * broker() const
Definition js-inlining.h:89
FrameState CreateArtificialFrameState(Node *node, FrameState outer_frame_state, int parameter_count, FrameStateType frame_state_type, SharedFunctionInfoRef shared, OptionalBytecodeArrayRef maybe_bytecode_array, Node *context=nullptr, Node *callee=nullptr)
Reduction InlineCall(Node *call, Node *new_target, Node *context, Node *frame_state, StartNode start, Node *end, Node *exception_target, const NodeVector &uncaught_subcalls, int argument_count)
CommonOperatorBuilder * common() const
NodeOriginTable *const node_origins_
Definition js-inlining.h:97
SimplifiedOperatorBuilder * simplified() const
JSOperatorBuilder * javascript() const
JsWasmCallsSidetable * js_wasm_calls_sidetable_
Definition js-inlining.h:99
const wasm::WasmModule * wasm_module_
Definition js-inlining.h:98
OptionalSharedFunctionInfoRef DetermineCallTarget(Node *node)
FeedbackCellRef DetermineCallContext(Node *node, Node **context_out)
OptimizedCompilationInfo * info_
Definition js-inlining.h:93
SourcePositionTable *const source_positions_
Definition js-inlining.h:96
CommonOperatorBuilder * common() const
static void ReplaceEffectInput(Node *node, Node *effect, int index=0)
static void ReplaceControlInput(Node *node, Node *control, int index=0)
static void ReplaceUses(Node *node, Node *value, Node *effect=nullptr, Node *success=nullptr, Node *exception=nullptr)
static Node * GetEffectInput(Node *node, int index=0)
static Node * GetContextInput(Node *node)
static Node * GetFrameStateInput(Node *node)
static bool CanBePrimitive(JSHeapBroker *broker, Node *receiver, Effect effect)
static Node * GetValueInput(Node *node, int index)
static void ReplaceValueInput(Node *node, Node *value, int index)
static bool IsExceptionalCall(Node *node, Node **out_exception=nullptr)
static Node * GetControlInput(Node *node, int index=0)
static Node * FindSuccessfulControlProjection(Node *node)
constexpr IrOpcode::Value opcode() const
Definition node.h:52
Inputs inputs() const
Definition node.h:478
const Operator * op() const
Definition node.h:50
Node * InputAt(int index) const
Definition node.h:70
static OutputFrameStateCombine Ignore()
static Reduction Changed(Node *node)
Node * NewNode(const Operator *op, int input_count, Node *const *inputs, bool incomplete=false)
const WasmModule * module() const
WasmEnabledFeatures enabled_features() const
int start
int end
DirectHandle< Object > new_target
Definition execution.cc:75
TNode< Context > context
TNode< Object > receiver
FrameState outer_frame_state
ZoneVector< RpoNumber > & result
#define TRACE(...)
int m
Definition mul-fft.cc:294
int n
Definition mul-fft.cc:296
int r
Definition mul-fft.cc:298
TNode< Oddball > UndefinedConstant(JSGraph *jsgraph)
CallDescriptor const * CallDescriptorOf(const Operator *const op)
ZoneVector< Node * > NodeVector
Definition node.h:374
int ParameterIndexOf(const Operator *const op)
const CallParameters & CallParametersOf(const Operator *op)
Handle< FeedbackCell > FeedbackCellOf(const Operator *op)
void BuildInlinedJSToWasmWrapper(Zone *zone, MachineGraph *mcgraph, const wasm::CanonicalSig *signature, Isolate *isolate, compiler::SourcePositionTable *spt, Node *frame_state, bool set_in_wasm_flag)
void BuildGraphFromBytecode(JSHeapBroker *broker, Zone *local_zone, SharedFunctionInfoRef shared_info, BytecodeArrayRef bytecode, FeedbackCellRef feedback_cell, BytecodeOffset osr_offset, JSGraph *jsgraph, CallFrequency const &invocation_frequency, SourcePositionTable *source_positions, NodeOriginTable *node_origins, int inlining_id, CodeKind code_kind, BytecodeGraphBuilderFlags flags, TickCounter *tick_counter, ObserveNodeInfo const &observe_node_info)
ref_traits< T >::ref_type MakeRef(JSHeapBroker *broker, Tagged< T > object)
bool is_asmjs_module(const WasmModule *module)
Signature< ValueType > FunctionSig
bool is_sloppy(LanguageMode language_mode)
Definition globals.h:773
bool IsClassConstructor(FunctionKind kind)
bool IsDerivedConstructor(FunctionKind kind)
constexpr int kMaxUInt16
Definition globals.h:382
kWasmInternalFunctionIndirectPointerTag kProtectedInstanceDataOffset sig
Flag flags[]
Definition flags.cc:3797
bool IsConstructable(FunctionKind kind)
V8_EXPORT_PRIVATE FlagValues v8_flags
return value
Definition map-inl.h:893
Local< T > Handle
static constexpr RelaxedLoadTag kRelaxedLoad
Definition globals.h:2909
uint32_t equals
#define DCHECK_LE(v1, v2)
Definition logging.h:490
#define CHECK(condition)
Definition logging.h:124
#define CHECK_LE(lhs, rhs)
#define DCHECK_IMPLIES(v1, v2)
Definition logging.h:493
#define DCHECK_NE(v1, v2)
Definition logging.h:486
#define DCHECK_GE(v1, v2)
Definition logging.h:488
#define CHECK_EQ(lhs, rhs)
#define DCHECK(condition)
Definition logging.h:482
#define DCHECK_EQ(v1, v2)
Definition logging.h:485
#define USE(...)
Definition macros.h:293
HeapObjectRef Ref(JSHeapBroker *broker) const
const Operator * op() const