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/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.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 /// Clear the DAG state (e.g. between scheduling regions).
50 void ScheduleDAG::clearDAG() {
56 /// getInstrDesc helper to handle SDNodes.
57 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
58 if (!Node || !Node->isMachineOpcode()) return NULL;
59 return &TII->get(Node->getMachineOpcode());
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
65 bool SUnit::addPred(const SDep &D, bool Required) {
66 // If this node already has this depenence, don't add a redundant one.
67 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
69 // Zero-latency weak edges may be added purely for heuristic ordering. Don't
70 // add them if another kind of edge already exists.
71 if (!Required && I->getSUnit() == D.getSUnit())
74 // Extend the latency if needed. Equivalent to removePred(I) + addPred(D).
75 if (I->getLatency() < D.getLatency()) {
76 SUnit *PredSU = I->getSUnit();
77 // Find the corresponding successor in N.
79 ForwardD.setSUnit(this);
80 for (SmallVector<SDep, 4>::iterator II = PredSU->Succs.begin(),
81 EE = PredSU->Succs.end(); II != EE; ++II) {
82 if (*II == ForwardD) {
83 II->setLatency(D.getLatency());
87 I->setLatency(D.getLatency());
92 // Now add a corresponding succ to N.
95 SUnit *N = D.getSUnit();
96 // Update the bookkeeping.
97 if (D.getKind() == SDep::Data) {
98 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
99 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
103 if (!N->isScheduled) {
108 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
117 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
122 N->Succs.push_back(P);
123 if (P.getLatency() != 0) {
124 this->setDepthDirty();
130 /// removePred - This removes the specified edge as a pred of the current
131 /// node if it exists. It also removes the current node as a successor of
132 /// the specified node.
133 void SUnit::removePred(const SDep &D) {
134 // Find the matching predecessor.
135 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
138 bool FoundSucc = false;
139 // Find the corresponding successor in N.
142 SUnit *N = D.getSUnit();
143 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
144 EE = N->Succs.end(); II != EE; ++II)
150 assert(FoundSucc && "Mismatching preds / succs lists!");
153 // Update the bookkeeping.
154 if (P.getKind() == SDep::Data) {
155 assert(NumPreds > 0 && "NumPreds will underflow!");
156 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
160 if (!N->isScheduled) {
164 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
172 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
176 if (P.getLatency() != 0) {
177 this->setDepthDirty();
184 void SUnit::setDepthDirty() {
185 if (!isDepthCurrent) return;
186 SmallVector<SUnit*, 8> WorkList;
187 WorkList.push_back(this);
189 SUnit *SU = WorkList.pop_back_val();
190 SU->isDepthCurrent = false;
191 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
192 E = SU->Succs.end(); I != E; ++I) {
193 SUnit *SuccSU = I->getSUnit();
194 if (SuccSU->isDepthCurrent)
195 WorkList.push_back(SuccSU);
197 } while (!WorkList.empty());
200 void SUnit::setHeightDirty() {
201 if (!isHeightCurrent) return;
202 SmallVector<SUnit*, 8> WorkList;
203 WorkList.push_back(this);
205 SUnit *SU = WorkList.pop_back_val();
206 SU->isHeightCurrent = false;
207 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
208 E = SU->Preds.end(); I != E; ++I) {
209 SUnit *PredSU = I->getSUnit();
210 if (PredSU->isHeightCurrent)
211 WorkList.push_back(PredSU);
213 } while (!WorkList.empty());
216 /// setDepthToAtLeast - Update this node's successors to reflect the
217 /// fact that this node's depth just increased.
219 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
220 if (NewDepth <= getDepth())
224 isDepthCurrent = true;
227 /// setHeightToAtLeast - Update this node's predecessors to reflect the
228 /// fact that this node's height just increased.
230 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
231 if (NewHeight <= getHeight())
235 isHeightCurrent = true;
238 /// ComputeDepth - Calculate the maximal path from the node to the exit.
240 void SUnit::ComputeDepth() {
241 SmallVector<SUnit*, 8> WorkList;
242 WorkList.push_back(this);
244 SUnit *Cur = WorkList.back();
247 unsigned MaxPredDepth = 0;
248 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
249 E = Cur->Preds.end(); I != E; ++I) {
250 SUnit *PredSU = I->getSUnit();
251 if (PredSU->isDepthCurrent)
252 MaxPredDepth = std::max(MaxPredDepth,
253 PredSU->Depth + I->getLatency());
256 WorkList.push_back(PredSU);
262 if (MaxPredDepth != Cur->Depth) {
263 Cur->setDepthDirty();
264 Cur->Depth = MaxPredDepth;
266 Cur->isDepthCurrent = true;
268 } while (!WorkList.empty());
271 /// ComputeHeight - Calculate the maximal path from the node to the entry.
273 void SUnit::ComputeHeight() {
274 SmallVector<SUnit*, 8> WorkList;
275 WorkList.push_back(this);
277 SUnit *Cur = WorkList.back();
280 unsigned MaxSuccHeight = 0;
281 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
282 E = Cur->Succs.end(); I != E; ++I) {
283 SUnit *SuccSU = I->getSUnit();
284 if (SuccSU->isHeightCurrent)
285 MaxSuccHeight = std::max(MaxSuccHeight,
286 SuccSU->Height + I->getLatency());
289 WorkList.push_back(SuccSU);
295 if (MaxSuccHeight != Cur->Height) {
296 Cur->setHeightDirty();
297 Cur->Height = MaxSuccHeight;
299 Cur->isHeightCurrent = true;
301 } while (!WorkList.empty());
304 void SUnit::biasCriticalPath() {
308 SUnit::pred_iterator BestI = Preds.begin();
309 unsigned MaxDepth = BestI->getSUnit()->getDepth();
310 for (SUnit::pred_iterator
311 I = llvm::next(BestI), E = Preds.end(); I != E; ++I) {
312 if (I->getKind() == SDep::Data && I->getSUnit()->getDepth() > MaxDepth)
315 if (BestI != Preds.begin())
316 std::swap(*Preds.begin(), *BestI);
319 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
320 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
321 /// a group of nodes flagged together.
322 void SUnit::dump(const ScheduleDAG *G) const {
323 dbgs() << "SU(" << NodeNum << "): ";
327 void SUnit::dumpAll(const ScheduleDAG *G) const {
330 dbgs() << " # preds left : " << NumPredsLeft << "\n";
331 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
333 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
335 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
336 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
337 dbgs() << " Latency : " << Latency << "\n";
338 dbgs() << " Depth : " << Depth << "\n";
339 dbgs() << " Height : " << Height << "\n";
341 if (Preds.size() != 0) {
342 dbgs() << " Predecessors:\n";
343 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
346 switch (I->getKind()) {
347 case SDep::Data: dbgs() << "val "; break;
348 case SDep::Anti: dbgs() << "anti"; break;
349 case SDep::Output: dbgs() << "out "; break;
350 case SDep::Order: dbgs() << "ch "; break;
352 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
353 if (I->isArtificial())
355 dbgs() << ": Latency=" << I->getLatency();
356 if (I->isAssignedRegDep())
357 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
361 if (Succs.size() != 0) {
362 dbgs() << " Successors:\n";
363 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
366 switch (I->getKind()) {
367 case SDep::Data: dbgs() << "val "; break;
368 case SDep::Anti: dbgs() << "anti"; break;
369 case SDep::Output: dbgs() << "out "; break;
370 case SDep::Order: dbgs() << "ch "; break;
372 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
373 if (I->isArtificial())
375 dbgs() << ": Latency=" << I->getLatency();
384 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
385 /// their state is consistent. Return the number of scheduled nodes.
387 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
388 bool AnyNotSched = false;
389 unsigned DeadNodes = 0;
390 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
391 if (!SUnits[i].isScheduled) {
392 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
397 dbgs() << "*** Scheduling failed! ***\n";
398 SUnits[i].dump(this);
399 dbgs() << "has not been scheduled!\n";
402 if (SUnits[i].isScheduled &&
403 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
406 dbgs() << "*** Scheduling failed! ***\n";
407 SUnits[i].dump(this);
408 dbgs() << "has an unexpected "
409 << (isBottomUp ? "Height" : "Depth") << " value!\n";
413 if (SUnits[i].NumSuccsLeft != 0) {
415 dbgs() << "*** Scheduling failed! ***\n";
416 SUnits[i].dump(this);
417 dbgs() << "has successors left!\n";
421 if (SUnits[i].NumPredsLeft != 0) {
423 dbgs() << "*** Scheduling failed! ***\n";
424 SUnits[i].dump(this);
425 dbgs() << "has predecessors left!\n";
430 assert(!AnyNotSched);
431 return SUnits.size() - DeadNodes;
435 /// InitDAGTopologicalSorting - create the initial topological
436 /// ordering from the DAG to be scheduled.
438 /// The idea of the algorithm is taken from
439 /// "Online algorithms for managing the topological order of
440 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
441 /// This is the MNR algorithm, which was first introduced by
442 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
443 /// "Maintaining a topological order under edge insertions".
445 /// Short description of the algorithm:
447 /// Topological ordering, ord, of a DAG maps each node to a topological
448 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
450 /// This means that if there is a path from the node X to the node Z,
451 /// then ord(X) < ord(Z).
453 /// This property can be used to check for reachability of nodes:
454 /// if Z is reachable from X, then an insertion of the edge Z->X would
457 /// The algorithm first computes a topological ordering for the DAG by
458 /// initializing the Index2Node and Node2Index arrays and then tries to keep
459 /// the ordering up-to-date after edge insertions by reordering the DAG.
461 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
462 /// the nodes reachable from Y, and then shifts them using Shift to lie
463 /// immediately after X in Index2Node.
464 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
465 unsigned DAGSize = SUnits.size();
466 std::vector<SUnit*> WorkList;
467 WorkList.reserve(DAGSize);
469 Index2Node.resize(DAGSize);
470 Node2Index.resize(DAGSize);
472 // Initialize the data structures.
474 WorkList.push_back(ExitSU);
475 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
476 SUnit *SU = &SUnits[i];
477 int NodeNum = SU->NodeNum;
478 unsigned Degree = SU->Succs.size();
479 // Temporarily use the Node2Index array as scratch space for degree counts.
480 Node2Index[NodeNum] = Degree;
482 // Is it a node without dependencies?
484 assert(SU->Succs.empty() && "SUnit should have no successors");
485 // Collect leaf nodes.
486 WorkList.push_back(SU);
491 while (!WorkList.empty()) {
492 SUnit *SU = WorkList.back();
494 if (SU->NodeNum < DAGSize)
495 Allocate(SU->NodeNum, --Id);
496 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
498 SUnit *SU = I->getSUnit();
499 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
500 // If all dependencies of the node are processed already,
501 // then the node can be computed now.
502 WorkList.push_back(SU);
506 Visited.resize(DAGSize);
509 // Check correctness of the ordering
510 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
511 SUnit *SU = &SUnits[i];
512 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
514 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
515 "Wrong topological sorting");
521 /// AddPred - Updates the topological ordering to accommodate an edge
522 /// to be added from SUnit X to SUnit Y.
523 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
524 int UpperBound, LowerBound;
525 LowerBound = Node2Index[Y->NodeNum];
526 UpperBound = Node2Index[X->NodeNum];
527 bool HasLoop = false;
528 // Is Ord(X) < Ord(Y) ?
529 if (LowerBound < UpperBound) {
530 // Update the topological order.
532 DFS(Y, UpperBound, HasLoop);
533 assert(!HasLoop && "Inserted edge creates a loop!");
534 // Recompute topological indexes.
535 Shift(Visited, LowerBound, UpperBound);
539 /// RemovePred - Updates the topological ordering to accommodate an
540 /// an edge to be removed from the specified node N from the predecessors
541 /// of the current node M.
542 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
543 // InitDAGTopologicalSorting();
546 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
547 /// all nodes affected by the edge insertion. These nodes will later get new
548 /// topological indexes by means of the Shift method.
549 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
551 std::vector<const SUnit*> WorkList;
552 WorkList.reserve(SUnits.size());
554 WorkList.push_back(SU);
556 SU = WorkList.back();
558 Visited.set(SU->NodeNum);
559 for (int I = SU->Succs.size()-1; I >= 0; --I) {
560 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
561 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
562 if (s >= Node2Index.size())
564 if (Node2Index[s] == UpperBound) {
568 // Visit successors if not already and in affected region.
569 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
570 WorkList.push_back(SU->Succs[I].getSUnit());
573 } while (!WorkList.empty());
576 /// Shift - Renumber the nodes so that the topological ordering is
578 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
584 for (i = LowerBound; i <= UpperBound; ++i) {
585 // w is node at topological index i.
586 int w = Index2Node[i];
587 if (Visited.test(w)) {
593 Allocate(w, i - shift);
597 for (unsigned j = 0; j < L.size(); ++j) {
598 Allocate(L[j], i - shift);
604 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
605 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
606 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
607 // Is SU reachable from TargetSU via successor edges?
608 if (IsReachable(SU, TargetSU))
610 for (SUnit::pred_iterator
611 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
612 if (I->isAssignedRegDep() &&
613 IsReachable(SU, I->getSUnit()))
618 /// IsReachable - Checks if SU is reachable from TargetSU.
619 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
620 const SUnit *TargetSU) {
621 // If insertion of the edge SU->TargetSU would create a cycle
622 // then there is a path from TargetSU to SU.
623 int UpperBound, LowerBound;
624 LowerBound = Node2Index[TargetSU->NodeNum];
625 UpperBound = Node2Index[SU->NodeNum];
626 bool HasLoop = false;
627 // Is Ord(TargetSU) < Ord(SU) ?
628 if (LowerBound < UpperBound) {
630 // There may be a path from TargetSU to SU. Check for it.
631 DFS(TargetSU, UpperBound, HasLoop);
636 /// Allocate - assign the topological index to the node n.
637 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
638 Node2Index[n] = index;
639 Index2Node[index] = n;
642 ScheduleDAGTopologicalSort::
643 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
644 : SUnits(sunits), ExitSU(exitsu) {}
646 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}