Line data Source code
1 : // Copyright 2013 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/scheduler.h"
6 :
7 : #include <iomanip>
8 :
9 : #include "src/base/adapters.h"
10 : #include "src/bit-vector.h"
11 : #include "src/compiler/common-operator.h"
12 : #include "src/compiler/control-equivalence.h"
13 : #include "src/compiler/graph.h"
14 : #include "src/compiler/node-marker.h"
15 : #include "src/compiler/node-properties.h"
16 : #include "src/compiler/node.h"
17 : #include "src/zone/zone-containers.h"
18 :
19 : namespace v8 {
20 : namespace internal {
21 : namespace compiler {
22 :
23 : #define TRACE(...) \
24 : do { \
25 : if (FLAG_trace_turbo_scheduler) PrintF(__VA_ARGS__); \
26 : } while (false)
27 :
28 2741186 : Scheduler::Scheduler(Zone* zone, Graph* graph, Schedule* schedule, Flags flags,
29 : size_t node_count_hint)
30 : : zone_(zone),
31 : graph_(graph),
32 : schedule_(schedule),
33 : flags_(flags),
34 : scheduled_nodes_(zone),
35 : schedule_root_nodes_(zone),
36 : schedule_queue_(zone),
37 5482372 : node_data_(zone) {
38 2742871 : node_data_.reserve(node_count_hint);
39 5483062 : node_data_.resize(graph->NodeCount(), DefaultSchedulerData());
40 2741102 : }
41 :
42 2740812 : Schedule* Scheduler::ComputeSchedule(Zone* zone, Graph* graph, Flags flags) {
43 : Zone* schedule_zone =
44 2740812 : (flags & Scheduler::kTempSchedule) ? zone : graph->zone();
45 :
46 : // Reserve 10% more space for nodes if node splitting is enabled to try to
47 : // avoid resizing the vector since that would triple its zone memory usage.
48 2740812 : float node_hint_multiplier = (flags & Scheduler::kSplitNodes) ? 1.1 : 1;
49 2740812 : size_t node_count_hint = node_hint_multiplier * graph->NodeCount();
50 :
51 : Schedule* schedule =
52 2741107 : new (schedule_zone) Schedule(schedule_zone, node_count_hint);
53 2742012 : Scheduler scheduler(zone, graph, schedule, flags, node_count_hint);
54 :
55 2741134 : scheduler.BuildCFG();
56 2741361 : scheduler.ComputeSpecialRPONumbering();
57 2742177 : scheduler.GenerateImmediateDominatorTree();
58 :
59 2741820 : scheduler.PrepareUses();
60 2742986 : scheduler.ScheduleEarly();
61 2742899 : scheduler.ScheduleLate();
62 :
63 2742730 : scheduler.SealFinalSchedule();
64 :
65 2742920 : return schedule;
66 : }
67 :
68 :
69 : Scheduler::SchedulerData Scheduler::DefaultSchedulerData() {
70 : SchedulerData def = {schedule_->start(), 0, kUnknown};
71 : return def;
72 : }
73 :
74 :
75 : Scheduler::SchedulerData* Scheduler::GetData(Node* node) {
76 2612890754 : return &node_data_[node->id()];
77 : }
78 :
79 140070919 : Scheduler::Placement Scheduler::InitializePlacement(Node* node) {
80 : SchedulerData* data = GetData(node);
81 140070919 : if (data->placement_ == kFixed) {
82 : // Nothing to do for control nodes that have been already fixed in
83 : // the schedule.
84 : return data->placement_;
85 : }
86 : DCHECK_EQ(kUnknown, data->placement_);
87 : switch (node->opcode()) {
88 : case IrOpcode::kParameter:
89 : case IrOpcode::kOsrValue:
90 : // Parameters and OSR values are always fixed to the start block.
91 6390355 : data->placement_ = kFixed;
92 6390355 : break;
93 : case IrOpcode::kPhi:
94 : case IrOpcode::kEffectPhi: {
95 : // Phis and effect phis are fixed if their control inputs are, whereas
96 : // otherwise they are coupled to a floating control node.
97 5036022 : Placement p = GetPlacement(NodeProperties::GetControlInput(node));
98 5035989 : data->placement_ = (p == kFixed ? kFixed : kCoupled);
99 5035989 : break;
100 : }
101 : #define DEFINE_CONTROL_CASE(V) case IrOpcode::k##V:
102 : CONTROL_OP_LIST(DEFINE_CONTROL_CASE)
103 : #undef DEFINE_CONTROL_CASE
104 : {
105 : // Control nodes that were not control-reachable from end may float.
106 526026 : data->placement_ = kSchedulable;
107 526026 : break;
108 : }
109 : default:
110 98579804 : data->placement_ = kSchedulable;
111 98579804 : break;
112 : }
113 110532174 : return data->placement_;
114 : }
115 :
116 0 : Scheduler::Placement Scheduler::GetPlacement(Node* node) {
117 1978248933 : return GetData(node)->placement_;
118 : }
119 :
120 0 : bool Scheduler::IsLive(Node* node) { return GetPlacement(node) != kUnknown; }
121 :
122 131044701 : void Scheduler::UpdatePlacement(Node* node, Placement placement) {
123 : SchedulerData* data = GetData(node);
124 131044701 : if (data->placement_ == kUnknown) {
125 : // We only update control nodes from {kUnknown} to {kFixed}. Ideally, we
126 : // should check that {node} is a control node (including exceptional calls),
127 : // but that is expensive.
128 : DCHECK_EQ(Scheduler::kFixed, placement);
129 29543113 : data->placement_ = placement;
130 29543113 : return;
131 : }
132 :
133 101501588 : switch (node->opcode()) {
134 : case IrOpcode::kParameter:
135 : // Parameters are fixed once and for all.
136 0 : UNREACHABLE();
137 : break;
138 : case IrOpcode::kPhi:
139 : case IrOpcode::kEffectPhi: {
140 : // Phis and effect phis are coupled to their respective blocks.
141 : DCHECK_EQ(Scheduler::kCoupled, data->placement_);
142 : DCHECK_EQ(Scheduler::kFixed, placement);
143 39913 : Node* control = NodeProperties::GetControlInput(node);
144 39914 : BasicBlock* block = schedule_->block(control);
145 39914 : schedule_->AddNode(block, node);
146 39914 : break;
147 : }
148 : #define DEFINE_CONTROL_CASE(V) case IrOpcode::k##V:
149 : CONTROL_OP_LIST(DEFINE_CONTROL_CASE)
150 : #undef DEFINE_CONTROL_CASE
151 : {
152 : // Control nodes force coupled uses to be placed.
153 2315848 : for (auto use : node->uses()) {
154 1789640 : if (GetPlacement(use) == Scheduler::kCoupled) {
155 : DCHECK_EQ(node, NodeProperties::GetControlInput(use));
156 39913 : UpdatePlacement(use, placement);
157 : }
158 : }
159 : break;
160 : }
161 : default:
162 : DCHECK_EQ(Scheduler::kSchedulable, data->placement_);
163 : DCHECK_EQ(Scheduler::kScheduled, placement);
164 : break;
165 : }
166 : // Reduce the use count of the node's inputs to potentially make them
167 : // schedulable. If all the uses of a node have been scheduled, then the node
168 : // itself can be scheduled.
169 353100275 : for (Edge const edge : node->input_edges()) {
170 251597797 : DecrementUnscheduledUseCount(edge.to(), edge.index(), edge.from());
171 : }
172 101502478 : data->placement_ = placement;
173 : }
174 :
175 :
176 : bool Scheduler::IsCoupledControlEdge(Node* node, int index) {
177 503500365 : return GetPlacement(node) == kCoupled &&
178 : NodeProperties::FirstControlIndex(node) == index;
179 : }
180 :
181 :
182 251590233 : void Scheduler::IncrementUnscheduledUseCount(Node* node, int index,
183 : Node* from) {
184 : // Make sure that control edges from coupled nodes are not counted.
185 251619852 : if (IsCoupledControlEdge(from, index)) return;
186 :
187 : // Tracking use counts for fixed nodes is useless.
188 251579986 : if (GetPlacement(node) == kFixed) return;
189 :
190 : // Use count for coupled nodes is summed up on their control.
191 189296498 : if (GetPlacement(node) == kCoupled) {
192 29619 : Node* control = NodeProperties::GetControlInput(node);
193 29619 : return IncrementUnscheduledUseCount(control, index, from);
194 : }
195 :
196 189266879 : ++(GetData(node)->unscheduled_count_);
197 189266879 : if (FLAG_trace_turbo_scheduler) {
198 0 : TRACE(" Use count of #%d:%s (used by #%d:%s)++ = %d\n", node->id(),
199 : node->op()->mnemonic(), from->id(), from->op()->mnemonic(),
200 : GetData(node)->unscheduled_count_);
201 : }
202 : }
203 :
204 :
205 251627182 : void Scheduler::DecrementUnscheduledUseCount(Node* node, int index,
206 : Node* from) {
207 : // Make sure that control edges from coupled nodes are not counted.
208 251627182 : if (IsCoupledControlEdge(from, index)) return;
209 :
210 : // Tracking use counts for fixed nodes is useless.
211 503178144 : if (GetPlacement(node) == kFixed) return;
212 :
213 : // Use count for coupled nodes is summed up on their control.
214 189287074 : if (GetPlacement(node) == kCoupled) {
215 29618 : Node* control = NodeProperties::GetControlInput(node);
216 29618 : return DecrementUnscheduledUseCount(control, index, from);
217 : }
218 :
219 : DCHECK_LT(0, GetData(node)->unscheduled_count_);
220 189257456 : --(GetData(node)->unscheduled_count_);
221 189257456 : if (FLAG_trace_turbo_scheduler) {
222 0 : TRACE(" Use count of #%d:%s (used by #%d:%s)-- = %d\n", node->id(),
223 : node->op()->mnemonic(), from->id(), from->op()->mnemonic(),
224 : GetData(node)->unscheduled_count_);
225 : }
226 378520082 : if (GetData(node)->unscheduled_count_ == 0) {
227 83832469 : TRACE(" newly eligible #%d:%s\n", node->id(), node->op()->mnemonic());
228 : schedule_queue_.push(node);
229 : }
230 : }
231 :
232 :
233 : // -----------------------------------------------------------------------------
234 : // Phase 1: Build control-flow graph.
235 :
236 :
237 : // Internal class to build a control flow graph (i.e the basic blocks and edges
238 : // between them within a Schedule) from the node graph. Visits control edges of
239 : // the graph backwards from an end node in order to find the connected control
240 : // subgraph, needed for scheduling.
241 : class CFGBuilder : public ZoneObject {
242 : public:
243 2741063 : CFGBuilder(Zone* zone, Scheduler* scheduler)
244 : : zone_(zone),
245 : scheduler_(scheduler),
246 2741063 : schedule_(scheduler->schedule_),
247 : queued_(scheduler->graph_, 2),
248 : queue_(zone),
249 : control_(zone),
250 : component_entry_(nullptr),
251 : component_start_(nullptr),
252 10966225 : component_end_(nullptr) {}
253 :
254 : // Run the control flow graph construction algorithm by walking the graph
255 : // backwards from end through control edges, building and connecting the
256 : // basic blocks for control nodes.
257 2742920 : void Run() {
258 : ResetDataStructures();
259 2742920 : Queue(scheduler_->graph_->end());
260 :
261 38987094 : while (!queue_.empty()) { // Breadth-first backwards traversal.
262 36243722 : Node* node = queue_.front();
263 : queue_.pop();
264 36243805 : int max = NodeProperties::PastControlIndex(node);
265 115210355 : for (int i = NodeProperties::FirstControlIndex(node); i < max; i++) {
266 39482255 : Queue(node->InputAt(i));
267 : }
268 : }
269 :
270 38986371 : for (NodeVector::iterator i = control_.begin(); i != control_.end(); ++i) {
271 36244613 : ConnectBlocks(*i); // Connect block to its predecessor/successors.
272 : }
273 2741758 : }
274 :
275 : // Run the control flow graph construction for a minimal control-connected
276 : // component ending in {exit} and merge that component into an existing
277 : // control flow graph at the bottom of {block}.
278 39504 : void Run(BasicBlock* block, Node* exit) {
279 : ResetDataStructures();
280 39504 : Queue(exit);
281 :
282 39504 : component_entry_ = nullptr;
283 39504 : component_start_ = block;
284 39504 : component_end_ = schedule_->block(exit);
285 39504 : scheduler_->equivalence_->Run(exit);
286 199157 : while (!queue_.empty()) { // Breadth-first backwards traversal.
287 159653 : Node* node = queue_.front();
288 : queue_.pop();
289 :
290 : // Use control dependence equivalence to find a canonical single-entry
291 : // single-exit region that makes up a minimal component to be scheduled.
292 159653 : if (IsSingleEntrySingleExitRegion(node, exit)) {
293 39504 : TRACE("Found SESE at #%d:%s\n", node->id(), node->op()->mnemonic());
294 : DCHECK(!component_entry_);
295 39504 : component_entry_ = node;
296 39504 : continue;
297 : }
298 :
299 120149 : int max = NodeProperties::PastControlIndex(node);
300 440272 : for (int i = NodeProperties::FirstControlIndex(node); i < max; i++) {
301 160062 : Queue(node->InputAt(i));
302 : }
303 : }
304 : DCHECK(component_entry_);
305 :
306 199156 : for (NodeVector::iterator i = control_.begin(); i != control_.end(); ++i) {
307 159652 : ConnectBlocks(*i); // Connect block to its predecessor/successors.
308 : }
309 39504 : }
310 :
311 : private:
312 : friend class ScheduleLateNodeVisitor;
313 : friend class Scheduler;
314 :
315 : void FixNode(BasicBlock* block, Node* node) {
316 20694934 : schedule_->AddNode(block, node);
317 20694255 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
318 : }
319 :
320 42423520 : void Queue(Node* node) {
321 : // Mark the connected control nodes as they are queued.
322 84847040 : if (!queued_.Get(node)) {
323 36403798 : BuildBlocks(node);
324 : queue_.push(node);
325 36402993 : queued_.Set(node, true);
326 36402993 : control_.push_back(node);
327 : }
328 42423069 : }
329 :
330 36403698 : void BuildBlocks(Node* node) {
331 36403698 : switch (node->opcode()) {
332 : case IrOpcode::kEnd:
333 2732277 : FixNode(schedule_->end(), node);
334 : break;
335 : case IrOpcode::kStart:
336 2742991 : FixNode(schedule_->start(), node);
337 : break;
338 : case IrOpcode::kLoop:
339 : case IrOpcode::kMerge:
340 3655670 : BuildBlockForNode(node);
341 3655656 : break;
342 : case IrOpcode::kTerminate: {
343 : // Put Terminate in the loop to which it refers.
344 179016 : Node* loop = NodeProperties::GetControlInput(node);
345 179016 : BasicBlock* block = BuildBlockForNode(loop);
346 : FixNode(block, node);
347 : break;
348 : }
349 : case IrOpcode::kBranch:
350 : case IrOpcode::kSwitch:
351 5140405 : BuildBlocksForSuccessors(node);
352 5140443 : break;
353 : #define BUILD_BLOCK_JS_CASE(Name) case IrOpcode::k##Name:
354 : JS_OP_LIST(BUILD_BLOCK_JS_CASE)
355 : // JS opcodes are just like calls => fall through.
356 : #undef BUILD_BLOCK_JS_CASE
357 : case IrOpcode::kCall:
358 : case IrOpcode::kCallWithCallerSavedRegisters:
359 6736576 : if (NodeProperties::IsExceptionalCall(node)) {
360 403114 : BuildBlocksForSuccessors(node);
361 : }
362 : break;
363 : default:
364 : break;
365 : }
366 36402655 : }
367 :
368 36403393 : void ConnectBlocks(Node* node) {
369 36403393 : switch (node->opcode()) {
370 : case IrOpcode::kLoop:
371 : case IrOpcode::kMerge:
372 3655651 : ConnectMerge(node);
373 3655706 : break;
374 : case IrOpcode::kBranch:
375 5109308 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
376 5109314 : ConnectBranch(node);
377 5109281 : break;
378 : case IrOpcode::kSwitch:
379 31131 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
380 31131 : ConnectSwitch(node);
381 31130 : break;
382 : case IrOpcode::kDeoptimize:
383 85411 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
384 85411 : ConnectDeoptimize(node);
385 85411 : break;
386 : case IrOpcode::kTailCall:
387 63353 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
388 63353 : ConnectTailCall(node);
389 63353 : break;
390 : case IrOpcode::kReturn:
391 3045800 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
392 3045846 : ConnectReturn(node);
393 3045265 : break;
394 : case IrOpcode::kThrow:
395 271601 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
396 271601 : ConnectThrow(node);
397 271601 : break;
398 : #define CONNECT_BLOCK_JS_CASE(Name) case IrOpcode::k##Name:
399 : JS_OP_LIST(CONNECT_BLOCK_JS_CASE)
400 : // JS opcodes are just like calls => fall through.
401 : #undef CONNECT_BLOCK_JS_CASE
402 : case IrOpcode::kCall:
403 : case IrOpcode::kCallWithCallerSavedRegisters:
404 6736591 : if (NodeProperties::IsExceptionalCall(node)) {
405 403115 : scheduler_->UpdatePlacement(node, Scheduler::kFixed);
406 403115 : ConnectCall(node);
407 : }
408 : break;
409 : default:
410 : break;
411 : }
412 36402858 : }
413 :
414 15219443 : BasicBlock* BuildBlockForNode(Node* node) {
415 15219443 : BasicBlock* block = schedule_->block(node);
416 15219408 : if (block == nullptr) {
417 15040418 : block = schedule_->NewBasicBlock();
418 15040645 : TRACE("Create block id:%d for #%d:%s\n", block->id().ToInt(), node->id(),
419 : node->op()->mnemonic());
420 : FixNode(block, node);
421 : }
422 15219619 : return block;
423 : }
424 :
425 5543509 : void BuildBlocksForSuccessors(Node* node) {
426 5543509 : size_t const successor_cnt = node->op()->ControlOutputCount();
427 5543509 : Node** successors = zone_->NewArray<Node*>(successor_cnt);
428 5543491 : NodeProperties::CollectControlProjections(node, successors, successor_cnt);
429 28313781 : for (size_t index = 0; index < successor_cnt; ++index) {
430 11385062 : BuildBlockForNode(successors[index]);
431 : }
432 5543563 : }
433 :
434 5543440 : void CollectSuccessorBlocks(Node* node, BasicBlock** successor_blocks,
435 : size_t successor_cnt) {
436 : Node** successors = reinterpret_cast<Node**>(successor_blocks);
437 5543440 : NodeProperties::CollectControlProjections(node, successors, successor_cnt);
438 28313889 : for (size_t index = 0; index < successor_cnt; ++index) {
439 11385172 : successor_blocks[index] = schedule_->block(successors[index]);
440 : }
441 5543529 : }
442 :
443 29526281 : BasicBlock* FindPredecessorBlock(Node* node) {
444 : BasicBlock* predecessor_block = nullptr;
445 : while (true) {
446 40534396 : predecessor_block = schedule_->block(node);
447 40534614 : if (predecessor_block != nullptr) break;
448 11008106 : node = NodeProperties::GetControlInput(node);
449 : }
450 29526508 : return predecessor_block;
451 : }
452 :
453 403115 : void ConnectCall(Node* call) {
454 : BasicBlock* successor_blocks[2];
455 403115 : CollectSuccessorBlocks(call, successor_blocks, arraysize(successor_blocks));
456 :
457 : // Consider the exception continuation to be deferred.
458 403114 : successor_blocks[1]->set_deferred(true);
459 :
460 403114 : Node* call_control = NodeProperties::GetControlInput(call);
461 403114 : BasicBlock* call_block = FindPredecessorBlock(call_control);
462 403114 : TraceConnect(call, call_block, successor_blocks[0]);
463 403113 : TraceConnect(call, call_block, successor_blocks[1]);
464 403114 : schedule_->AddCall(call_block, call, successor_blocks[0],
465 403114 : successor_blocks[1]);
466 403114 : }
467 :
468 5109192 : void ConnectBranch(Node* branch) {
469 : BasicBlock* successor_blocks[2];
470 : CollectSuccessorBlocks(branch, successor_blocks,
471 5109192 : arraysize(successor_blocks));
472 :
473 : // Consider branch hints.
474 5109290 : switch (BranchHintOf(branch->op())) {
475 : case BranchHint::kNone:
476 : break;
477 : case BranchHint::kTrue:
478 1668768 : successor_blocks[1]->set_deferred(true);
479 : break;
480 : case BranchHint::kFalse:
481 984285 : successor_blocks[0]->set_deferred(true);
482 : break;
483 : }
484 :
485 5109154 : if (branch == component_entry_) {
486 39502 : TraceConnect(branch, component_start_, successor_blocks[0]);
487 39503 : TraceConnect(branch, component_start_, successor_blocks[1]);
488 39503 : schedule_->InsertBranch(component_start_, component_end_, branch,
489 39503 : successor_blocks[0], successor_blocks[1]);
490 : } else {
491 5069652 : Node* branch_control = NodeProperties::GetControlInput(branch);
492 5069683 : BasicBlock* branch_block = FindPredecessorBlock(branch_control);
493 5069722 : TraceConnect(branch, branch_block, successor_blocks[0]);
494 5069735 : TraceConnect(branch, branch_block, successor_blocks[1]);
495 5069658 : schedule_->AddBranch(branch_block, branch, successor_blocks[0],
496 5069658 : successor_blocks[1]);
497 : }
498 5109283 : }
499 :
500 31127 : void ConnectSwitch(Node* sw) {
501 31127 : size_t const successor_count = sw->op()->ControlOutputCount();
502 : BasicBlock** successor_blocks =
503 31127 : zone_->NewArray<BasicBlock*>(successor_count);
504 31128 : CollectSuccessorBlocks(sw, successor_blocks, successor_count);
505 :
506 31131 : if (sw == component_entry_) {
507 7 : for (size_t index = 0; index < successor_count; ++index) {
508 3 : TraceConnect(sw, component_start_, successor_blocks[index]);
509 : }
510 1 : schedule_->InsertSwitch(component_start_, component_end_, sw,
511 1 : successor_blocks, successor_count);
512 : } else {
513 31130 : Node* switch_control = NodeProperties::GetControlInput(sw);
514 31130 : BasicBlock* switch_block = FindPredecessorBlock(switch_control);
515 751969 : for (size_t index = 0; index < successor_count; ++index) {
516 360419 : TraceConnect(sw, switch_block, successor_blocks[index]);
517 : }
518 31130 : schedule_->AddSwitch(switch_block, sw, successor_blocks, successor_count);
519 : }
520 751964 : for (size_t index = 0; index < successor_count; ++index) {
521 720832 : if (BranchHintOf(successor_blocks[index]->front()->op()) ==
522 : BranchHint::kFalse) {
523 8848 : successor_blocks[index]->set_deferred(true);
524 : }
525 : }
526 31131 : }
527 :
528 3655562 : void ConnectMerge(Node* merge) {
529 : // Don't connect the special merge at the end to its predecessors.
530 3655562 : if (IsFinalMerge(merge)) return;
531 :
532 3655652 : BasicBlock* block = schedule_->block(merge);
533 : DCHECK_NOT_NULL(block);
534 : // For all of the merge's control inputs, add a goto at the end to the
535 : // merge's basic block.
536 12428964 : for (Node* const input : merge->inputs()) {
537 8773301 : BasicBlock* predecessor_block = FindPredecessorBlock(input);
538 8773295 : TraceConnect(merge, predecessor_block, block);
539 8773308 : schedule_->AddGoto(predecessor_block, block);
540 : }
541 : }
542 :
543 63353 : void ConnectTailCall(Node* call) {
544 63353 : Node* call_control = NodeProperties::GetControlInput(call);
545 63353 : BasicBlock* call_block = FindPredecessorBlock(call_control);
546 63353 : TraceConnect(call, call_block, nullptr);
547 63353 : schedule_->AddTailCall(call_block, call);
548 63353 : }
549 :
550 3044436 : void ConnectReturn(Node* ret) {
551 3044436 : Node* return_control = NodeProperties::GetControlInput(ret);
552 3044607 : BasicBlock* return_block = FindPredecessorBlock(return_control);
553 3044593 : TraceConnect(ret, return_block, nullptr);
554 3044647 : schedule_->AddReturn(return_block, ret);
555 3045245 : }
556 :
557 85411 : void ConnectDeoptimize(Node* deopt) {
558 85411 : Node* deoptimize_control = NodeProperties::GetControlInput(deopt);
559 85411 : BasicBlock* deoptimize_block = FindPredecessorBlock(deoptimize_control);
560 85411 : TraceConnect(deopt, deoptimize_block, nullptr);
561 85411 : schedule_->AddDeoptimize(deoptimize_block, deopt);
562 85411 : }
563 :
564 271600 : void ConnectThrow(Node* thr) {
565 271600 : Node* throw_control = NodeProperties::GetControlInput(thr);
566 271600 : BasicBlock* throw_block = FindPredecessorBlock(throw_control);
567 271599 : TraceConnect(thr, throw_block, nullptr);
568 271599 : schedule_->AddThrow(throw_block, thr);
569 271601 : }
570 :
571 23623052 : void TraceConnect(Node* node, BasicBlock* block, BasicBlock* succ) {
572 : DCHECK_NOT_NULL(block);
573 23623052 : if (succ == nullptr) {
574 3464902 : TRACE("Connect #%d:%s, id:%d -> end\n", node->id(),
575 : node->op()->mnemonic(), block->id().ToInt());
576 : } else {
577 20158150 : TRACE("Connect #%d:%s, id:%d -> id:%d\n", node->id(),
578 : node->op()->mnemonic(), block->id().ToInt(), succ->id().ToInt());
579 : }
580 23623052 : }
581 :
582 : bool IsFinalMerge(Node* node) {
583 7132194 : return (node->opcode() == IrOpcode::kMerge &&
584 3476632 : node == scheduler_->graph_->end()->InputAt(0));
585 : }
586 :
587 159653 : bool IsSingleEntrySingleExitRegion(Node* entry, Node* exit) const {
588 159653 : size_t entry_class = scheduler_->equivalence_->ClassOf(entry);
589 159653 : size_t exit_class = scheduler_->equivalence_->ClassOf(exit);
590 159653 : return entry != exit && entry_class == exit_class;
591 : }
592 :
593 : void ResetDataStructures() {
594 : control_.clear();
595 : DCHECK(queue_.empty());
596 : DCHECK(control_.empty());
597 : }
598 :
599 : Zone* zone_;
600 : Scheduler* scheduler_;
601 : Schedule* schedule_;
602 : NodeMarker<bool> queued_; // Mark indicating whether node is queued.
603 : ZoneQueue<Node*> queue_; // Queue used for breadth-first traversal.
604 : NodeVector control_; // List of encountered control nodes.
605 : Node* component_entry_; // Component single-entry node.
606 : BasicBlock* component_start_; // Component single-entry block.
607 : BasicBlock* component_end_; // Component single-exit block.
608 : };
609 :
610 :
611 2740667 : void Scheduler::BuildCFG() {
612 2740667 : TRACE("--- CREATING CFG -------------------------------------------\n");
613 :
614 : // Instantiate a new control equivalence algorithm for the graph.
615 8222951 : equivalence_ = new (zone_) ControlEquivalence(zone_, graph_);
616 :
617 : // Build a control-flow graph for the main control-connected component that
618 : // is being spanned by the graph's start and end nodes.
619 5482932 : control_flow_builder_ = new (zone_) CFGBuilder(zone_, this);
620 2742960 : control_flow_builder_->Run();
621 :
622 : // Initialize per-block data.
623 : // Reserve an extra 10% to avoid resizing vector when fusing floating control.
624 5483464 : scheduled_nodes_.reserve(schedule_->BasicBlockCount() * 1.1);
625 5482278 : scheduled_nodes_.resize(schedule_->BasicBlockCount());
626 2741350 : }
627 :
628 :
629 : // -----------------------------------------------------------------------------
630 : // Phase 2: Compute special RPO and dominator tree.
631 :
632 :
633 : // Compute the special reverse-post-order block ordering, which is essentially
634 : // a RPO of the graph where loop bodies are contiguous. Properties:
635 : // 1. If block A is a predecessor of B, then A appears before B in the order,
636 : // unless B is a loop header and A is in the loop headed at B
637 : // (i.e. A -> B is a backedge).
638 : // => If block A dominates block B, then A appears before B in the order.
639 : // => If block A is a loop header, A appears before all blocks in the loop
640 : // headed at A.
641 : // 2. All loops are contiguous in the order (i.e. no intervening blocks that
642 : // do not belong to the loop.)
643 : // Note a simple RPO traversal satisfies (1) but not (2).
644 248750 : class SpecialRPONumberer : public ZoneObject {
645 : public:
646 2989378 : SpecialRPONumberer(Zone* zone, Schedule* schedule)
647 : : zone_(zone),
648 : schedule_(schedule),
649 : order_(nullptr),
650 : beyond_end_(nullptr),
651 : loops_(zone),
652 : backedges_(zone),
653 : stack_(zone),
654 : previous_block_count_(0),
655 8968211 : empty_(0, zone) {}
656 :
657 : // Computes the special reverse-post-order for the main control flow graph,
658 : // that is for the graph spanned between the schedule's start and end blocks.
659 : void ComputeSpecialRPO() {
660 : DCHECK_EQ(0, schedule_->end()->SuccessorCount());
661 : DCHECK(!order_); // Main order does not exist yet.
662 2989396 : ComputeAndInsertSpecialRPO(schedule_->start(), schedule_->end());
663 : }
664 :
665 : // Computes the special reverse-post-order for a partial control flow graph,
666 : // that is for the graph spanned between the given {entry} and {end} blocks,
667 : // then updates the existing ordering with this new information.
668 : void UpdateSpecialRPO(BasicBlock* entry, BasicBlock* end) {
669 : DCHECK(order_); // Main order to be updated is present.
670 39504 : ComputeAndInsertSpecialRPO(entry, end);
671 : }
672 :
673 : // Serialize the previously computed order as a special reverse-post-order
674 : // numbering for basic blocks into the final schedule.
675 2991058 : void SerializeRPOIntoSchedule() {
676 : int32_t number = 0;
677 30506781 : for (BasicBlock* b = order_; b != nullptr; b = b->rpo_next()) {
678 27514992 : b->set_rpo_number(number++);
679 27515081 : schedule_->rpo_order()->push_back(b);
680 : }
681 2991789 : BeyondEndSentinel()->set_rpo_number(number);
682 2989737 : }
683 :
684 : // Print and verify the special reverse-post-order.
685 : void PrintAndVerifySpecialRPO() {
686 : #if DEBUG
687 : if (FLAG_trace_turbo_scheduler) PrintRPO();
688 : VerifySpecialRPO();
689 : #endif
690 : }
691 :
692 : const ZoneVector<BasicBlock*>& GetOutgoingBlocks(BasicBlock* block) {
693 7432407 : if (HasLoopNumber(block)) {
694 7432435 : LoopInfo const& loop = loops_[GetLoopNumber(block)];
695 7432435 : if (loop.outgoing) return *loop.outgoing;
696 : }
697 59388 : return empty_;
698 : }
699 :
700 : private:
701 : typedef std::pair<BasicBlock*, size_t> Backedge;
702 :
703 : // Numbering for BasicBlock::rpo_number for this block traversal:
704 : static const int kBlockOnStack = -2;
705 : static const int kBlockVisited1 = -3;
706 : static const int kBlockVisited2 = -4;
707 : static const int kBlockUnvisited1 = -1;
708 : static const int kBlockUnvisited2 = kBlockVisited1;
709 :
710 : struct SpecialRPOStackFrame {
711 : BasicBlock* block;
712 : size_t index;
713 : };
714 :
715 : struct LoopInfo {
716 : BasicBlock* header;
717 : ZoneVector<BasicBlock*>* outgoing;
718 : BitVector* members;
719 : LoopInfo* prev;
720 : BasicBlock* end;
721 : BasicBlock* start;
722 :
723 885080 : void AddOutgoing(Zone* zone, BasicBlock* block) {
724 885080 : if (outgoing == nullptr) {
725 : outgoing = new (zone->New(sizeof(ZoneVector<BasicBlock*>)))
726 535160 : ZoneVector<BasicBlock*>(zone);
727 : }
728 885080 : outgoing->push_back(block);
729 885083 : }
730 : };
731 :
732 : int Push(ZoneVector<SpecialRPOStackFrame>& stack, int depth,
733 : BasicBlock* child, int unvisited) {
734 40485720 : if (child->rpo_number() == unvisited) {
735 77821524 : stack[depth].block = child;
736 40485242 : stack[depth].index = 0;
737 40485242 : child->set_rpo_number(kBlockOnStack);
738 37336494 : return depth + 1;
739 : }
740 : return depth;
741 : }
742 :
743 : BasicBlock* PushFront(BasicBlock* head, BasicBlock* block) {
744 : block->set_rpo_next(head);
745 : return block;
746 : }
747 :
748 : static int GetLoopNumber(BasicBlock* block) { return block->loop_number(); }
749 : static void SetLoopNumber(BasicBlock* block, int loop_number) {
750 : return block->set_loop_number(loop_number);
751 : }
752 : static bool HasLoopNumber(BasicBlock* block) {
753 : return block->loop_number() >= 0;
754 : }
755 :
756 : // TODO(mstarzinger): We only need this special sentinel because some tests
757 : // use the schedule's end block in actual control flow (e.g. with end having
758 : // successors). Once this has been cleaned up we can use the end block here.
759 2993803 : BasicBlock* BeyondEndSentinel() {
760 2993803 : if (beyond_end_ == nullptr) {
761 : BasicBlock::Id id = BasicBlock::Id::FromInt(-1);
762 5983025 : beyond_end_ = new (schedule_->zone()) BasicBlock(schedule_->zone(), id);
763 : }
764 2991625 : return beyond_end_;
765 : }
766 :
767 : // Compute special RPO for the control flow graph between {entry} and {end},
768 : // mutating any existing order so that the result is still valid.
769 3028718 : void ComputeAndInsertSpecialRPO(BasicBlock* entry, BasicBlock* end) {
770 : // RPO should not have been serialized for this schedule yet.
771 3028718 : CHECK_EQ(kBlockUnvisited1, schedule_->start()->loop_number());
772 3028718 : CHECK_EQ(kBlockUnvisited1, schedule_->start()->rpo_number());
773 3028718 : CHECK_EQ(0, static_cast<int>(schedule_->rpo_order()->size()));
774 :
775 : // Find correct insertion point within existing order.
776 : BasicBlock* insertion_point = entry->rpo_next();
777 : BasicBlock* order = insertion_point;
778 :
779 : // Perform an iterative RPO traversal using an explicit stack,
780 : // recording backedges that form cycles. O(|B|).
781 : DCHECK_LT(previous_block_count_, schedule_->BasicBlockCount());
782 3028718 : stack_.resize(schedule_->BasicBlockCount() - previous_block_count_);
783 6057678 : previous_block_count_ = schedule_->BasicBlockCount();
784 : int stack_depth = Push(stack_, 0, entry, kBlockUnvisited1);
785 3030551 : int num_loops = static_cast<int>(loops_.size());
786 :
787 62389772 : while (stack_depth > 0) {
788 59358749 : int current = stack_depth - 1;
789 59358749 : SpecialRPOStackFrame* frame = &stack_[current];
790 :
791 115689039 : if (frame->block != end &&
792 56330290 : frame->index < frame->block->SuccessorCount()) {
793 : // Process the next successor.
794 31805173 : BasicBlock* succ = frame->block->SuccessorAt(frame->index++);
795 31805173 : if (succ->rpo_number() == kBlockVisited1) continue;
796 24821211 : if (succ->rpo_number() == kBlockOnStack) {
797 : // The successor is on the stack, so this is a backedge (cycle).
798 597860 : backedges_.push_back(Backedge(frame->block, frame->index - 1));
799 298928 : if (!HasLoopNumber(succ)) {
800 : // Assign a new loop number to the header if it doesn't have one.
801 269811 : SetLoopNumber(succ, num_loops++);
802 : }
803 : } else {
804 : // Push the successor onto the stack.
805 : DCHECK_EQ(kBlockUnvisited1, succ->rpo_number());
806 : stack_depth = Push(stack_, stack_depth, succ, kBlockUnvisited1);
807 : }
808 : } else {
809 : // Finished with all successors; pop the stack and add the block.
810 : order = PushFront(order, frame->block);
811 27553576 : frame->block->set_rpo_number(kBlockVisited1);
812 : stack_depth--;
813 : }
814 : }
815 :
816 : // If no loops were encountered, then the order we computed was correct.
817 3031023 : if (num_loops > static_cast<int>(loops_.size())) {
818 : // Otherwise, compute the loop information from the backedges in order
819 : // to perform a traversal that groups loop bodies together.
820 120060 : ComputeLoopInfo(stack_, num_loops, &backedges_);
821 :
822 : // Initialize the "loop stack". Note the entry could be a loop header.
823 : LoopInfo* loop =
824 120059 : HasLoopNumber(entry) ? &loops_[GetLoopNumber(entry)] : nullptr;
825 : order = insertion_point;
826 :
827 : // Perform an iterative post-order traversal, visiting loop bodies before
828 : // edges that lead out of loops. Visits each block once, but linking loop
829 : // sections together is linear in the loop size, so overall is
830 : // O(|B| + max(loop_depth) * max(|loop|))
831 : stack_depth = Push(stack_, 0, entry, kBlockUnvisited2);
832 30888296 : while (stack_depth > 0) {
833 30768397 : SpecialRPOStackFrame* frame = &stack_[stack_depth - 1];
834 30768397 : BasicBlock* block = frame->block;
835 : BasicBlock* succ = nullptr;
836 :
837 61418657 : if (block != end && frame->index < block->SuccessorCount()) {
838 : // Process the next normal successor.
839 16948714 : succ = block->SuccessorAt(frame->index++);
840 13819683 : } else if (HasLoopNumber(block)) {
841 : // Process additional outgoing edges from the loop header.
842 1154898 : if (block->rpo_number() == kBlockOnStack) {
843 : // Finish the loop body the first time the header is left on the
844 : // stack.
845 : DCHECK(loop != nullptr && loop->header == block);
846 269815 : loop->start = PushFront(order, block);
847 269815 : order = loop->end;
848 269815 : block->set_rpo_number(kBlockVisited2);
849 : // Pop the loop stack and continue visiting outgoing edges within
850 : // the context of the outer loop, if any.
851 269816 : loop = loop->prev;
852 : // We leave the loop header on the stack; the rest of this iteration
853 : // and later iterations will go through its outgoing edges list.
854 : }
855 :
856 : // Use the next outgoing edge if there are any.
857 2309798 : size_t outgoing_index = frame->index - block->SuccessorCount();
858 1154899 : LoopInfo* info = &loops_[GetLoopNumber(block)];
859 : DCHECK(loop != info);
860 2307564 : if (block != entry && info->outgoing != nullptr &&
861 : outgoing_index < info->outgoing->size()) {
862 1770168 : succ = info->outgoing->at(outgoing_index);
863 885084 : frame->index++;
864 : }
865 : }
866 :
867 30768398 : if (succ != nullptr) {
868 : // Process the next successor.
869 17833799 : if (succ->rpo_number() == kBlockOnStack) continue;
870 17534878 : if (succ->rpo_number() == kBlockVisited2) continue;
871 : DCHECK_EQ(kBlockUnvisited2, succ->rpo_number());
872 23433034 : if (loop != nullptr && !loop->members->Contains(succ->id().ToInt())) {
873 : // The successor is not in the current loop or any nested loop.
874 : // Add it to the outgoing edges of this loop and visit it later.
875 885083 : loop->AddOutgoing(zone_, succ);
876 : } else {
877 : // Push the successor onto the stack.
878 : stack_depth = Push(stack_, stack_depth, succ, kBlockUnvisited2);
879 12814536 : if (HasLoopNumber(succ)) {
880 : // Push the inner loop onto the loop stack.
881 : DCHECK(GetLoopNumber(succ) < num_loops);
882 269810 : LoopInfo* next = &loops_[GetLoopNumber(succ)];
883 269810 : next->end = order;
884 269810 : next->prev = loop;
885 : loop = next;
886 : }
887 : }
888 : } else {
889 : // Finished with all successors of the current block.
890 12934599 : if (HasLoopNumber(block)) {
891 : // If we are going to pop a loop header, then add its entire body.
892 269816 : LoopInfo* info = &loops_[GetLoopNumber(block)];
893 269816 : for (BasicBlock* b = info->start; true; b = b->rpo_next()) {
894 5227132 : if (b->rpo_next() == info->end) {
895 : b->set_rpo_next(order);
896 269816 : info->end = order;
897 : break;
898 : }
899 : }
900 269816 : order = info->start;
901 : } else {
902 : // Pop a single node off the stack and add it to the order.
903 : order = PushFront(order, block);
904 12664783 : block->set_rpo_number(kBlockVisited2);
905 : }
906 : stack_depth--;
907 : }
908 : }
909 : }
910 :
911 : // Publish new order the first time.
912 3030862 : if (order_ == nullptr) order_ = order;
913 :
914 : // Compute the correct loop headers and set the correct loop ends.
915 : LoopInfo* current_loop = nullptr;
916 : BasicBlock* current_header = entry->loop_header();
917 : int32_t loop_depth = entry->loop_depth();
918 3030862 : if (entry->IsLoopHeader()) --loop_depth; // Entry might be a loop header.
919 58135240 : for (BasicBlock* b = order; b != insertion_point; b = b->rpo_next()) {
920 : BasicBlock* current = b;
921 :
922 : // Reset BasicBlock::rpo_number again.
923 27552625 : current->set_rpo_number(kBlockUnvisited1);
924 :
925 : // Finish the previous loop(s) if we just exited them.
926 28088088 : while (current_header != nullptr &&
927 : current == current_header->loop_end()) {
928 : DCHECK(current_header->IsLoopHeader());
929 : DCHECK_NOT_NULL(current_loop);
930 267742 : current_loop = current_loop->prev;
931 : current_header =
932 267742 : current_loop == nullptr ? nullptr : current_loop->header;
933 267742 : --loop_depth;
934 : }
935 27552604 : current->set_loop_header(current_header);
936 :
937 : // Push a new loop onto the stack if this loop is a loop header.
938 27553141 : if (HasLoopNumber(current)) {
939 269819 : ++loop_depth;
940 269819 : current_loop = &loops_[GetLoopNumber(current)];
941 269819 : BasicBlock* end = current_loop->end;
942 269819 : current->set_loop_end(end == nullptr ? BeyondEndSentinel() : end);
943 269819 : current_header = current_loop->header;
944 269819 : TRACE("id:%d is a loop header, increment loop depth to %d\n",
945 : current->id().ToInt(), loop_depth);
946 : }
947 :
948 27553141 : current->set_loop_depth(loop_depth);
949 :
950 27552107 : if (current->loop_header() == nullptr) {
951 23562401 : TRACE("id:%d is not in a loop (depth == %d)\n", current->id().ToInt(),
952 : current->loop_depth());
953 : } else {
954 3989706 : TRACE("id:%d has loop header id:%d, (depth == %d)\n",
955 : current->id().ToInt(), current->loop_header()->id().ToInt(),
956 : current->loop_depth());
957 : }
958 : }
959 3030426 : }
960 :
961 : // Computes loop membership from the backedges of the control flow graph.
962 120055 : void ComputeLoopInfo(ZoneVector<SpecialRPOStackFrame>& queue,
963 : size_t num_loops, ZoneVector<Backedge>* backedges) {
964 : // Extend existing loop membership vectors.
965 120056 : for (LoopInfo& loop : loops_) {
966 2 : loop.members->Resize(static_cast<int>(schedule_->BasicBlockCount()),
967 1 : zone_);
968 : }
969 :
970 : // Extend loop information vector.
971 120055 : loops_.resize(num_loops, LoopInfo());
972 :
973 : // Compute loop membership starting from backedges.
974 : // O(max(loop_depth) * max(|loop|)
975 717924 : for (size_t i = 0; i < backedges->size(); i++) {
976 298932 : BasicBlock* member = backedges->at(i).first;
977 298932 : BasicBlock* header = member->SuccessorAt(backedges->at(i).second);
978 298932 : size_t loop_num = GetLoopNumber(header);
979 298932 : if (loops_[loop_num].header == nullptr) {
980 269810 : loops_[loop_num].header = header;
981 : loops_[loop_num].members = new (zone_)
982 1079242 : BitVector(static_cast<int>(schedule_->BasicBlockCount()), zone_);
983 : }
984 :
985 : int queue_length = 0;
986 298933 : if (member != header) {
987 : // As long as the header doesn't have a backedge to itself,
988 : // Push the member onto the queue and process its predecessors.
989 597704 : if (!loops_[loop_num].members->Contains(member->id().ToInt())) {
990 : loops_[loop_num].members->Add(member->id().ToInt());
991 : }
992 298852 : queue[queue_length++].block = member;
993 : }
994 :
995 : // Propagate loop membership backwards. All predecessors of M up to the
996 : // loop header H are members of the loop too. O(|blocks between M and H|).
997 5256205 : while (queue_length > 0) {
998 9914544 : BasicBlock* block = queue[--queue_length].block;
999 17364512 : for (size_t i = 0; i < block->PredecessorCount(); i++) {
1000 : BasicBlock* pred = block->PredecessorAt(i);
1001 6203620 : if (pred != header) {
1002 11707452 : if (!loops_[loop_num].members->Contains(pred->id().ToInt())) {
1003 : loops_[loop_num].members->Add(pred->id().ToInt());
1004 9316852 : queue[queue_length++].block = pred;
1005 : }
1006 : }
1007 : }
1008 : }
1009 : }
1010 120059 : }
1011 :
1012 : #if DEBUG
1013 : void PrintRPO() {
1014 : StdoutStream os;
1015 : os << "RPO with " << loops_.size() << " loops";
1016 : if (loops_.size() > 0) {
1017 : os << " (";
1018 : for (size_t i = 0; i < loops_.size(); i++) {
1019 : if (i > 0) os << " ";
1020 : os << "id:" << loops_[i].header->id();
1021 : }
1022 : os << ")";
1023 : }
1024 : os << ":\n";
1025 :
1026 : for (BasicBlock* block = order_; block != nullptr;
1027 : block = block->rpo_next()) {
1028 : os << std::setw(5) << "B" << block->rpo_number() << ":";
1029 : for (size_t i = 0; i < loops_.size(); i++) {
1030 : bool range = loops_[i].header->LoopContains(block);
1031 : bool membership = loops_[i].header != block && range;
1032 : os << (membership ? " |" : " ");
1033 : os << (range ? "x" : " ");
1034 : }
1035 : os << " id:" << block->id() << ": ";
1036 : if (block->loop_end() != nullptr) {
1037 : os << " range: [B" << block->rpo_number() << ", B"
1038 : << block->loop_end()->rpo_number() << ")";
1039 : }
1040 : if (block->loop_header() != nullptr) {
1041 : os << " header: id:" << block->loop_header()->id();
1042 : }
1043 : if (block->loop_depth() > 0) {
1044 : os << " depth: " << block->loop_depth();
1045 : }
1046 : os << "\n";
1047 : }
1048 : }
1049 :
1050 : void VerifySpecialRPO() {
1051 : BasicBlockVector* order = schedule_->rpo_order();
1052 : DCHECK_LT(0, order->size());
1053 : DCHECK_EQ(0, (*order)[0]->id().ToInt()); // entry should be first.
1054 :
1055 : for (size_t i = 0; i < loops_.size(); i++) {
1056 : LoopInfo* loop = &loops_[i];
1057 : BasicBlock* header = loop->header;
1058 : BasicBlock* end = header->loop_end();
1059 :
1060 : DCHECK_NOT_NULL(header);
1061 : DCHECK_LE(0, header->rpo_number());
1062 : DCHECK_LT(header->rpo_number(), order->size());
1063 : DCHECK_NOT_NULL(end);
1064 : DCHECK_LE(end->rpo_number(), order->size());
1065 : DCHECK_GT(end->rpo_number(), header->rpo_number());
1066 : DCHECK_NE(header->loop_header(), header);
1067 :
1068 : // Verify the start ... end list relationship.
1069 : int links = 0;
1070 : BasicBlock* block = loop->start;
1071 : DCHECK_EQ(header, block);
1072 : bool end_found;
1073 : while (true) {
1074 : if (block == nullptr || block == loop->end) {
1075 : end_found = (loop->end == block);
1076 : break;
1077 : }
1078 : // The list should be in same order as the final result.
1079 : DCHECK(block->rpo_number() == links + header->rpo_number());
1080 : links++;
1081 : block = block->rpo_next();
1082 : DCHECK_LT(links, static_cast<int>(2 * order->size())); // cycle?
1083 : }
1084 : DCHECK_LT(0, links);
1085 : DCHECK_EQ(links, end->rpo_number() - header->rpo_number());
1086 : DCHECK(end_found);
1087 :
1088 : // Check loop depth of the header.
1089 : int loop_depth = 0;
1090 : for (LoopInfo* outer = loop; outer != nullptr; outer = outer->prev) {
1091 : loop_depth++;
1092 : }
1093 : DCHECK_EQ(loop_depth, header->loop_depth());
1094 :
1095 : // Check the contiguousness of loops.
1096 : int count = 0;
1097 : for (int j = 0; j < static_cast<int>(order->size()); j++) {
1098 : BasicBlock* block = order->at(j);
1099 : DCHECK_EQ(block->rpo_number(), j);
1100 : if (j < header->rpo_number() || j >= end->rpo_number()) {
1101 : DCHECK(!header->LoopContains(block));
1102 : } else {
1103 : DCHECK(header->LoopContains(block));
1104 : DCHECK_GE(block->loop_depth(), loop_depth);
1105 : count++;
1106 : }
1107 : }
1108 : DCHECK_EQ(links, count);
1109 : }
1110 : }
1111 : #endif // DEBUG
1112 :
1113 : Zone* zone_;
1114 : Schedule* schedule_;
1115 : BasicBlock* order_;
1116 : BasicBlock* beyond_end_;
1117 : ZoneVector<LoopInfo> loops_;
1118 : ZoneVector<Backedge> backedges_;
1119 : ZoneVector<SpecialRPOStackFrame> stack_;
1120 : size_t previous_block_count_;
1121 : ZoneVector<BasicBlock*> const empty_;
1122 : };
1123 :
1124 :
1125 248750 : BasicBlockVector* Scheduler::ComputeSpecialRPO(Zone* zone, Schedule* schedule) {
1126 248750 : SpecialRPONumberer numberer(zone, schedule);
1127 : numberer.ComputeSpecialRPO();
1128 248750 : numberer.SerializeRPOIntoSchedule();
1129 : numberer.PrintAndVerifySpecialRPO();
1130 248750 : return schedule->rpo_order();
1131 : }
1132 :
1133 :
1134 2740546 : void Scheduler::ComputeSpecialRPONumbering() {
1135 2740546 : TRACE("--- COMPUTING SPECIAL RPO ----------------------------------\n");
1136 :
1137 : // Compute the special reverse-post-order for basic blocks.
1138 5481317 : special_rpo_ = new (zone_) SpecialRPONumberer(zone_, schedule_);
1139 : special_rpo_->ComputeSpecialRPO();
1140 2742211 : }
1141 :
1142 :
1143 2781071 : void Scheduler::PropagateImmediateDominators(BasicBlock* block) {
1144 44699909 : for (/*nop*/; block != nullptr; block = block->rpo_next()) {
1145 : auto pred = block->predecessors().begin();
1146 : auto end = block->predecessors().end();
1147 : DCHECK(pred != end); // All blocks except start have predecessors.
1148 20959272 : BasicBlock* dominator = *pred;
1149 : bool deferred = dominator->deferred();
1150 : // For multiple predecessors, walk up the dominator tree until a common
1151 : // dominator is found. Visitation order guarantees that all predecessors
1152 : // except for backwards edges have been visited.
1153 28231924 : for (++pred; pred != end; ++pred) {
1154 : // Don't examine backwards edges.
1155 7272654 : if ((*pred)->dominator_depth() < 0) continue;
1156 7063341 : dominator = BasicBlock::GetCommonDominator(dominator, *pred);
1157 7063339 : deferred = deferred & (*pred)->deferred();
1158 : }
1159 : block->set_dominator(dominator);
1160 20959270 : block->set_dominator_depth(dominator->dominator_depth() + 1);
1161 20959270 : block->set_deferred(deferred | block->deferred());
1162 20959270 : TRACE("Block id:%d's idom is id:%d, depth = %d\n", block->id().ToInt(),
1163 : dominator->id().ToInt(), block->dominator_depth());
1164 : }
1165 2781218 : }
1166 :
1167 :
1168 2741419 : void Scheduler::GenerateImmediateDominatorTree() {
1169 2741419 : TRACE("--- IMMEDIATE BLOCK DOMINATORS -----------------------------\n");
1170 :
1171 : // Seed start block to be the first dominator.
1172 2741419 : schedule_->start()->set_dominator_depth(0);
1173 :
1174 : // Build the block dominator tree resulting from the above seed.
1175 2741419 : PropagateImmediateDominators(schedule_->start()->rpo_next());
1176 2741981 : }
1177 :
1178 :
1179 : // -----------------------------------------------------------------------------
1180 : // Phase 3: Prepare use counts for nodes.
1181 :
1182 :
1183 : class PrepareUsesVisitor {
1184 : public:
1185 : explicit PrepareUsesVisitor(Scheduler* scheduler)
1186 2740799 : : scheduler_(scheduler), schedule_(scheduler->schedule_) {}
1187 :
1188 140070789 : void Pre(Node* node) {
1189 140070789 : if (scheduler_->InitializePlacement(node) == Scheduler::kFixed) {
1190 : // Fixed nodes are always roots for schedule late.
1191 40932369 : scheduler_->schedule_root_nodes_.push_back(node);
1192 40932181 : if (!schedule_->IsScheduled(node)) {
1193 : // Make sure root nodes are scheduled in their respective blocks.
1194 11388161 : TRACE("Scheduling fixed position node #%d:%s\n", node->id(),
1195 : node->op()->mnemonic());
1196 11388194 : IrOpcode::Value opcode = node->opcode();
1197 : BasicBlock* block =
1198 : opcode == IrOpcode::kParameter
1199 6348931 : ? schedule_->start()
1200 16427457 : : schedule_->block(NodeProperties::GetControlInput(node));
1201 : DCHECK_NOT_NULL(block);
1202 11388212 : schedule_->AddNode(block, node);
1203 : }
1204 : }
1205 140072652 : }
1206 :
1207 324238646 : void PostEdge(Node* from, int index, Node* to) {
1208 : // If the edge is from an unscheduled node, then tally it in the use count
1209 : // for all of its inputs. The same criterion will be used in ScheduleLate
1210 : // for decrementing use counts.
1211 324238646 : if (!schedule_->IsScheduled(from)) {
1212 : DCHECK_NE(Scheduler::kFixed, scheduler_->GetPlacement(from));
1213 249510629 : scheduler_->IncrementUnscheduledUseCount(to, index, from);
1214 : }
1215 324239244 : }
1216 :
1217 : private:
1218 : Scheduler* scheduler_;
1219 : Schedule* schedule_;
1220 : };
1221 :
1222 :
1223 2740799 : void Scheduler::PrepareUses() {
1224 2740799 : TRACE("--- PREPARE USES -------------------------------------------\n");
1225 :
1226 : // Count the uses of every node, which is used to ensure that all of a
1227 : // node's uses are scheduled before the node itself.
1228 : PrepareUsesVisitor prepare_uses(this);
1229 :
1230 : // TODO(turbofan): simplify the careful pre/post ordering here.
1231 2740799 : BoolVector visited(graph_->NodeCount(), false, zone_);
1232 2741860 : ZoneStack<Node::InputEdges::iterator> stack(zone_);
1233 2742117 : Node* node = graph_->end();
1234 2742117 : prepare_uses.Pre(node);
1235 2742518 : visited[node->id()] = true;
1236 5516354 : stack.push(node->input_edges().begin());
1237 464312836 : while (!stack.empty()) {
1238 : Edge edge = *stack.top();
1239 : Node* node = edge.to();
1240 923139878 : if (visited[node->id()]) {
1241 324240726 : prepare_uses.PostEdge(edge.from(), edge.index(), edge.to());
1242 324244412 : if (++stack.top() == edge.from()->input_edges().end()) stack.pop();
1243 : } else {
1244 137329213 : prepare_uses.Pre(node);
1245 137332695 : visited[node->id()] = true;
1246 327952473 : if (node->InputCount() > 0) stack.push(node->input_edges().begin());
1247 : }
1248 : }
1249 2743063 : }
1250 :
1251 :
1252 : // -----------------------------------------------------------------------------
1253 : // Phase 4: Schedule nodes early.
1254 :
1255 :
1256 2782409 : class ScheduleEarlyNodeVisitor {
1257 : public:
1258 : ScheduleEarlyNodeVisitor(Zone* zone, Scheduler* scheduler)
1259 2782057 : : scheduler_(scheduler), schedule_(scheduler->schedule_), queue_(zone) {}
1260 :
1261 : // Run the schedule early algorithm on a set of fixed root nodes.
1262 2780452 : void Run(NodeVector* roots) {
1263 43914208 : for (Node* const root : *roots) {
1264 : queue_.push(root);
1265 175278733 : while (!queue_.empty()) {
1266 134144977 : VisitNode(queue_.front());
1267 : queue_.pop();
1268 : }
1269 : }
1270 2782532 : }
1271 :
1272 : private:
1273 : // Visits one node from the queue and propagates its current schedule early
1274 : // position to all uses. This in turn might push more nodes onto the queue.
1275 134144954 : void VisitNode(Node* node) {
1276 134144954 : Scheduler::SchedulerData* data = scheduler_->GetData(node);
1277 :
1278 : // Fixed nodes already know their schedule early position.
1279 134144954 : if (scheduler_->GetPlacement(node) == Scheduler::kFixed) {
1280 41132868 : data->minimum_block_ = schedule_->block(node);
1281 41133681 : TRACE("Fixing #%d:%s minimum_block = id:%d, dominator_depth = %d\n",
1282 : node->id(), node->op()->mnemonic(),
1283 : data->minimum_block_->id().ToInt(),
1284 : data->minimum_block_->dominator_depth());
1285 : }
1286 :
1287 : // No need to propagate unconstrained schedule early positions.
1288 134147340 : if (data->minimum_block_ == schedule_->start()) return;
1289 :
1290 : // Propagate schedule early position.
1291 : DCHECK_NOT_NULL(data->minimum_block_);
1292 365264013 : for (auto use : node->uses()) {
1293 486001922 : if (scheduler_->IsLive(use)) {
1294 243000324 : PropagateMinimumPositionToNode(data->minimum_block_, use);
1295 : }
1296 : }
1297 : }
1298 :
1299 : // Propagates {block} as another minimum position into the given {node}. This
1300 : // has the net effect of computing the minimum dominator block of {node} that
1301 : // still post-dominates all inputs to {node} when the queue is processed.
1302 243082934 : void PropagateMinimumPositionToNode(BasicBlock* block, Node* node) {
1303 243082934 : Scheduler::SchedulerData* data = scheduler_->GetData(node);
1304 :
1305 : // No need to propagate to fixed node, it's guaranteed to be a root.
1306 243082934 : if (scheduler_->GetPlacement(node) == Scheduler::kFixed) return;
1307 :
1308 : // Coupled nodes influence schedule early position of their control.
1309 168687445 : if (scheduler_->GetPlacement(node) == Scheduler::kCoupled) {
1310 82301 : Node* control = NodeProperties::GetControlInput(node);
1311 82301 : PropagateMinimumPositionToNode(block, control);
1312 : }
1313 :
1314 : // Propagate new position if it is deeper down the dominator tree than the
1315 : // current. Note that all inputs need to have minimum block position inside
1316 : // the dominator chain of {node}'s minimum block position.
1317 : DCHECK(InsideSameDominatorChain(block, data->minimum_block_));
1318 168691046 : if (block->dominator_depth() > data->minimum_block_->dominator_depth()) {
1319 93016485 : data->minimum_block_ = block;
1320 : queue_.push(node);
1321 93016692 : TRACE("Propagating #%d:%s minimum_block = id:%d, dominator_depth = %d\n",
1322 : node->id(), node->op()->mnemonic(),
1323 : data->minimum_block_->id().ToInt(),
1324 : data->minimum_block_->dominator_depth());
1325 : }
1326 : }
1327 :
1328 : #if DEBUG
1329 : bool InsideSameDominatorChain(BasicBlock* b1, BasicBlock* b2) {
1330 : BasicBlock* dominator = BasicBlock::GetCommonDominator(b1, b2);
1331 : return dominator == b1 || dominator == b2;
1332 : }
1333 : #endif
1334 :
1335 : Scheduler* scheduler_;
1336 : Schedule* schedule_;
1337 : ZoneQueue<Node*> queue_;
1338 : };
1339 :
1340 :
1341 2742296 : void Scheduler::ScheduleEarly() {
1342 2742296 : TRACE("--- SCHEDULE EARLY -----------------------------------------\n");
1343 2742553 : if (FLAG_trace_turbo_scheduler) {
1344 0 : TRACE("roots: ");
1345 0 : for (Node* node : schedule_root_nodes_) {
1346 0 : TRACE("#%d:%s ", node->id(), node->op()->mnemonic());
1347 : }
1348 0 : TRACE("\n");
1349 : }
1350 :
1351 : // Compute the minimum block for each node thereby determining the earliest
1352 : // position each node could be placed within a valid schedule.
1353 2742553 : ScheduleEarlyNodeVisitor schedule_early_visitor(zone_, this);
1354 2742780 : schedule_early_visitor.Run(&schedule_root_nodes_);
1355 2742905 : }
1356 :
1357 :
1358 : // -----------------------------------------------------------------------------
1359 : // Phase 5: Schedule nodes late.
1360 :
1361 :
1362 2742749 : class ScheduleLateNodeVisitor {
1363 : public:
1364 2741910 : ScheduleLateNodeVisitor(Zone* zone, Scheduler* scheduler)
1365 : : zone_(zone),
1366 : scheduler_(scheduler),
1367 2741910 : schedule_(scheduler_->schedule_),
1368 : marked_(scheduler->zone_),
1369 10966825 : marking_queue_(scheduler->zone_) {}
1370 :
1371 : // Run the schedule late algorithm on a set of fixed root nodes.
1372 : void Run(NodeVector* roots) {
1373 43674369 : for (Node* const root : *roots) {
1374 40931334 : ProcessQueue(root);
1375 : }
1376 : }
1377 :
1378 : private:
1379 40936747 : void ProcessQueue(Node* root) {
1380 40936747 : ZoneQueue<Node*>* queue = &(scheduler_->schedule_queue_);
1381 190426115 : for (Node* node : root->inputs()) {
1382 : // Don't schedule coupled nodes on their own.
1383 149492868 : if (scheduler_->GetPlacement(node) == Scheduler::kCoupled) {
1384 21230 : node = NodeProperties::GetControlInput(node);
1385 : }
1386 :
1387 : // Test schedulability condition by looking at unscheduled use count.
1388 149492868 : if (scheduler_->GetData(node)->unscheduled_count_ != 0) continue;
1389 :
1390 : queue->push(node);
1391 154383375 : do {
1392 154387665 : Node* const node = queue->front();
1393 : queue->pop();
1394 154383346 : VisitNode(node);
1395 : } while (!queue->empty());
1396 : }
1397 40933247 : }
1398 :
1399 : // Visits one node from the queue of schedulable nodes and determines its
1400 : // schedule late position. Also hoists nodes out of loops to find a more
1401 : // optimal scheduling position.
1402 154383562 : void VisitNode(Node* node) {
1403 : DCHECK_EQ(0, scheduler_->GetData(node)->unscheduled_count_);
1404 :
1405 : // Don't schedule nodes that are already scheduled.
1406 154383562 : if (schedule_->IsScheduled(node)) return;
1407 : DCHECK_EQ(Scheduler::kSchedulable, scheduler_->GetPlacement(node));
1408 :
1409 : // Determine the dominating block for all of the uses of this node. It is
1410 : // the latest block that this node can be scheduled in.
1411 99519775 : TRACE("Scheduling #%d:%s\n", node->id(), node->op()->mnemonic());
1412 99519775 : BasicBlock* block = GetCommonDominatorOfUses(node);
1413 : DCHECK_NOT_NULL(block);
1414 :
1415 : // The schedule early block dominates the schedule late block.
1416 199039452 : BasicBlock* min_block = scheduler_->GetData(node)->minimum_block_;
1417 : DCHECK_EQ(min_block, BasicBlock::GetCommonDominator(block, min_block));
1418 99519726 : TRACE(
1419 : "Schedule late of #%d:%s is id:%d at loop depth %d, minimum = id:%d\n",
1420 : node->id(), node->op()->mnemonic(), block->id().ToInt(),
1421 : block->loop_depth(), min_block->id().ToInt());
1422 :
1423 : // Hoist nodes out of loops if possible. Nodes can be hoisted iteratively
1424 : // into enclosing loop pre-headers until they would precede their schedule
1425 : // early position.
1426 99519726 : BasicBlock* hoist_block = GetHoistBlock(block);
1427 99519378 : if (hoist_block &&
1428 : hoist_block->dominator_depth() >= min_block->dominator_depth()) {
1429 475595 : do {
1430 475597 : TRACE(" hoisting #%d:%s to block id:%d\n", node->id(),
1431 : node->op()->mnemonic(), hoist_block->id().ToInt());
1432 : DCHECK_LT(hoist_block->loop_depth(), block->loop_depth());
1433 : block = hoist_block;
1434 475597 : hoist_block = GetHoistBlock(hoist_block);
1435 475595 : } while (hoist_block &&
1436 : hoist_block->dominator_depth() >= min_block->dominator_depth());
1437 198095374 : } else if (scheduler_->flags_ & Scheduler::kSplitNodes) {
1438 : // Split the {node} if beneficial and return the new {block} for it.
1439 39347337 : block = SplitNode(block, node);
1440 : }
1441 :
1442 : // Schedule the node or a floating control structure.
1443 99519712 : if (IrOpcode::IsMergeOpcode(node->opcode())) {
1444 : ScheduleFloatingControl(block, node);
1445 99480208 : } else if (node->opcode() == IrOpcode::kFinishRegion) {
1446 132262 : ScheduleRegion(block, node);
1447 : } else {
1448 99347946 : ScheduleNode(block, node);
1449 : }
1450 : }
1451 :
1452 : bool IsMarked(BasicBlock* block) const {
1453 : DCHECK_LT(block->id().ToSize(), marked_.size());
1454 : return marked_[block->id().ToSize()];
1455 : }
1456 :
1457 : void Mark(BasicBlock* block) { marked_[block->id().ToSize()] = true; }
1458 :
1459 : // Mark {block} and push its non-marked predecessor on the marking queue.
1460 79108770 : void MarkBlock(BasicBlock* block) {
1461 : DCHECK_LT(block->id().ToSize(), marked_.size());
1462 : Mark(block);
1463 183599361 : for (BasicBlock* pred_block : block->predecessors()) {
1464 104490533 : if (IsMarked(pred_block)) continue;
1465 98277145 : marking_queue_.push_back(pred_block);
1466 : }
1467 79108828 : }
1468 :
1469 39347302 : BasicBlock* SplitNode(BasicBlock* block, Node* node) {
1470 : // For now, we limit splitting to pure nodes.
1471 39347302 : if (!node->op()->HasProperty(Operator::kPure)) return block;
1472 : // TODO(titzer): fix the special case of splitting of projections.
1473 27700332 : if (node->opcode() == IrOpcode::kProjection) return block;
1474 :
1475 : // The {block} is common dominator of all uses of {node}, so we cannot
1476 : // split anything unless the {block} has at least two successors.
1477 : DCHECK_EQ(block, GetCommonDominatorOfUses(node));
1478 27411883 : if (block->SuccessorCount() < 2) return block;
1479 :
1480 : // Clear marking bits.
1481 : DCHECK(marking_queue_.empty());
1482 27308906 : std::fill(marked_.begin(), marked_.end(), false);
1483 27309046 : marked_.resize(schedule_->BasicBlockCount() + 1, false);
1484 :
1485 : // Check if the {node} has uses in {block}.
1486 74029301 : for (Edge edge : node->use_edges()) {
1487 71191948 : if (!scheduler_->IsLive(edge.from())) continue;
1488 35595855 : BasicBlock* use_block = GetBlockForUse(edge);
1489 71191677 : if (use_block == nullptr || IsMarked(use_block)) continue;
1490 26833884 : if (use_block == block) {
1491 10817073 : TRACE(" not splitting #%d:%s, it is used in id:%d\n", node->id(),
1492 : node->op()->mnemonic(), block->id().ToInt());
1493 10817073 : marking_queue_.clear();
1494 10817040 : return block;
1495 : }
1496 16016811 : MarkBlock(use_block);
1497 : }
1498 :
1499 : // Compute transitive marking closure; a block is marked if all its
1500 : // successors are marked.
1501 91314720 : do {
1502 91314727 : BasicBlock* top_block = marking_queue_.front();
1503 91314727 : marking_queue_.pop_front();
1504 91314674 : if (IsMarked(top_block)) continue;
1505 : bool marked = true;
1506 160762730 : for (BasicBlock* successor : top_block->successors()) {
1507 97670494 : if (!IsMarked(successor)) {
1508 : marked = false;
1509 : break;
1510 : }
1511 : }
1512 72028486 : if (marked) MarkBlock(top_block);
1513 : } while (!marking_queue_.empty());
1514 :
1515 : // If the (common dominator) {block} is marked, we know that all paths from
1516 : // {block} to the end contain at least one use of {node}, and hence there's
1517 : // no point in splitting the {node} in this case.
1518 2837346 : if (IsMarked(block)) {
1519 1759219 : TRACE(" not splitting #%d:%s, its common dominator id:%d is perfect\n",
1520 : node->id(), node->op()->mnemonic(), block->id().ToInt());
1521 : return block;
1522 : }
1523 :
1524 : // Split {node} for uses according to the previously computed marking
1525 : // closure. Every marking partition has a unique dominator, which get's a
1526 : // copy of the {node} with the exception of the first partition, which get's
1527 : // the {node} itself.
1528 1078127 : ZoneMap<BasicBlock*, Node*> dominators(scheduler_->zone_);
1529 10551149 : for (Edge edge : node->use_edges()) {
1530 9473022 : if (!scheduler_->IsLive(edge.from())) continue;
1531 4736513 : BasicBlock* use_block = GetBlockForUse(edge);
1532 4736514 : if (use_block == nullptr) continue;
1533 22442828 : while (IsMarked(use_block->dominator())) {
1534 4323268 : use_block = use_block->dominator();
1535 : }
1536 4736512 : auto& use_node = dominators[use_block];
1537 4736506 : if (use_node == nullptr) {
1538 3435447 : if (dominators.size() == 1u) {
1539 : // Place the {node} at {use_block}.
1540 1078131 : block = use_block;
1541 1078131 : use_node = node;
1542 1078131 : TRACE(" pushing #%d:%s down to id:%d\n", node->id(),
1543 : node->op()->mnemonic(), block->id().ToInt());
1544 : } else {
1545 : // Place a copy of {node} at {use_block}.
1546 2357316 : use_node = CloneNode(node);
1547 2357309 : TRACE(" cloning #%d:%s for id:%d\n", use_node->id(),
1548 : use_node->op()->mnemonic(), use_block->id().ToInt());
1549 2357309 : scheduler_->schedule_queue_.push(use_node);
1550 : }
1551 : }
1552 4736498 : edge.UpdateTo(use_node);
1553 : }
1554 : return block;
1555 : }
1556 :
1557 99994811 : BasicBlock* GetHoistBlock(BasicBlock* block) {
1558 99994811 : if (block->IsLoopHeader()) return block->dominator();
1559 : // We have to check to make sure that the {block} dominates all
1560 : // of the outgoing blocks. If it doesn't, then there is a path
1561 : // out of the loop which does not execute this {block}, so we
1562 : // can't hoist operations from this {block} out of the loop, as
1563 : // that would introduce additional computations.
1564 98855172 : if (BasicBlock* header_block = block->loop_header()) {
1565 13183143 : for (BasicBlock* outgoing_block :
1566 20330481 : scheduler_->special_rpo_->GetOutgoingBlocks(header_block)) {
1567 12898074 : if (BasicBlock::GetCommonDominator(block, outgoing_block) != block) {
1568 : return nullptr;
1569 : }
1570 : }
1571 285069 : return header_block->dominator();
1572 : }
1573 : return nullptr;
1574 : }
1575 :
1576 99563018 : BasicBlock* GetCommonDominatorOfUses(Node* node) {
1577 : BasicBlock* block = nullptr;
1578 535228034 : for (Edge edge : node->use_edges()) {
1579 435668718 : if (!scheduler_->IsLive(edge.from())) continue;
1580 217832203 : BasicBlock* use_block = GetBlockForUse(edge);
1581 : block = block == nullptr
1582 : ? use_block
1583 : : use_block == nullptr
1584 : ? block
1585 217830772 : : BasicBlock::GetCommonDominator(block, use_block);
1586 : }
1587 99559316 : return block;
1588 : }
1589 :
1590 : BasicBlock* FindPredecessorBlock(Node* node) {
1591 11785516 : return scheduler_->control_flow_builder_->FindPredecessorBlock(node);
1592 : }
1593 :
1594 258161975 : BasicBlock* GetBlockForUse(Edge edge) {
1595 : // TODO(titzer): ignore uses from dead nodes (not visited in PrepareUses()).
1596 : // Dead uses only occur if the graph is not trimmed before scheduling.
1597 : Node* use = edge.from();
1598 258161975 : if (IrOpcode::IsPhiOpcode(use->opcode())) {
1599 : // If the use is from a coupled (i.e. floating) phi, compute the common
1600 : // dominator of its uses. This will not recurse more than one level.
1601 20470718 : if (scheduler_->GetPlacement(use) == Scheduler::kCoupled) {
1602 39506 : TRACE(" inspecting uses of coupled #%d:%s\n", use->id(),
1603 : use->op()->mnemonic());
1604 : // TODO(titzer): reenable once above TODO is addressed.
1605 : // DCHECK_EQ(edge.to(), NodeProperties::GetControlInput(use));
1606 39506 : return GetCommonDominatorOfUses(use);
1607 : }
1608 : // If the use is from a fixed (i.e. non-floating) phi, we use the
1609 : // predecessor block of the corresponding control input to the merge.
1610 10195853 : if (scheduler_->GetPlacement(use) == Scheduler::kFixed) {
1611 10195850 : TRACE(" input@%d into a fixed phi #%d:%s\n", edge.index(), use->id(),
1612 : use->op()->mnemonic());
1613 10195850 : Node* merge = NodeProperties::GetControlInput(use, 0);
1614 : DCHECK(IrOpcode::IsMergeOpcode(merge->opcode()));
1615 10195786 : Node* input = NodeProperties::GetControlInput(merge, edge.index());
1616 10195709 : return FindPredecessorBlock(input);
1617 : }
1618 247926616 : } else if (IrOpcode::IsMergeOpcode(use->opcode())) {
1619 : // If the use is from a fixed (i.e. non-floating) merge, we use the
1620 : // predecessor block of the current input to the merge.
1621 3179624 : if (scheduler_->GetPlacement(use) == Scheduler::kFixed) {
1622 1589815 : TRACE(" input@%d into a fixed merge #%d:%s\n", edge.index(), use->id(),
1623 : use->op()->mnemonic());
1624 1589815 : return FindPredecessorBlock(edge.to());
1625 : }
1626 : }
1627 246336804 : BasicBlock* result = schedule_->block(use);
1628 246336413 : if (result == nullptr) return nullptr;
1629 246336607 : TRACE(" must dominate use #%d:%s in id:%d\n", use->id(),
1630 : use->op()->mnemonic(), result->id().ToInt());
1631 : return result;
1632 : }
1633 :
1634 : void ScheduleFloatingControl(BasicBlock* block, Node* node) {
1635 39504 : scheduler_->FuseFloatingControl(block, node);
1636 : }
1637 :
1638 132262 : void ScheduleRegion(BasicBlock* block, Node* region_end) {
1639 : // We only allow regions of instructions connected into a linear
1640 : // effect chain. The only value allowed to be produced by a node
1641 : // in the chain must be the value consumed by the FinishRegion node.
1642 :
1643 : // We schedule back to front; we first schedule FinishRegion.
1644 132262 : CHECK_EQ(IrOpcode::kFinishRegion, region_end->opcode());
1645 132262 : ScheduleNode(block, region_end);
1646 :
1647 : // Schedule the chain.
1648 132262 : Node* node = NodeProperties::GetEffectInput(region_end);
1649 3514072 : while (node->opcode() != IrOpcode::kBeginRegion) {
1650 : DCHECK_EQ(0, scheduler_->GetData(node)->unscheduled_count_);
1651 : DCHECK_EQ(1, node->op()->EffectInputCount());
1652 : DCHECK_EQ(1, node->op()->EffectOutputCount());
1653 : DCHECK_EQ(0, node->op()->ControlOutputCount());
1654 : // The value output (if there is any) must be consumed
1655 : // by the EndRegion node.
1656 : DCHECK(node->op()->ValueOutputCount() == 0 ||
1657 : node == region_end->InputAt(0));
1658 1690905 : ScheduleNode(block, node);
1659 1690905 : node = NodeProperties::GetEffectInput(node);
1660 : }
1661 : // Schedule the BeginRegion node.
1662 : DCHECK_EQ(0, scheduler_->GetData(node)->unscheduled_count_);
1663 132262 : ScheduleNode(block, node);
1664 132262 : }
1665 :
1666 101302943 : void ScheduleNode(BasicBlock* block, Node* node) {
1667 101302943 : schedule_->PlanNode(block, node);
1668 : size_t block_id = block->id().ToSize();
1669 202604410 : if (!scheduler_->scheduled_nodes_[block_id]) {
1670 12246183 : scheduler_->scheduled_nodes_[block_id] =
1671 36739123 : new (zone_->New(sizeof(NodeVector))) NodeVector(zone_);
1672 : }
1673 202603262 : scheduler_->scheduled_nodes_[block_id]->push_back(node);
1674 101300208 : scheduler_->UpdatePlacement(node, Scheduler::kScheduled);
1675 101302735 : }
1676 :
1677 2357316 : Node* CloneNode(Node* node) {
1678 : int const input_count = node->InputCount();
1679 6517726 : for (int index = 0; index < input_count; ++index) {
1680 : Node* const input = node->InputAt(index);
1681 2080204 : scheduler_->IncrementUnscheduledUseCount(input, index, node);
1682 : }
1683 2357317 : Node* const copy = scheduler_->graph_->CloneNode(node);
1684 2357306 : TRACE(("clone #%d:%s -> #%d\n"), node->id(), node->op()->mnemonic(),
1685 : copy->id());
1686 2357306 : scheduler_->node_data_.resize(copy->id() + 1,
1687 4714612 : scheduler_->DefaultSchedulerData());
1688 7071927 : scheduler_->node_data_[copy->id()] = scheduler_->node_data_[node->id()];
1689 2357309 : return copy;
1690 : }
1691 :
1692 : Zone* zone_;
1693 : Scheduler* scheduler_;
1694 : Schedule* schedule_;
1695 : BoolVector marked_;
1696 : ZoneDeque<BasicBlock*> marking_queue_;
1697 : };
1698 :
1699 :
1700 2741712 : void Scheduler::ScheduleLate() {
1701 2741712 : TRACE("--- SCHEDULE LATE ------------------------------------------\n");
1702 2741905 : if (FLAG_trace_turbo_scheduler) {
1703 0 : TRACE("roots: ");
1704 0 : for (Node* node : schedule_root_nodes_) {
1705 0 : TRACE("#%d:%s ", node->id(), node->op()->mnemonic());
1706 : }
1707 0 : TRACE("\n");
1708 : }
1709 :
1710 : // Schedule: Places nodes in dominator block of all their uses.
1711 2741905 : ScheduleLateNodeVisitor schedule_late_visitor(zone_, this);
1712 : schedule_late_visitor.Run(&schedule_root_nodes_);
1713 2742749 : }
1714 :
1715 :
1716 : // -----------------------------------------------------------------------------
1717 : // Phase 6: Seal the final schedule.
1718 :
1719 :
1720 2742694 : void Scheduler::SealFinalSchedule() {
1721 2742694 : TRACE("--- SEAL FINAL SCHEDULE ------------------------------------\n");
1722 :
1723 : // Serialize the assembly order and reverse-post-order numbering.
1724 2742694 : special_rpo_->SerializeRPOIntoSchedule();
1725 : special_rpo_->PrintAndVerifySpecialRPO();
1726 :
1727 : // Add collected nodes for basic blocks to their blocks in the right order.
1728 : int block_num = 0;
1729 23267596 : for (NodeVector* nodes : scheduled_nodes_) {
1730 41049294 : BasicBlock::Id id = BasicBlock::Id::FromInt(block_num++);
1731 20524647 : BasicBlock* block = schedule_->GetBlockById(id);
1732 20525282 : if (nodes) {
1733 113546474 : for (Node* node : base::Reversed(*nodes)) {
1734 101299502 : schedule_->AddNode(block, node);
1735 : }
1736 : }
1737 : }
1738 2742949 : }
1739 :
1740 :
1741 : // -----------------------------------------------------------------------------
1742 :
1743 :
1744 39504 : void Scheduler::FuseFloatingControl(BasicBlock* block, Node* node) {
1745 39504 : TRACE("--- FUSE FLOATING CONTROL ----------------------------------\n");
1746 39504 : if (FLAG_trace_turbo_scheduler) {
1747 0 : StdoutStream{} << "Schedule before control flow fusion:\n" << *schedule_;
1748 : }
1749 :
1750 : // Iterate on phase 1: Build control-flow graph.
1751 39504 : control_flow_builder_->Run(block, node);
1752 :
1753 : // Iterate on phase 2: Compute special RPO and dominator tree.
1754 39504 : special_rpo_->UpdateSpecialRPO(block, schedule_->block(node));
1755 : // TODO(mstarzinger): Currently "iterate on" means "re-run". Fix that.
1756 6637645 : for (BasicBlock* b = block->rpo_next(); b != nullptr; b = b->rpo_next()) {
1757 : b->set_dominator_depth(-1);
1758 : b->set_dominator(nullptr);
1759 : }
1760 39503 : PropagateImmediateDominators(block->rpo_next());
1761 :
1762 : // Iterate on phase 4: Schedule nodes early.
1763 : // TODO(mstarzinger): The following loop gathering the propagation roots is a
1764 : // temporary solution and should be merged into the rest of the scheduler as
1765 : // soon as the approach settled for all floating loops.
1766 39504 : NodeVector propagation_roots(control_flow_builder_->control_);
1767 238664 : for (Node* node : control_flow_builder_->control_) {
1768 592336 : for (Node* use : node->uses()) {
1769 256256 : if (NodeProperties::IsPhi(use) && IsLive(use)) {
1770 39914 : propagation_roots.push_back(use);
1771 : }
1772 : }
1773 : }
1774 39504 : if (FLAG_trace_turbo_scheduler) {
1775 0 : TRACE("propagation roots: ");
1776 0 : for (Node* node : propagation_roots) {
1777 0 : TRACE("#%d:%s ", node->id(), node->op()->mnemonic());
1778 : }
1779 0 : TRACE("\n");
1780 : }
1781 39504 : ScheduleEarlyNodeVisitor schedule_early_visitor(zone_, this);
1782 39504 : schedule_early_visitor.Run(&propagation_roots);
1783 :
1784 : // Move previously planned nodes.
1785 : // TODO(mstarzinger): Improve that by supporting bulk moves.
1786 79008 : scheduled_nodes_.resize(schedule_->BasicBlockCount());
1787 39503 : MovePlannedNodes(block, schedule_->block(node));
1788 :
1789 39504 : if (FLAG_trace_turbo_scheduler) {
1790 0 : StdoutStream{} << "Schedule after control flow fusion:\n" << *schedule_;
1791 : }
1792 39504 : }
1793 :
1794 :
1795 39503 : void Scheduler::MovePlannedNodes(BasicBlock* from, BasicBlock* to) {
1796 39503 : TRACE("Move planned nodes from id:%d to id:%d\n", from->id().ToInt(),
1797 : to->id().ToInt());
1798 39504 : NodeVector* from_nodes = scheduled_nodes_[from->id().ToSize()];
1799 39504 : NodeVector* to_nodes = scheduled_nodes_[to->id().ToSize()];
1800 39504 : if (!from_nodes) return;
1801 :
1802 240479 : for (Node* const node : *from_nodes) {
1803 222261 : schedule_->SetBlockForNode(to, node);
1804 : }
1805 18218 : if (to_nodes) {
1806 0 : to_nodes->insert(to_nodes->end(), from_nodes->begin(), from_nodes->end());
1807 : from_nodes->clear();
1808 : } else {
1809 : std::swap(scheduled_nodes_[from->id().ToSize()],
1810 : scheduled_nodes_[to->id().ToSize()]);
1811 : }
1812 : }
1813 :
1814 : #undef TRACE
1815 :
1816 : } // namespace compiler
1817 : } // namespace internal
1818 120216 : } // namespace v8
|