1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
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"
29 static cl::opt<bool> StressSchedOpt(
30 "stress-sched", cl::Hidden, cl::init(false),
31 cl::desc("Stress test instruction scheduling"));
34 void SchedulingPriorityQueue::anchor() { }
36 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
38 TII(TM.getInstrInfo()),
39 TRI(TM.getRegisterInfo()),
40 MF(mf), MRI(mf.getRegInfo()),
43 StressSched = StressSchedOpt;
47 ScheduleDAG::~ScheduleDAG() {}
49 /// getInstrDesc helper to handle SDNodes.
50 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
51 if (!Node || !Node->isMachineOpcode()) return NULL;
52 return &TII->get(Node->getMachineOpcode());
55 /// Run - perform scheduling.
57 void ScheduleDAG::Run(MachineBasicBlock *bb,
58 MachineBasicBlock::iterator insertPos) {
60 InsertPos = insertPos;
70 /// addPred - This adds the specified edge as a pred of the current node if
71 /// not already. It also adds the current node as a successor of the
73 bool SUnit::addPred(const SDep &D) {
74 // If this node already has this depenence, don't add a redundant one.
75 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
79 // Now add a corresponding succ to N.
82 SUnit *N = D.getSUnit();
83 // Update the bookkeeping.
84 if (D.getKind() == SDep::Data) {
85 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
86 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
90 if (!N->isScheduled) {
91 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
95 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
99 N->Succs.push_back(P);
100 if (P.getLatency() != 0) {
101 this->setDepthDirty();
107 /// removePred - This removes the specified edge as a pred of the current
108 /// node if it exists. It also removes the current node as a successor of
109 /// the specified node.
110 void SUnit::removePred(const SDep &D) {
111 // Find the matching predecessor.
112 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
115 bool FoundSucc = false;
116 // Find the corresponding successor in N.
119 SUnit *N = D.getSUnit();
120 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
121 EE = N->Succs.end(); II != EE; ++II)
127 assert(FoundSucc && "Mismatching preds / succs lists!");
130 // Update the bookkeeping.
131 if (P.getKind() == SDep::Data) {
132 assert(NumPreds > 0 && "NumPreds will underflow!");
133 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
137 if (!N->isScheduled) {
138 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
142 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
145 if (P.getLatency() != 0) {
146 this->setDepthDirty();
153 void SUnit::setDepthDirty() {
154 if (!isDepthCurrent) return;
155 SmallVector<SUnit*, 8> WorkList;
156 WorkList.push_back(this);
158 SUnit *SU = WorkList.pop_back_val();
159 SU->isDepthCurrent = false;
160 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
161 E = SU->Succs.end(); I != E; ++I) {
162 SUnit *SuccSU = I->getSUnit();
163 if (SuccSU->isDepthCurrent)
164 WorkList.push_back(SuccSU);
166 } while (!WorkList.empty());
169 void SUnit::setHeightDirty() {
170 if (!isHeightCurrent) return;
171 SmallVector<SUnit*, 8> WorkList;
172 WorkList.push_back(this);
174 SUnit *SU = WorkList.pop_back_val();
175 SU->isHeightCurrent = false;
176 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
177 E = SU->Preds.end(); I != E; ++I) {
178 SUnit *PredSU = I->getSUnit();
179 if (PredSU->isHeightCurrent)
180 WorkList.push_back(PredSU);
182 } while (!WorkList.empty());
185 /// setDepthToAtLeast - Update this node's successors to reflect the
186 /// fact that this node's depth just increased.
188 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
189 if (NewDepth <= getDepth())
193 isDepthCurrent = true;
196 /// setHeightToAtLeast - Update this node's predecessors to reflect the
197 /// fact that this node's height just increased.
199 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
200 if (NewHeight <= getHeight())
204 isHeightCurrent = true;
207 /// ComputeDepth - Calculate the maximal path from the node to the exit.
209 void SUnit::ComputeDepth() {
210 SmallVector<SUnit*, 8> WorkList;
211 WorkList.push_back(this);
213 SUnit *Cur = WorkList.back();
216 unsigned MaxPredDepth = 0;
217 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
218 E = Cur->Preds.end(); I != E; ++I) {
219 SUnit *PredSU = I->getSUnit();
220 if (PredSU->isDepthCurrent)
221 MaxPredDepth = std::max(MaxPredDepth,
222 PredSU->Depth + I->getLatency());
225 WorkList.push_back(PredSU);
231 if (MaxPredDepth != Cur->Depth) {
232 Cur->setDepthDirty();
233 Cur->Depth = MaxPredDepth;
235 Cur->isDepthCurrent = true;
237 } while (!WorkList.empty());
240 /// ComputeHeight - Calculate the maximal path from the node to the entry.
242 void SUnit::ComputeHeight() {
243 SmallVector<SUnit*, 8> WorkList;
244 WorkList.push_back(this);
246 SUnit *Cur = WorkList.back();
249 unsigned MaxSuccHeight = 0;
250 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
251 E = Cur->Succs.end(); I != E; ++I) {
252 SUnit *SuccSU = I->getSUnit();
253 if (SuccSU->isHeightCurrent)
254 MaxSuccHeight = std::max(MaxSuccHeight,
255 SuccSU->Height + I->getLatency());
258 WorkList.push_back(SuccSU);
264 if (MaxSuccHeight != Cur->Height) {
265 Cur->setHeightDirty();
266 Cur->Height = MaxSuccHeight;
268 Cur->isHeightCurrent = true;
270 } while (!WorkList.empty());
273 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
274 /// a group of nodes flagged together.
275 void SUnit::dump(const ScheduleDAG *G) const {
276 dbgs() << "SU(" << NodeNum << "): ";
280 void SUnit::dumpAll(const ScheduleDAG *G) const {
283 dbgs() << " # preds left : " << NumPredsLeft << "\n";
284 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
285 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
286 dbgs() << " Latency : " << Latency << "\n";
287 dbgs() << " Depth : " << Depth << "\n";
288 dbgs() << " Height : " << Height << "\n";
290 if (Preds.size() != 0) {
291 dbgs() << " Predecessors:\n";
292 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
295 switch (I->getKind()) {
296 case SDep::Data: dbgs() << "val "; break;
297 case SDep::Anti: dbgs() << "anti"; break;
298 case SDep::Output: dbgs() << "out "; break;
299 case SDep::Order: dbgs() << "ch "; break;
301 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
302 if (I->isArtificial())
304 dbgs() << ": Latency=" << I->getLatency();
305 if (I->isAssignedRegDep())
306 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
310 if (Succs.size() != 0) {
311 dbgs() << " Successors:\n";
312 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
315 switch (I->getKind()) {
316 case SDep::Data: dbgs() << "val "; break;
317 case SDep::Anti: dbgs() << "anti"; break;
318 case SDep::Output: dbgs() << "out "; break;
319 case SDep::Order: dbgs() << "ch "; break;
321 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
322 if (I->isArtificial())
324 dbgs() << ": Latency=" << I->getLatency();
332 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
333 /// their state is consistent. Return the number of scheduled nodes.
335 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
336 bool AnyNotSched = false;
337 unsigned DeadNodes = 0;
338 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
339 if (!SUnits[i].isScheduled) {
340 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
345 dbgs() << "*** Scheduling failed! ***\n";
346 SUnits[i].dump(this);
347 dbgs() << "has not been scheduled!\n";
350 if (SUnits[i].isScheduled &&
351 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
354 dbgs() << "*** Scheduling failed! ***\n";
355 SUnits[i].dump(this);
356 dbgs() << "has an unexpected "
357 << (isBottomUp ? "Height" : "Depth") << " value!\n";
361 if (SUnits[i].NumSuccsLeft != 0) {
363 dbgs() << "*** Scheduling failed! ***\n";
364 SUnits[i].dump(this);
365 dbgs() << "has successors left!\n";
369 if (SUnits[i].NumPredsLeft != 0) {
371 dbgs() << "*** Scheduling failed! ***\n";
372 SUnits[i].dump(this);
373 dbgs() << "has predecessors left!\n";
378 assert(!AnyNotSched);
379 return SUnits.size() - DeadNodes;
383 /// InitDAGTopologicalSorting - create the initial topological
384 /// ordering from the DAG to be scheduled.
386 /// The idea of the algorithm is taken from
387 /// "Online algorithms for managing the topological order of
388 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
389 /// This is the MNR algorithm, which was first introduced by
390 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
391 /// "Maintaining a topological order under edge insertions".
393 /// Short description of the algorithm:
395 /// Topological ordering, ord, of a DAG maps each node to a topological
396 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
398 /// This means that if there is a path from the node X to the node Z,
399 /// then ord(X) < ord(Z).
401 /// This property can be used to check for reachability of nodes:
402 /// if Z is reachable from X, then an insertion of the edge Z->X would
405 /// The algorithm first computes a topological ordering for the DAG by
406 /// initializing the Index2Node and Node2Index arrays and then tries to keep
407 /// the ordering up-to-date after edge insertions by reordering the DAG.
409 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
410 /// the nodes reachable from Y, and then shifts them using Shift to lie
411 /// immediately after X in Index2Node.
412 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
413 unsigned DAGSize = SUnits.size();
414 std::vector<SUnit*> WorkList;
415 WorkList.reserve(DAGSize);
417 Index2Node.resize(DAGSize);
418 Node2Index.resize(DAGSize);
420 // Initialize the data structures.
421 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
422 SUnit *SU = &SUnits[i];
423 int NodeNum = SU->NodeNum;
424 unsigned Degree = SU->Succs.size();
425 // Temporarily use the Node2Index array as scratch space for degree counts.
426 Node2Index[NodeNum] = Degree;
428 // Is it a node without dependencies?
430 assert(SU->Succs.empty() && "SUnit should have no successors");
431 // Collect leaf nodes.
432 WorkList.push_back(SU);
437 while (!WorkList.empty()) {
438 SUnit *SU = WorkList.back();
440 Allocate(SU->NodeNum, --Id);
441 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
443 SUnit *SU = I->getSUnit();
444 if (!--Node2Index[SU->NodeNum])
445 // If all dependencies of the node are processed already,
446 // then the node can be computed now.
447 WorkList.push_back(SU);
451 Visited.resize(DAGSize);
454 // Check correctness of the ordering
455 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
456 SUnit *SU = &SUnits[i];
457 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
459 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
460 "Wrong topological sorting");
466 /// AddPred - Updates the topological ordering to accommodate an edge
467 /// to be added from SUnit X to SUnit Y.
468 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
469 int UpperBound, LowerBound;
470 LowerBound = Node2Index[Y->NodeNum];
471 UpperBound = Node2Index[X->NodeNum];
472 bool HasLoop = false;
473 // Is Ord(X) < Ord(Y) ?
474 if (LowerBound < UpperBound) {
475 // Update the topological order.
477 DFS(Y, UpperBound, HasLoop);
478 assert(!HasLoop && "Inserted edge creates a loop!");
479 // Recompute topological indexes.
480 Shift(Visited, LowerBound, UpperBound);
484 /// RemovePred - Updates the topological ordering to accommodate an
485 /// an edge to be removed from the specified node N from the predecessors
486 /// of the current node M.
487 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
488 // InitDAGTopologicalSorting();
491 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
492 /// all nodes affected by the edge insertion. These nodes will later get new
493 /// topological indexes by means of the Shift method.
494 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
496 std::vector<const SUnit*> WorkList;
497 WorkList.reserve(SUnits.size());
499 WorkList.push_back(SU);
501 SU = WorkList.back();
503 Visited.set(SU->NodeNum);
504 for (int I = SU->Succs.size()-1; I >= 0; --I) {
505 int s = SU->Succs[I].getSUnit()->NodeNum;
506 if (Node2Index[s] == UpperBound) {
510 // Visit successors if not already and in affected region.
511 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
512 WorkList.push_back(SU->Succs[I].getSUnit());
515 } while (!WorkList.empty());
518 /// Shift - Renumber the nodes so that the topological ordering is
520 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
526 for (i = LowerBound; i <= UpperBound; ++i) {
527 // w is node at topological index i.
528 int w = Index2Node[i];
529 if (Visited.test(w)) {
535 Allocate(w, i - shift);
539 for (unsigned j = 0; j < L.size(); ++j) {
540 Allocate(L[j], i - shift);
546 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
548 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
549 if (IsReachable(TargetSU, SU))
551 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
553 if (I->isAssignedRegDep() &&
554 IsReachable(TargetSU, I->getSUnit()))
559 /// IsReachable - Checks if SU is reachable from TargetSU.
560 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
561 const SUnit *TargetSU) {
562 // If insertion of the edge SU->TargetSU would create a cycle
563 // then there is a path from TargetSU to SU.
564 int UpperBound, LowerBound;
565 LowerBound = Node2Index[TargetSU->NodeNum];
566 UpperBound = Node2Index[SU->NodeNum];
567 bool HasLoop = false;
568 // Is Ord(TargetSU) < Ord(SU) ?
569 if (LowerBound < UpperBound) {
571 // There may be a path from TargetSU to SU. Check for it.
572 DFS(TargetSU, UpperBound, HasLoop);
577 /// Allocate - assign the topological index to the node n.
578 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
579 Node2Index[n] = index;
580 Index2Node[index] = n;
583 ScheduleDAGTopologicalSort::
584 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
586 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}