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 #include "llvm/CodeGen/ScheduleDAG.h"
16 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
17 #include "llvm/CodeGen/SelectionDAGNodes.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
27 #define DEBUG_TYPE "pre-RA-sched"
30 static cl::opt<bool> StressSchedOpt(
31 "stress-sched", cl::Hidden, cl::init(false),
32 cl::desc("Stress test instruction scheduling"));
35 void SchedulingPriorityQueue::anchor() { }
37 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
39 TII(TM.getInstrInfo()),
40 TRI(TM.getRegisterInfo()),
41 MF(mf), MRI(mf.getRegInfo()),
44 StressSched = StressSchedOpt;
48 ScheduleDAG::~ScheduleDAG() {}
50 /// Clear the DAG state (e.g. between scheduling regions).
51 void ScheduleDAG::clearDAG() {
57 /// getInstrDesc helper to handle SDNodes.
58 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
59 if (!Node || !Node->isMachineOpcode()) return nullptr;
60 return &TII->get(Node->getMachineOpcode());
63 /// addPred - This adds the specified edge as a pred of the current node if
64 /// not already. It also adds the current node as a successor of the
66 bool SUnit::addPred(const SDep &D, bool Required) {
67 // If this node already has this dependence, don't add a redundant one.
68 for (SmallVectorImpl<SDep>::iterator I = Preds.begin(), E = Preds.end();
70 // Zero-latency weak edges may be added purely for heuristic ordering. Don't
71 // add them if another kind of edge already exists.
72 if (!Required && I->getSUnit() == D.getSUnit())
75 // Extend the latency if needed. Equivalent to removePred(I) + addPred(D).
76 if (I->getLatency() < D.getLatency()) {
77 SUnit *PredSU = I->getSUnit();
78 // Find the corresponding successor in N.
80 ForwardD.setSUnit(this);
81 for (SmallVectorImpl<SDep>::iterator II = PredSU->Succs.begin(),
82 EE = PredSU->Succs.end(); II != EE; ++II) {
83 if (*II == ForwardD) {
84 II->setLatency(D.getLatency());
88 I->setLatency(D.getLatency());
93 // Now add a corresponding succ to N.
96 SUnit *N = D.getSUnit();
97 // Update the bookkeeping.
98 if (D.getKind() == SDep::Data) {
99 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
100 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
104 if (!N->isScheduled) {
109 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
118 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
123 N->Succs.push_back(P);
124 if (P.getLatency() != 0) {
125 this->setDepthDirty();
131 /// removePred - This removes the specified edge as a pred of the current
132 /// node if it exists. It also removes the current node as a successor of
133 /// the specified node.
134 void SUnit::removePred(const SDep &D) {
135 // Find the matching predecessor.
136 for (SmallVectorImpl<SDep>::iterator I = Preds.begin(), E = Preds.end();
139 // Find the corresponding successor in N.
142 SUnit *N = D.getSUnit();
143 SmallVectorImpl<SDep>::iterator Succ = std::find(N->Succs.begin(),
145 assert(Succ != N->Succs.end() && "Mismatching preds / succs lists!");
146 N->Succs.erase(Succ);
148 // Update the bookkeeping.
149 if (P.getKind() == SDep::Data) {
150 assert(NumPreds > 0 && "NumPreds will underflow!");
151 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
155 if (!N->isScheduled) {
159 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
167 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
171 if (P.getLatency() != 0) {
172 this->setDepthDirty();
179 void SUnit::setDepthDirty() {
180 if (!isDepthCurrent) return;
181 SmallVector<SUnit*, 8> WorkList;
182 WorkList.push_back(this);
184 SUnit *SU = WorkList.pop_back_val();
185 SU->isDepthCurrent = false;
186 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
187 E = SU->Succs.end(); I != E; ++I) {
188 SUnit *SuccSU = I->getSUnit();
189 if (SuccSU->isDepthCurrent)
190 WorkList.push_back(SuccSU);
192 } while (!WorkList.empty());
195 void SUnit::setHeightDirty() {
196 if (!isHeightCurrent) return;
197 SmallVector<SUnit*, 8> WorkList;
198 WorkList.push_back(this);
200 SUnit *SU = WorkList.pop_back_val();
201 SU->isHeightCurrent = false;
202 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
203 E = SU->Preds.end(); I != E; ++I) {
204 SUnit *PredSU = I->getSUnit();
205 if (PredSU->isHeightCurrent)
206 WorkList.push_back(PredSU);
208 } while (!WorkList.empty());
211 /// setDepthToAtLeast - Update this node's successors to reflect the
212 /// fact that this node's depth just increased.
214 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
215 if (NewDepth <= getDepth())
219 isDepthCurrent = true;
222 /// setHeightToAtLeast - Update this node's predecessors to reflect the
223 /// fact that this node's height just increased.
225 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
226 if (NewHeight <= getHeight())
230 isHeightCurrent = true;
233 /// ComputeDepth - Calculate the maximal path from the node to the exit.
235 void SUnit::ComputeDepth() {
236 SmallVector<SUnit*, 8> WorkList;
237 WorkList.push_back(this);
239 SUnit *Cur = WorkList.back();
242 unsigned MaxPredDepth = 0;
243 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
244 E = Cur->Preds.end(); I != E; ++I) {
245 SUnit *PredSU = I->getSUnit();
246 if (PredSU->isDepthCurrent)
247 MaxPredDepth = std::max(MaxPredDepth,
248 PredSU->Depth + I->getLatency());
251 WorkList.push_back(PredSU);
257 if (MaxPredDepth != Cur->Depth) {
258 Cur->setDepthDirty();
259 Cur->Depth = MaxPredDepth;
261 Cur->isDepthCurrent = true;
263 } while (!WorkList.empty());
266 /// ComputeHeight - Calculate the maximal path from the node to the entry.
268 void SUnit::ComputeHeight() {
269 SmallVector<SUnit*, 8> WorkList;
270 WorkList.push_back(this);
272 SUnit *Cur = WorkList.back();
275 unsigned MaxSuccHeight = 0;
276 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
277 E = Cur->Succs.end(); I != E; ++I) {
278 SUnit *SuccSU = I->getSUnit();
279 if (SuccSU->isHeightCurrent)
280 MaxSuccHeight = std::max(MaxSuccHeight,
281 SuccSU->Height + I->getLatency());
284 WorkList.push_back(SuccSU);
290 if (MaxSuccHeight != Cur->Height) {
291 Cur->setHeightDirty();
292 Cur->Height = MaxSuccHeight;
294 Cur->isHeightCurrent = true;
296 } while (!WorkList.empty());
299 void SUnit::biasCriticalPath() {
303 SUnit::pred_iterator BestI = Preds.begin();
304 unsigned MaxDepth = BestI->getSUnit()->getDepth();
305 for (SUnit::pred_iterator I = std::next(BestI), E = Preds.end(); I != E;
307 if (I->getKind() == SDep::Data && I->getSUnit()->getDepth() > MaxDepth)
310 if (BestI != Preds.begin())
311 std::swap(*Preds.begin(), *BestI);
314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
315 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
316 /// a group of nodes flagged together.
317 void SUnit::dump(const ScheduleDAG *G) const {
318 dbgs() << "SU(" << NodeNum << "): ";
322 void SUnit::dumpAll(const ScheduleDAG *G) const {
325 dbgs() << " # preds left : " << NumPredsLeft << "\n";
326 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
328 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
330 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
331 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
332 dbgs() << " Latency : " << Latency << "\n";
333 dbgs() << " Depth : " << getDepth() << "\n";
334 dbgs() << " Height : " << getHeight() << "\n";
336 if (Preds.size() != 0) {
337 dbgs() << " Predecessors:\n";
338 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
341 switch (I->getKind()) {
342 case SDep::Data: dbgs() << "val "; break;
343 case SDep::Anti: dbgs() << "anti"; break;
344 case SDep::Output: dbgs() << "out "; break;
345 case SDep::Order: dbgs() << "ch "; break;
347 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
348 if (I->isArtificial())
350 dbgs() << ": Latency=" << I->getLatency();
351 if (I->isAssignedRegDep())
352 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
356 if (Succs.size() != 0) {
357 dbgs() << " Successors:\n";
358 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
361 switch (I->getKind()) {
362 case SDep::Data: dbgs() << "val "; break;
363 case SDep::Anti: dbgs() << "anti"; break;
364 case SDep::Output: dbgs() << "out "; break;
365 case SDep::Order: dbgs() << "ch "; break;
367 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
368 if (I->isArtificial())
370 dbgs() << ": Latency=" << I->getLatency();
371 if (I->isAssignedRegDep())
372 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
381 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
382 /// their state is consistent. Return the number of scheduled nodes.
384 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
385 bool AnyNotSched = false;
386 unsigned DeadNodes = 0;
387 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
388 if (!SUnits[i].isScheduled) {
389 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
394 dbgs() << "*** Scheduling failed! ***\n";
395 SUnits[i].dump(this);
396 dbgs() << "has not been scheduled!\n";
399 if (SUnits[i].isScheduled &&
400 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
403 dbgs() << "*** Scheduling failed! ***\n";
404 SUnits[i].dump(this);
405 dbgs() << "has an unexpected "
406 << (isBottomUp ? "Height" : "Depth") << " value!\n";
410 if (SUnits[i].NumSuccsLeft != 0) {
412 dbgs() << "*** Scheduling failed! ***\n";
413 SUnits[i].dump(this);
414 dbgs() << "has successors left!\n";
418 if (SUnits[i].NumPredsLeft != 0) {
420 dbgs() << "*** Scheduling failed! ***\n";
421 SUnits[i].dump(this);
422 dbgs() << "has predecessors left!\n";
427 assert(!AnyNotSched);
428 return SUnits.size() - DeadNodes;
432 /// InitDAGTopologicalSorting - create the initial topological
433 /// ordering from the DAG to be scheduled.
435 /// The idea of the algorithm is taken from
436 /// "Online algorithms for managing the topological order of
437 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
438 /// This is the MNR algorithm, which was first introduced by
439 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
440 /// "Maintaining a topological order under edge insertions".
442 /// Short description of the algorithm:
444 /// Topological ordering, ord, of a DAG maps each node to a topological
445 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
447 /// This means that if there is a path from the node X to the node Z,
448 /// then ord(X) < ord(Z).
450 /// This property can be used to check for reachability of nodes:
451 /// if Z is reachable from X, then an insertion of the edge Z->X would
454 /// The algorithm first computes a topological ordering for the DAG by
455 /// initializing the Index2Node and Node2Index arrays and then tries to keep
456 /// the ordering up-to-date after edge insertions by reordering the DAG.
458 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
459 /// the nodes reachable from Y, and then shifts them using Shift to lie
460 /// immediately after X in Index2Node.
461 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
462 unsigned DAGSize = SUnits.size();
463 std::vector<SUnit*> WorkList;
464 WorkList.reserve(DAGSize);
466 Index2Node.resize(DAGSize);
467 Node2Index.resize(DAGSize);
469 // Initialize the data structures.
471 WorkList.push_back(ExitSU);
472 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
473 SUnit *SU = &SUnits[i];
474 int NodeNum = SU->NodeNum;
475 unsigned Degree = SU->Succs.size();
476 // Temporarily use the Node2Index array as scratch space for degree counts.
477 Node2Index[NodeNum] = Degree;
479 // Is it a node without dependencies?
481 assert(SU->Succs.empty() && "SUnit should have no successors");
482 // Collect leaf nodes.
483 WorkList.push_back(SU);
488 while (!WorkList.empty()) {
489 SUnit *SU = WorkList.back();
491 if (SU->NodeNum < DAGSize)
492 Allocate(SU->NodeNum, --Id);
493 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
495 SUnit *SU = I->getSUnit();
496 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
497 // If all dependencies of the node are processed already,
498 // then the node can be computed now.
499 WorkList.push_back(SU);
503 Visited.resize(DAGSize);
506 // Check correctness of the ordering
507 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
508 SUnit *SU = &SUnits[i];
509 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
511 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
512 "Wrong topological sorting");
518 /// AddPred - Updates the topological ordering to accommodate an edge
519 /// to be added from SUnit X to SUnit Y.
520 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
521 int UpperBound, LowerBound;
522 LowerBound = Node2Index[Y->NodeNum];
523 UpperBound = Node2Index[X->NodeNum];
524 bool HasLoop = false;
525 // Is Ord(X) < Ord(Y) ?
526 if (LowerBound < UpperBound) {
527 // Update the topological order.
529 DFS(Y, UpperBound, HasLoop);
530 assert(!HasLoop && "Inserted edge creates a loop!");
531 // Recompute topological indexes.
532 Shift(Visited, LowerBound, UpperBound);
536 /// RemovePred - Updates the topological ordering to accommodate an
537 /// an edge to be removed from the specified node N from the predecessors
538 /// of the current node M.
539 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
540 // InitDAGTopologicalSorting();
543 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
544 /// all nodes affected by the edge insertion. These nodes will later get new
545 /// topological indexes by means of the Shift method.
546 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
548 std::vector<const SUnit*> WorkList;
549 WorkList.reserve(SUnits.size());
551 WorkList.push_back(SU);
553 SU = WorkList.back();
555 Visited.set(SU->NodeNum);
556 for (int I = SU->Succs.size()-1; I >= 0; --I) {
557 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
558 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
559 if (s >= Node2Index.size())
561 if (Node2Index[s] == UpperBound) {
565 // Visit successors if not already and in affected region.
566 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
567 WorkList.push_back(SU->Succs[I].getSUnit());
570 } while (!WorkList.empty());
573 /// Shift - Renumber the nodes so that the topological ordering is
575 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
581 for (i = LowerBound; i <= UpperBound; ++i) {
582 // w is node at topological index i.
583 int w = Index2Node[i];
584 if (Visited.test(w)) {
590 Allocate(w, i - shift);
594 for (unsigned j = 0; j < L.size(); ++j) {
595 Allocate(L[j], i - shift);
601 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
602 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
603 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
604 // Is SU reachable from TargetSU via successor edges?
605 if (IsReachable(SU, TargetSU))
607 for (SUnit::pred_iterator
608 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
609 if (I->isAssignedRegDep() &&
610 IsReachable(SU, I->getSUnit()))
615 /// IsReachable - Checks if SU is reachable from TargetSU.
616 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
617 const SUnit *TargetSU) {
618 // If insertion of the edge SU->TargetSU would create a cycle
619 // then there is a path from TargetSU to SU.
620 int UpperBound, LowerBound;
621 LowerBound = Node2Index[TargetSU->NodeNum];
622 UpperBound = Node2Index[SU->NodeNum];
623 bool HasLoop = false;
624 // Is Ord(TargetSU) < Ord(SU) ?
625 if (LowerBound < UpperBound) {
627 // There may be a path from TargetSU to SU. Check for it.
628 DFS(TargetSU, UpperBound, HasLoop);
633 /// Allocate - assign the topological index to the node n.
634 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
635 Node2Index[n] = index;
636 Index2Node[index] = n;
639 ScheduleDAGTopologicalSort::
640 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
641 : SUnits(sunits), ExitSU(exitsu) {}
643 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}