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 
5 #include "src/compiler/js-inlining.h"
6 
7 #include "src/ast/ast.h"
8 #include "src/ast/ast-numbering.h"
9 #include "src/ast/scopes.h"
10 #include "src/compiler.h"
11 #include "src/compiler/all-nodes.h"
12 #include "src/compiler/ast-graph-builder.h"
13 #include "src/compiler/common-operator.h"
14 #include "src/compiler/graph-reducer.h"
15 #include "src/compiler/js-operator.h"
16 #include "src/compiler/node-matchers.h"
17 #include "src/compiler/node-properties.h"
18 #include "src/compiler/operator-properties.h"
19 #include "src/isolate-inl.h"
20 #include "src/parsing/parser.h"
21 #include "src/parsing/rewriter.h"
22 
23 namespace v8 {
24 namespace internal {
25 namespace compiler {
26 
27 #define TRACE(...)                                      \
28   do {                                                  \
29     if (FLAG_trace_turbo_inlining) PrintF(__VA_ARGS__); \
30   } while (false)
31 
32 
33 // Provides convenience accessors for the common layout of nodes having either
34 // the {JSCallFunction} or the {JSCallConstruct} operator.
35 class JSCallAccessor {
36  public:
JSCallAccessor(Node * call)37   explicit JSCallAccessor(Node* call) : call_(call) {
38     DCHECK(call->opcode() == IrOpcode::kJSCallFunction ||
39            call->opcode() == IrOpcode::kJSCallConstruct);
40   }
41 
target()42   Node* target() {
43     // Both, {JSCallFunction} and {JSCallConstruct}, have same layout here.
44     return call_->InputAt(0);
45   }
46 
receiver()47   Node* receiver() {
48     DCHECK_EQ(IrOpcode::kJSCallFunction, call_->opcode());
49     return call_->InputAt(1);
50   }
51 
new_target()52   Node* new_target() {
53     DCHECK_EQ(IrOpcode::kJSCallConstruct, call_->opcode());
54     return call_->InputAt(formal_arguments() + 1);
55   }
56 
frame_state_before()57   Node* frame_state_before() {
58     return NodeProperties::GetFrameStateInput(call_, 1);
59   }
60 
frame_state_after()61   Node* frame_state_after() {
62     // Both, {JSCallFunction} and {JSCallConstruct}, have frame state after.
63     return NodeProperties::GetFrameStateInput(call_, 0);
64   }
65 
formal_arguments()66   int formal_arguments() {
67     // Both, {JSCallFunction} and {JSCallConstruct}, have two extra inputs:
68     //  - JSCallConstruct: Includes target function and new target.
69     //  - JSCallFunction: Includes target function and receiver.
70     return call_->op()->ValueInputCount() - 2;
71   }
72 
73  private:
74   Node* call_;
75 };
76 
77 
78 class CopyVisitor {
79  public:
CopyVisitor(Graph * source_graph,Graph * target_graph,Zone * temp_zone)80   CopyVisitor(Graph* source_graph, Graph* target_graph, Zone* temp_zone)
81       : sentinel_op_(IrOpcode::kDead, Operator::kNoProperties, "Sentinel", 0, 0,
82                      0, 0, 0, 0),
83         sentinel_(target_graph->NewNode(&sentinel_op_)),
84         copies_(source_graph->NodeCount(), sentinel_, temp_zone),
85         source_graph_(source_graph),
86         target_graph_(target_graph),
87         temp_zone_(temp_zone) {}
88 
GetCopy(Node * orig)89   Node* GetCopy(Node* orig) { return copies_[orig->id()]; }
90 
CopyGraph()91   void CopyGraph() {
92     NodeVector inputs(temp_zone_);
93     // TODO(bmeurer): AllNodes should be turned into something like
94     // Graph::CollectNodesReachableFromEnd() and the gray set stuff should be
95     // removed since it's only needed by the visualizer.
96     AllNodes all(temp_zone_, source_graph_);
97     // Copy all nodes reachable from end.
98     for (Node* orig : all.live) {
99       Node* copy = GetCopy(orig);
100       if (copy != sentinel_) {
101         // Mapping already exists.
102         continue;
103       }
104       // Copy the node.
105       inputs.clear();
106       for (Node* input : orig->inputs()) inputs.push_back(copies_[input->id()]);
107       copy = target_graph_->NewNode(orig->op(), orig->InputCount(),
108                                     inputs.empty() ? nullptr : &inputs[0]);
109       copies_[orig->id()] = copy;
110     }
111     // For missing inputs.
112     for (Node* orig : all.live) {
113       Node* copy = copies_[orig->id()];
114       for (int i = 0; i < copy->InputCount(); ++i) {
115         Node* input = copy->InputAt(i);
116         if (input == sentinel_) {
117           copy->ReplaceInput(i, GetCopy(orig->InputAt(i)));
118         }
119       }
120     }
121   }
122 
copies() const123   const NodeVector& copies() const { return copies_; }
124 
125  private:
126   Operator const sentinel_op_;
127   Node* const sentinel_;
128   NodeVector copies_;
129   Graph* const source_graph_;
130   Graph* const target_graph_;
131   Zone* const temp_zone_;
132 };
133 
134 
InlineCall(Node * call,Node * new_target,Node * context,Node * frame_state,Node * start,Node * end)135 Reduction JSInliner::InlineCall(Node* call, Node* new_target, Node* context,
136                                 Node* frame_state, Node* start, Node* end) {
137   // The scheduler is smart enough to place our code; we just ensure {control}
138   // becomes the control input of the start of the inlinee, and {effect} becomes
139   // the effect input of the start of the inlinee.
140   Node* control = NodeProperties::GetControlInput(call);
141   Node* effect = NodeProperties::GetEffectInput(call);
142 
143   int const inlinee_new_target_index =
144       static_cast<int>(start->op()->ValueOutputCount()) - 3;
145   int const inlinee_arity_index =
146       static_cast<int>(start->op()->ValueOutputCount()) - 2;
147   int const inlinee_context_index =
148       static_cast<int>(start->op()->ValueOutputCount()) - 1;
149 
150   // {inliner_inputs} counts JSFunction, receiver, arguments, but not
151   // new target value, argument count, context, effect or control.
152   int inliner_inputs = call->op()->ValueInputCount();
153   // Iterate over all uses of the start node.
154   for (Edge edge : start->use_edges()) {
155     Node* use = edge.from();
156     switch (use->opcode()) {
157       case IrOpcode::kParameter: {
158         int index = 1 + ParameterIndexOf(use->op());
159         DCHECK_LE(index, inlinee_context_index);
160         if (index < inliner_inputs && index < inlinee_new_target_index) {
161           // There is an input from the call, and the index is a value
162           // projection but not the context, so rewire the input.
163           Replace(use, call->InputAt(index));
164         } else if (index == inlinee_new_target_index) {
165           // The projection is requesting the new target value.
166           Replace(use, new_target);
167         } else if (index == inlinee_arity_index) {
168           // The projection is requesting the number of arguments.
169           Replace(use, jsgraph_->Int32Constant(inliner_inputs - 2));
170         } else if (index == inlinee_context_index) {
171           // The projection is requesting the inlinee function context.
172           Replace(use, context);
173         } else {
174           // Call has fewer arguments than required, fill with undefined.
175           Replace(use, jsgraph_->UndefinedConstant());
176         }
177         break;
178       }
179       default:
180         if (NodeProperties::IsEffectEdge(edge)) {
181           edge.UpdateTo(effect);
182         } else if (NodeProperties::IsControlEdge(edge)) {
183           edge.UpdateTo(control);
184         } else if (NodeProperties::IsFrameStateEdge(edge)) {
185           edge.UpdateTo(frame_state);
186         } else {
187           UNREACHABLE();
188         }
189         break;
190     }
191   }
192 
193   NodeVector values(local_zone_);
194   NodeVector effects(local_zone_);
195   NodeVector controls(local_zone_);
196   for (Node* const input : end->inputs()) {
197     switch (input->opcode()) {
198       case IrOpcode::kReturn:
199         values.push_back(NodeProperties::GetValueInput(input, 0));
200         effects.push_back(NodeProperties::GetEffectInput(input));
201         controls.push_back(NodeProperties::GetControlInput(input));
202         break;
203       case IrOpcode::kDeoptimize:
204       case IrOpcode::kTerminate:
205       case IrOpcode::kThrow:
206         NodeProperties::MergeControlToEnd(jsgraph_->graph(), jsgraph_->common(),
207                                           input);
208         break;
209       default:
210         UNREACHABLE();
211         break;
212     }
213   }
214   DCHECK_EQ(values.size(), effects.size());
215   DCHECK_EQ(values.size(), controls.size());
216 
217   // Depending on whether the inlinee produces a value, we either replace value
218   // uses with said value or kill value uses if no value can be returned.
219   if (values.size() > 0) {
220     int const input_count = static_cast<int>(controls.size());
221     Node* control_output = jsgraph_->graph()->NewNode(
222         jsgraph_->common()->Merge(input_count), input_count, &controls.front());
223     values.push_back(control_output);
224     effects.push_back(control_output);
225     Node* value_output = jsgraph_->graph()->NewNode(
226         jsgraph_->common()->Phi(MachineRepresentation::kTagged, input_count),
227         static_cast<int>(values.size()), &values.front());
228     Node* effect_output = jsgraph_->graph()->NewNode(
229         jsgraph_->common()->EffectPhi(input_count),
230         static_cast<int>(effects.size()), &effects.front());
231     ReplaceWithValue(call, value_output, effect_output, control_output);
232     return Changed(value_output);
233   } else {
234     ReplaceWithValue(call, call, call, jsgraph_->Dead());
235     return Changed(call);
236   }
237 }
238 
239 
CreateArtificialFrameState(Node * node,Node * outer_frame_state,int parameter_count,FrameStateType frame_state_type,Handle<SharedFunctionInfo> shared)240 Node* JSInliner::CreateArtificialFrameState(Node* node, Node* outer_frame_state,
241                                             int parameter_count,
242                                             FrameStateType frame_state_type,
243                                             Handle<SharedFunctionInfo> shared) {
244   const FrameStateFunctionInfo* state_info =
245       jsgraph_->common()->CreateFrameStateFunctionInfo(
246           frame_state_type, parameter_count + 1, 0, shared,
247           CALL_MAINTAINS_NATIVE_CONTEXT);
248 
249   const Operator* op = jsgraph_->common()->FrameState(
250       BailoutId(-1), OutputFrameStateCombine::Ignore(), state_info);
251   const Operator* op0 = jsgraph_->common()->StateValues(0);
252   Node* node0 = jsgraph_->graph()->NewNode(op0);
253   NodeVector params(local_zone_);
254   for (int parameter = 0; parameter < parameter_count + 1; ++parameter) {
255     params.push_back(node->InputAt(1 + parameter));
256   }
257   const Operator* op_param =
258       jsgraph_->common()->StateValues(static_cast<int>(params.size()));
259   Node* params_node = jsgraph_->graph()->NewNode(
260       op_param, static_cast<int>(params.size()), &params.front());
261   return jsgraph_->graph()->NewNode(op, params_node, node0, node0,
262                                     jsgraph_->UndefinedConstant(),
263                                     node->InputAt(0), outer_frame_state);
264 }
265 
266 
267 namespace {
268 
269 // TODO(mstarzinger,verwaest): Move this predicate onto SharedFunctionInfo?
NeedsImplicitReceiver(Handle<JSFunction> function,Isolate * isolate)270 bool NeedsImplicitReceiver(Handle<JSFunction> function, Isolate* isolate) {
271   Code* construct_stub = function->shared()->construct_stub();
272   return construct_stub != *isolate->builtins()->JSBuiltinsConstructStub() &&
273          construct_stub != *isolate->builtins()->ConstructedNonConstructable();
274 }
275 
276 }  // namespace
277 
278 
Reduce(Node * node)279 Reduction JSInliner::Reduce(Node* node) {
280   if (!IrOpcode::IsInlineeOpcode(node->opcode())) return NoChange();
281 
282   // This reducer can handle both normal function calls as well a constructor
283   // calls whenever the target is a constant function object, as follows:
284   //  - JSCallFunction(target:constant, receiver, args...)
285   //  - JSCallConstruct(target:constant, args..., new.target)
286   HeapObjectMatcher match(node->InputAt(0));
287   if (!match.HasValue() || !match.Value()->IsJSFunction()) return NoChange();
288   Handle<JSFunction> function = Handle<JSFunction>::cast(match.Value());
289 
290   return ReduceJSCall(node, function);
291 }
292 
293 
ReduceJSCall(Node * node,Handle<JSFunction> function)294 Reduction JSInliner::ReduceJSCall(Node* node, Handle<JSFunction> function) {
295   DCHECK(IrOpcode::IsInlineeOpcode(node->opcode()));
296   JSCallAccessor call(node);
297 
298   // Function must be inlineable.
299   if (!function->shared()->IsInlineable()) {
300     TRACE("Not inlining %s into %s because callee is not inlineable\n",
301           function->shared()->DebugName()->ToCString().get(),
302           info_->shared_info()->DebugName()->ToCString().get());
303     return NoChange();
304   }
305 
306   // Constructor must be constructable.
307   if (node->opcode() == IrOpcode::kJSCallConstruct &&
308       !function->IsConstructor()) {
309     TRACE("Not inlining %s into %s because constructor is not constructable.\n",
310           function->shared()->DebugName()->ToCString().get(),
311           info_->shared_info()->DebugName()->ToCString().get());
312     return NoChange();
313   }
314 
315   // Class constructors are callable, but [[Call]] will raise an exception.
316   // See ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList ).
317   if (node->opcode() == IrOpcode::kJSCallFunction &&
318       IsClassConstructor(function->shared()->kind())) {
319     TRACE("Not inlining %s into %s because callee is a class constructor.\n",
320           function->shared()->DebugName()->ToCString().get(),
321           info_->shared_info()->DebugName()->ToCString().get());
322     return NoChange();
323   }
324 
325   // Function contains break points.
326   if (function->shared()->HasDebugInfo()) {
327     TRACE("Not inlining %s into %s because callee may contain break points\n",
328           function->shared()->DebugName()->ToCString().get(),
329           info_->shared_info()->DebugName()->ToCString().get());
330     return NoChange();
331   }
332 
333   // Disallow cross native-context inlining for now. This means that all parts
334   // of the resulting code will operate on the same global object.
335   // This also prevents cross context leaks for asm.js code, where we could
336   // inline functions from a different context and hold on to that context (and
337   // closure) from the code object.
338   // TODO(turbofan): We might want to revisit this restriction later when we
339   // have a need for this, and we know how to model different native contexts
340   // in the same graph in a compositional way.
341   if (function->context()->native_context() !=
342       info_->context()->native_context()) {
343     TRACE("Not inlining %s into %s because of different native contexts\n",
344           function->shared()->DebugName()->ToCString().get(),
345           info_->shared_info()->DebugName()->ToCString().get());
346     return NoChange();
347   }
348 
349   // TODO(turbofan): TranslatedState::GetAdaptedArguments() currently relies on
350   // not inlining recursive functions. We might want to relax that at some
351   // point.
352   for (Node* frame_state = call.frame_state_after();
353        frame_state->opcode() == IrOpcode::kFrameState;
354        frame_state = frame_state->InputAt(kFrameStateOuterStateInput)) {
355     FrameStateInfo const& info = OpParameter<FrameStateInfo>(frame_state);
356     Handle<SharedFunctionInfo> shared_info;
357     if (info.shared_info().ToHandle(&shared_info) &&
358         *shared_info == function->shared()) {
359       TRACE("Not inlining %s into %s because call is recursive\n",
360             function->shared()->DebugName()->ToCString().get(),
361             info_->shared_info()->DebugName()->ToCString().get());
362       return NoChange();
363     }
364   }
365 
366   // TODO(turbofan): Inlining into a try-block is not yet supported.
367   if (NodeProperties::IsExceptionalCall(node)) {
368     TRACE("Not inlining %s into %s because of surrounding try-block\n",
369           function->shared()->DebugName()->ToCString().get(),
370           info_->shared_info()->DebugName()->ToCString().get());
371     return NoChange();
372   }
373 
374   Zone zone;
375   ParseInfo parse_info(&zone, function);
376   CompilationInfo info(&parse_info);
377   if (info_->is_deoptimization_enabled()) {
378     info.MarkAsDeoptimizationEnabled();
379   }
380 
381   if (!Compiler::ParseAndAnalyze(info.parse_info())) {
382     TRACE("Not inlining %s into %s because parsing failed\n",
383           function->shared()->DebugName()->ToCString().get(),
384           info_->shared_info()->DebugName()->ToCString().get());
385     if (info_->isolate()->has_pending_exception()) {
386       info_->isolate()->clear_pending_exception();
387     }
388     return NoChange();
389   }
390 
391   // In strong mode, in case of too few arguments we need to throw a TypeError
392   // so we must not inline this call.
393   int parameter_count = info.literal()->parameter_count();
394   if (is_strong(info.language_mode()) &&
395       call.formal_arguments() < parameter_count) {
396     TRACE("Not inlining %s into %s because too few arguments for strong mode\n",
397           function->shared()->DebugName()->ToCString().get(),
398           info_->shared_info()->DebugName()->ToCString().get());
399     return NoChange();
400   }
401 
402   if (!Compiler::EnsureDeoptimizationSupport(&info)) {
403     TRACE("Not inlining %s into %s because deoptimization support failed\n",
404           function->shared()->DebugName()->ToCString().get(),
405           info_->shared_info()->DebugName()->ToCString().get());
406     return NoChange();
407   }
408   // Remember that we inlined this function. This needs to be called right
409   // after we ensure deoptimization support so that the code flusher
410   // does not remove the code with the deoptimization support.
411   info_->AddInlinedFunction(info.shared_info());
412 
413   // ----------------------------------------------------------------
414   // After this point, we've made a decision to inline this function.
415   // We shall not bailout from inlining if we got here.
416 
417   TRACE("Inlining %s into %s\n",
418         function->shared()->DebugName()->ToCString().get(),
419         info_->shared_info()->DebugName()->ToCString().get());
420 
421   // TODO(mstarzinger): We could use the temporary zone for the graph because
422   // nodes are copied. This however leads to Zone-Types being allocated in the
423   // wrong zone and makes the engine explode at high speeds. Explosion bad!
424   Graph graph(jsgraph_->zone());
425   JSGraph jsgraph(info.isolate(), &graph, jsgraph_->common(),
426                   jsgraph_->javascript(), jsgraph_->simplified(),
427                   jsgraph_->machine());
428   AstGraphBuilder graph_builder(local_zone_, &info, &jsgraph);
429   graph_builder.CreateGraph(false);
430 
431   CopyVisitor visitor(&graph, jsgraph_->graph(), &zone);
432   visitor.CopyGraph();
433 
434   Node* start = visitor.GetCopy(graph.start());
435   Node* end = visitor.GetCopy(graph.end());
436   Node* frame_state = call.frame_state_after();
437   Node* new_target = jsgraph_->UndefinedConstant();
438 
439   // Insert nodes around the call that model the behavior required for a
440   // constructor dispatch (allocate implicit receiver and check return value).
441   // This models the behavior usually accomplished by our {JSConstructStub}.
442   // Note that the context has to be the callers context (input to call node).
443   Node* receiver = jsgraph_->UndefinedConstant();  // Implicit receiver.
444   if (node->opcode() == IrOpcode::kJSCallConstruct &&
445       NeedsImplicitReceiver(function, info_->isolate())) {
446     Node* effect = NodeProperties::GetEffectInput(node);
447     Node* context = NodeProperties::GetContextInput(node);
448     Node* create = jsgraph_->graph()->NewNode(
449         jsgraph_->javascript()->Create(), call.target(), call.new_target(),
450         context, call.frame_state_before(), effect);
451     NodeProperties::ReplaceEffectInput(node, create);
452     // Insert a check of the return value to determine whether the return value
453     // or the implicit receiver should be selected as a result of the call.
454     Node* check = jsgraph_->graph()->NewNode(
455         jsgraph_->javascript()->CallRuntime(Runtime::kInlineIsJSReceiver, 1),
456         node, context, node, start);
457     Node* select = jsgraph_->graph()->NewNode(
458         jsgraph_->common()->Select(MachineRepresentation::kTagged), check, node,
459         create);
460     NodeProperties::ReplaceUses(node, select, check, node, node);
461     NodeProperties::ReplaceValueInput(select, node, 1);
462     NodeProperties::ReplaceValueInput(check, node, 0);
463     NodeProperties::ReplaceEffectInput(check, node);
464     receiver = create;  // The implicit receiver.
465   }
466 
467   // Swizzle the inputs of the {JSCallConstruct} node to look like inputs to a
468   // normal {JSCallFunction} node so that the rest of the inlining machinery
469   // behaves as if we were dealing with a regular function invocation.
470   if (node->opcode() == IrOpcode::kJSCallConstruct) {
471     new_target = call.new_target();  // Retrieve new target value input.
472     node->RemoveInput(call.formal_arguments() + 1);  // Drop new target.
473     node->InsertInput(jsgraph_->graph()->zone(), 1, receiver);
474     // Insert a construct stub frame into the chain of frame states. This will
475     // reconstruct the proper frame when deoptimizing within the constructor.
476     frame_state = CreateArtificialFrameState(
477         node, frame_state, call.formal_arguments(),
478         FrameStateType::kConstructStub, info.shared_info());
479   }
480 
481   // The inlinee specializes to the context from the JSFunction object.
482   // TODO(turbofan): We might want to load the context from the JSFunction at
483   // runtime in case we only know the SharedFunctionInfo once we have dynamic
484   // type feedback in the compiler.
485   Node* context = jsgraph_->Constant(handle(function->context()));
486 
487   // Insert a JSConvertReceiver node for sloppy callees. Note that the context
488   // passed into this node has to be the callees context (loaded above). Note
489   // that the frame state passed to the JSConvertReceiver must be the frame
490   // state _before_ the call; it is not necessary to fiddle with the receiver
491   // in that frame state tho, as the conversion of the receiver can be repeated
492   // any number of times, it's not observable.
493   if (node->opcode() == IrOpcode::kJSCallFunction &&
494       is_sloppy(info.language_mode()) && !function->shared()->native()) {
495     const CallFunctionParameters& p = CallFunctionParametersOf(node->op());
496     Node* effect = NodeProperties::GetEffectInput(node);
497     Node* convert = jsgraph_->graph()->NewNode(
498         jsgraph_->javascript()->ConvertReceiver(p.convert_mode()),
499         call.receiver(), context, call.frame_state_before(), effect, start);
500     NodeProperties::ReplaceValueInput(node, convert, 1);
501     NodeProperties::ReplaceEffectInput(node, convert);
502   }
503 
504   // Insert argument adaptor frame if required. The callees formal parameter
505   // count (i.e. value outputs of start node minus target, receiver, new target,
506   // arguments count and context) have to match the number of arguments passed
507   // to the call.
508   DCHECK_EQ(parameter_count, start->op()->ValueOutputCount() - 5);
509   if (call.formal_arguments() != parameter_count) {
510     frame_state = CreateArtificialFrameState(
511         node, frame_state, call.formal_arguments(),
512         FrameStateType::kArgumentsAdaptor, info.shared_info());
513   }
514 
515   return InlineCall(node, new_target, context, frame_state, start, end);
516 }
517 
518 }  // namespace compiler
519 }  // namespace internal
520 }  // namespace v8
521