1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
18 #include "llvm/CodeGen/SelectionDAGNodes.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <climits>
26 using namespace llvm;
27
28 #ifndef NDEBUG
29 static cl::opt<bool> StressSchedOpt(
30 "stress-sched", cl::Hidden, cl::init(false),
31 cl::desc("Stress test instruction scheduling"));
32 #endif
33
anchor()34 void SchedulingPriorityQueue::anchor() { }
35
ScheduleDAG(MachineFunction & mf)36 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
37 : TM(mf.getTarget()),
38 TII(TM.getInstrInfo()),
39 TRI(TM.getRegisterInfo()),
40 MF(mf), MRI(mf.getRegInfo()),
41 EntrySU(), ExitSU() {
42 #ifndef NDEBUG
43 StressSched = StressSchedOpt;
44 #endif
45 }
46
~ScheduleDAG()47 ScheduleDAG::~ScheduleDAG() {}
48
49 /// Clear the DAG state (e.g. between scheduling regions).
clearDAG()50 void ScheduleDAG::clearDAG() {
51 SUnits.clear();
52 EntrySU = SUnit();
53 ExitSU = SUnit();
54 }
55
56 /// getInstrDesc helper to handle SDNodes.
getNodeDesc(const SDNode * Node) const57 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
58 if (!Node || !Node->isMachineOpcode()) return NULL;
59 return &TII->get(Node->getMachineOpcode());
60 }
61
62 /// addPred - This adds the specified edge as a pred of the current node if
63 /// not already. It also adds the current node as a successor of the
64 /// specified node.
addPred(const SDep & D)65 bool SUnit::addPred(const SDep &D) {
66 // If this node already has this depenence, don't add a redundant one.
67 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
68 I != E; ++I)
69 if (*I == D)
70 return false;
71 // Now add a corresponding succ to N.
72 SDep P = D;
73 P.setSUnit(this);
74 SUnit *N = D.getSUnit();
75 // Update the bookkeeping.
76 if (D.getKind() == SDep::Data) {
77 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
78 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
79 ++NumPreds;
80 ++N->NumSuccs;
81 }
82 if (!N->isScheduled) {
83 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
84 ++NumPredsLeft;
85 }
86 if (!isScheduled) {
87 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
88 ++N->NumSuccsLeft;
89 }
90 Preds.push_back(D);
91 N->Succs.push_back(P);
92 if (P.getLatency() != 0) {
93 this->setDepthDirty();
94 N->setHeightDirty();
95 }
96 return true;
97 }
98
99 /// removePred - This removes the specified edge as a pred of the current
100 /// node if it exists. It also removes the current node as a successor of
101 /// the specified node.
removePred(const SDep & D)102 void SUnit::removePred(const SDep &D) {
103 // Find the matching predecessor.
104 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
105 I != E; ++I)
106 if (*I == D) {
107 bool FoundSucc = false;
108 // Find the corresponding successor in N.
109 SDep P = D;
110 P.setSUnit(this);
111 SUnit *N = D.getSUnit();
112 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
113 EE = N->Succs.end(); II != EE; ++II)
114 if (*II == P) {
115 FoundSucc = true;
116 N->Succs.erase(II);
117 break;
118 }
119 assert(FoundSucc && "Mismatching preds / succs lists!");
120 (void)FoundSucc;
121 Preds.erase(I);
122 // Update the bookkeeping.
123 if (P.getKind() == SDep::Data) {
124 assert(NumPreds > 0 && "NumPreds will underflow!");
125 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
126 --NumPreds;
127 --N->NumSuccs;
128 }
129 if (!N->isScheduled) {
130 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
131 --NumPredsLeft;
132 }
133 if (!isScheduled) {
134 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
135 --N->NumSuccsLeft;
136 }
137 if (P.getLatency() != 0) {
138 this->setDepthDirty();
139 N->setHeightDirty();
140 }
141 return;
142 }
143 }
144
setDepthDirty()145 void SUnit::setDepthDirty() {
146 if (!isDepthCurrent) return;
147 SmallVector<SUnit*, 8> WorkList;
148 WorkList.push_back(this);
149 do {
150 SUnit *SU = WorkList.pop_back_val();
151 SU->isDepthCurrent = false;
152 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
153 E = SU->Succs.end(); I != E; ++I) {
154 SUnit *SuccSU = I->getSUnit();
155 if (SuccSU->isDepthCurrent)
156 WorkList.push_back(SuccSU);
157 }
158 } while (!WorkList.empty());
159 }
160
setHeightDirty()161 void SUnit::setHeightDirty() {
162 if (!isHeightCurrent) return;
163 SmallVector<SUnit*, 8> WorkList;
164 WorkList.push_back(this);
165 do {
166 SUnit *SU = WorkList.pop_back_val();
167 SU->isHeightCurrent = false;
168 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
169 E = SU->Preds.end(); I != E; ++I) {
170 SUnit *PredSU = I->getSUnit();
171 if (PredSU->isHeightCurrent)
172 WorkList.push_back(PredSU);
173 }
174 } while (!WorkList.empty());
175 }
176
177 /// setDepthToAtLeast - Update this node's successors to reflect the
178 /// fact that this node's depth just increased.
179 ///
setDepthToAtLeast(unsigned NewDepth)180 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
181 if (NewDepth <= getDepth())
182 return;
183 setDepthDirty();
184 Depth = NewDepth;
185 isDepthCurrent = true;
186 }
187
188 /// setHeightToAtLeast - Update this node's predecessors to reflect the
189 /// fact that this node's height just increased.
190 ///
setHeightToAtLeast(unsigned NewHeight)191 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
192 if (NewHeight <= getHeight())
193 return;
194 setHeightDirty();
195 Height = NewHeight;
196 isHeightCurrent = true;
197 }
198
199 /// ComputeDepth - Calculate the maximal path from the node to the exit.
200 ///
ComputeDepth()201 void SUnit::ComputeDepth() {
202 SmallVector<SUnit*, 8> WorkList;
203 WorkList.push_back(this);
204 do {
205 SUnit *Cur = WorkList.back();
206
207 bool Done = true;
208 unsigned MaxPredDepth = 0;
209 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
210 E = Cur->Preds.end(); I != E; ++I) {
211 SUnit *PredSU = I->getSUnit();
212 if (PredSU->isDepthCurrent)
213 MaxPredDepth = std::max(MaxPredDepth,
214 PredSU->Depth + I->getLatency());
215 else {
216 Done = false;
217 WorkList.push_back(PredSU);
218 }
219 }
220
221 if (Done) {
222 WorkList.pop_back();
223 if (MaxPredDepth != Cur->Depth) {
224 Cur->setDepthDirty();
225 Cur->Depth = MaxPredDepth;
226 }
227 Cur->isDepthCurrent = true;
228 }
229 } while (!WorkList.empty());
230 }
231
232 /// ComputeHeight - Calculate the maximal path from the node to the entry.
233 ///
ComputeHeight()234 void SUnit::ComputeHeight() {
235 SmallVector<SUnit*, 8> WorkList;
236 WorkList.push_back(this);
237 do {
238 SUnit *Cur = WorkList.back();
239
240 bool Done = true;
241 unsigned MaxSuccHeight = 0;
242 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
243 E = Cur->Succs.end(); I != E; ++I) {
244 SUnit *SuccSU = I->getSUnit();
245 if (SuccSU->isHeightCurrent)
246 MaxSuccHeight = std::max(MaxSuccHeight,
247 SuccSU->Height + I->getLatency());
248 else {
249 Done = false;
250 WorkList.push_back(SuccSU);
251 }
252 }
253
254 if (Done) {
255 WorkList.pop_back();
256 if (MaxSuccHeight != Cur->Height) {
257 Cur->setHeightDirty();
258 Cur->Height = MaxSuccHeight;
259 }
260 Cur->isHeightCurrent = true;
261 }
262 } while (!WorkList.empty());
263 }
264
265 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
266 /// a group of nodes flagged together.
dump(const ScheduleDAG * G) const267 void SUnit::dump(const ScheduleDAG *G) const {
268 dbgs() << "SU(" << NodeNum << "): ";
269 G->dumpNode(this);
270 }
271
dumpAll(const ScheduleDAG * G) const272 void SUnit::dumpAll(const ScheduleDAG *G) const {
273 dump(G);
274
275 dbgs() << " # preds left : " << NumPredsLeft << "\n";
276 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
277 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
278 dbgs() << " Latency : " << Latency << "\n";
279 dbgs() << " Depth : " << Depth << "\n";
280 dbgs() << " Height : " << Height << "\n";
281
282 if (Preds.size() != 0) {
283 dbgs() << " Predecessors:\n";
284 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
285 I != E; ++I) {
286 dbgs() << " ";
287 switch (I->getKind()) {
288 case SDep::Data: dbgs() << "val "; break;
289 case SDep::Anti: dbgs() << "anti"; break;
290 case SDep::Output: dbgs() << "out "; break;
291 case SDep::Order: dbgs() << "ch "; break;
292 }
293 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
294 if (I->isArtificial())
295 dbgs() << " *";
296 dbgs() << ": Latency=" << I->getLatency();
297 if (I->isAssignedRegDep())
298 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
299 dbgs() << "\n";
300 }
301 }
302 if (Succs.size() != 0) {
303 dbgs() << " Successors:\n";
304 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
305 I != E; ++I) {
306 dbgs() << " ";
307 switch (I->getKind()) {
308 case SDep::Data: dbgs() << "val "; break;
309 case SDep::Anti: dbgs() << "anti"; break;
310 case SDep::Output: dbgs() << "out "; break;
311 case SDep::Order: dbgs() << "ch "; break;
312 }
313 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
314 if (I->isArtificial())
315 dbgs() << " *";
316 dbgs() << ": Latency=" << I->getLatency();
317 dbgs() << "\n";
318 }
319 }
320 dbgs() << "\n";
321 }
322
323 #ifndef NDEBUG
324 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
325 /// their state is consistent. Return the number of scheduled nodes.
326 ///
VerifyScheduledDAG(bool isBottomUp)327 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
328 bool AnyNotSched = false;
329 unsigned DeadNodes = 0;
330 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
331 if (!SUnits[i].isScheduled) {
332 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
333 ++DeadNodes;
334 continue;
335 }
336 if (!AnyNotSched)
337 dbgs() << "*** Scheduling failed! ***\n";
338 SUnits[i].dump(this);
339 dbgs() << "has not been scheduled!\n";
340 AnyNotSched = true;
341 }
342 if (SUnits[i].isScheduled &&
343 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
344 unsigned(INT_MAX)) {
345 if (!AnyNotSched)
346 dbgs() << "*** Scheduling failed! ***\n";
347 SUnits[i].dump(this);
348 dbgs() << "has an unexpected "
349 << (isBottomUp ? "Height" : "Depth") << " value!\n";
350 AnyNotSched = true;
351 }
352 if (isBottomUp) {
353 if (SUnits[i].NumSuccsLeft != 0) {
354 if (!AnyNotSched)
355 dbgs() << "*** Scheduling failed! ***\n";
356 SUnits[i].dump(this);
357 dbgs() << "has successors left!\n";
358 AnyNotSched = true;
359 }
360 } else {
361 if (SUnits[i].NumPredsLeft != 0) {
362 if (!AnyNotSched)
363 dbgs() << "*** Scheduling failed! ***\n";
364 SUnits[i].dump(this);
365 dbgs() << "has predecessors left!\n";
366 AnyNotSched = true;
367 }
368 }
369 }
370 assert(!AnyNotSched);
371 return SUnits.size() - DeadNodes;
372 }
373 #endif
374
375 /// InitDAGTopologicalSorting - create the initial topological
376 /// ordering from the DAG to be scheduled.
377 ///
378 /// The idea of the algorithm is taken from
379 /// "Online algorithms for managing the topological order of
380 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
381 /// This is the MNR algorithm, which was first introduced by
382 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
383 /// "Maintaining a topological order under edge insertions".
384 ///
385 /// Short description of the algorithm:
386 ///
387 /// Topological ordering, ord, of a DAG maps each node to a topological
388 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
389 ///
390 /// This means that if there is a path from the node X to the node Z,
391 /// then ord(X) < ord(Z).
392 ///
393 /// This property can be used to check for reachability of nodes:
394 /// if Z is reachable from X, then an insertion of the edge Z->X would
395 /// create a cycle.
396 ///
397 /// The algorithm first computes a topological ordering for the DAG by
398 /// initializing the Index2Node and Node2Index arrays and then tries to keep
399 /// the ordering up-to-date after edge insertions by reordering the DAG.
400 ///
401 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
402 /// the nodes reachable from Y, and then shifts them using Shift to lie
403 /// immediately after X in Index2Node.
InitDAGTopologicalSorting()404 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
405 unsigned DAGSize = SUnits.size();
406 std::vector<SUnit*> WorkList;
407 WorkList.reserve(DAGSize);
408
409 Index2Node.resize(DAGSize);
410 Node2Index.resize(DAGSize);
411
412 // Initialize the data structures.
413 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
414 SUnit *SU = &SUnits[i];
415 int NodeNum = SU->NodeNum;
416 unsigned Degree = SU->Succs.size();
417 // Temporarily use the Node2Index array as scratch space for degree counts.
418 Node2Index[NodeNum] = Degree;
419
420 // Is it a node without dependencies?
421 if (Degree == 0) {
422 assert(SU->Succs.empty() && "SUnit should have no successors");
423 // Collect leaf nodes.
424 WorkList.push_back(SU);
425 }
426 }
427
428 int Id = DAGSize;
429 while (!WorkList.empty()) {
430 SUnit *SU = WorkList.back();
431 WorkList.pop_back();
432 Allocate(SU->NodeNum, --Id);
433 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
434 I != E; ++I) {
435 SUnit *SU = I->getSUnit();
436 if (!--Node2Index[SU->NodeNum])
437 // If all dependencies of the node are processed already,
438 // then the node can be computed now.
439 WorkList.push_back(SU);
440 }
441 }
442
443 Visited.resize(DAGSize);
444
445 #ifndef NDEBUG
446 // Check correctness of the ordering
447 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
448 SUnit *SU = &SUnits[i];
449 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
450 I != E; ++I) {
451 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
452 "Wrong topological sorting");
453 }
454 }
455 #endif
456 }
457
458 /// AddPred - Updates the topological ordering to accommodate an edge
459 /// to be added from SUnit X to SUnit Y.
AddPred(SUnit * Y,SUnit * X)460 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
461 int UpperBound, LowerBound;
462 LowerBound = Node2Index[Y->NodeNum];
463 UpperBound = Node2Index[X->NodeNum];
464 bool HasLoop = false;
465 // Is Ord(X) < Ord(Y) ?
466 if (LowerBound < UpperBound) {
467 // Update the topological order.
468 Visited.reset();
469 DFS(Y, UpperBound, HasLoop);
470 assert(!HasLoop && "Inserted edge creates a loop!");
471 // Recompute topological indexes.
472 Shift(Visited, LowerBound, UpperBound);
473 }
474 }
475
476 /// RemovePred - Updates the topological ordering to accommodate an
477 /// an edge to be removed from the specified node N from the predecessors
478 /// of the current node M.
RemovePred(SUnit * M,SUnit * N)479 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
480 // InitDAGTopologicalSorting();
481 }
482
483 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
484 /// all nodes affected by the edge insertion. These nodes will later get new
485 /// topological indexes by means of the Shift method.
DFS(const SUnit * SU,int UpperBound,bool & HasLoop)486 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
487 bool &HasLoop) {
488 std::vector<const SUnit*> WorkList;
489 WorkList.reserve(SUnits.size());
490
491 WorkList.push_back(SU);
492 do {
493 SU = WorkList.back();
494 WorkList.pop_back();
495 Visited.set(SU->NodeNum);
496 for (int I = SU->Succs.size()-1; I >= 0; --I) {
497 int s = SU->Succs[I].getSUnit()->NodeNum;
498 if (Node2Index[s] == UpperBound) {
499 HasLoop = true;
500 return;
501 }
502 // Visit successors if not already and in affected region.
503 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
504 WorkList.push_back(SU->Succs[I].getSUnit());
505 }
506 }
507 } while (!WorkList.empty());
508 }
509
510 /// Shift - Renumber the nodes so that the topological ordering is
511 /// preserved.
Shift(BitVector & Visited,int LowerBound,int UpperBound)512 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
513 int UpperBound) {
514 std::vector<int> L;
515 int shift = 0;
516 int i;
517
518 for (i = LowerBound; i <= UpperBound; ++i) {
519 // w is node at topological index i.
520 int w = Index2Node[i];
521 if (Visited.test(w)) {
522 // Unmark.
523 Visited.reset(w);
524 L.push_back(w);
525 shift = shift + 1;
526 } else {
527 Allocate(w, i - shift);
528 }
529 }
530
531 for (unsigned j = 0; j < L.size(); ++j) {
532 Allocate(L[j], i - shift);
533 i = i + 1;
534 }
535 }
536
537
538 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
539 /// create a cycle.
WillCreateCycle(SUnit * SU,SUnit * TargetSU)540 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
541 if (IsReachable(TargetSU, SU))
542 return true;
543 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
544 I != E; ++I)
545 if (I->isAssignedRegDep() &&
546 IsReachable(TargetSU, I->getSUnit()))
547 return true;
548 return false;
549 }
550
551 /// IsReachable - Checks if SU is reachable from TargetSU.
IsReachable(const SUnit * SU,const SUnit * TargetSU)552 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
553 const SUnit *TargetSU) {
554 // If insertion of the edge SU->TargetSU would create a cycle
555 // then there is a path from TargetSU to SU.
556 int UpperBound, LowerBound;
557 LowerBound = Node2Index[TargetSU->NodeNum];
558 UpperBound = Node2Index[SU->NodeNum];
559 bool HasLoop = false;
560 // Is Ord(TargetSU) < Ord(SU) ?
561 if (LowerBound < UpperBound) {
562 Visited.reset();
563 // There may be a path from TargetSU to SU. Check for it.
564 DFS(TargetSU, UpperBound, HasLoop);
565 }
566 return HasLoop;
567 }
568
569 /// Allocate - assign the topological index to the node n.
Allocate(int n,int index)570 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
571 Node2Index[n] = index;
572 Index2Node[index] = n;
573 }
574
575 ScheduleDAGTopologicalSort::
ScheduleDAGTopologicalSort(std::vector<SUnit> & sunits)576 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
577
~ScheduleHazardRecognizer()578 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}
579