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 /// 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 // SD scheduler relies on artificial edges to enforce physreg
104 // antidependence, so it doesn't treat them as weak edges.
105 bool isWeak = D.isWeak() && N->isInstr();
106 if (!N->isScheduled) {
111 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
120 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
125 N->Succs.push_back(P);
126 if (P.getLatency() != 0) {
127 this->setDepthDirty();
133 /// removePred - This removes the specified edge as a pred of the current
134 /// node if it exists. It also removes the current node as a successor of
135 /// the specified node.
136 void SUnit::removePred(const SDep &D) {
137 // Find the matching predecessor.
138 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
141 bool FoundSucc = false;
142 // Find the corresponding successor in N.
145 SUnit *N = D.getSUnit();
146 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
147 EE = N->Succs.end(); II != EE; ++II)
153 assert(FoundSucc && "Mismatching preds / succs lists!");
156 // Update the bookkeeping.
157 if (P.getKind() == SDep::Data) {
158 assert(NumPreds > 0 && "NumPreds will underflow!");
159 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
163 bool isWeak = D.isWeak() && N->isInstr();
164 if (!N->isScheduled) {
168 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
176 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
180 if (P.getLatency() != 0) {
181 this->setDepthDirty();
188 void SUnit::setDepthDirty() {
189 if (!isDepthCurrent) return;
190 SmallVector<SUnit*, 8> WorkList;
191 WorkList.push_back(this);
193 SUnit *SU = WorkList.pop_back_val();
194 SU->isDepthCurrent = false;
195 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
196 E = SU->Succs.end(); I != E; ++I) {
197 SUnit *SuccSU = I->getSUnit();
198 if (SuccSU->isDepthCurrent)
199 WorkList.push_back(SuccSU);
201 } while (!WorkList.empty());
204 void SUnit::setHeightDirty() {
205 if (!isHeightCurrent) return;
206 SmallVector<SUnit*, 8> WorkList;
207 WorkList.push_back(this);
209 SUnit *SU = WorkList.pop_back_val();
210 SU->isHeightCurrent = false;
211 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
212 E = SU->Preds.end(); I != E; ++I) {
213 SUnit *PredSU = I->getSUnit();
214 if (PredSU->isHeightCurrent)
215 WorkList.push_back(PredSU);
217 } while (!WorkList.empty());
220 /// setDepthToAtLeast - Update this node's successors to reflect the
221 /// fact that this node's depth just increased.
223 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
224 if (NewDepth <= getDepth())
228 isDepthCurrent = true;
231 /// setHeightToAtLeast - Update this node's predecessors to reflect the
232 /// fact that this node's height just increased.
234 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
235 if (NewHeight <= getHeight())
239 isHeightCurrent = true;
242 /// ComputeDepth - Calculate the maximal path from the node to the exit.
244 void SUnit::ComputeDepth() {
245 SmallVector<SUnit*, 8> WorkList;
246 WorkList.push_back(this);
248 SUnit *Cur = WorkList.back();
251 unsigned MaxPredDepth = 0;
252 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
253 E = Cur->Preds.end(); I != E; ++I) {
254 SUnit *PredSU = I->getSUnit();
255 if (PredSU->isDepthCurrent)
256 MaxPredDepth = std::max(MaxPredDepth,
257 PredSU->Depth + I->getLatency());
260 WorkList.push_back(PredSU);
266 if (MaxPredDepth != Cur->Depth) {
267 Cur->setDepthDirty();
268 Cur->Depth = MaxPredDepth;
270 Cur->isDepthCurrent = true;
272 } while (!WorkList.empty());
275 /// ComputeHeight - Calculate the maximal path from the node to the entry.
277 void SUnit::ComputeHeight() {
278 SmallVector<SUnit*, 8> WorkList;
279 WorkList.push_back(this);
281 SUnit *Cur = WorkList.back();
284 unsigned MaxSuccHeight = 0;
285 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
286 E = Cur->Succs.end(); I != E; ++I) {
287 SUnit *SuccSU = I->getSUnit();
288 if (SuccSU->isHeightCurrent)
289 MaxSuccHeight = std::max(MaxSuccHeight,
290 SuccSU->Height + I->getLatency());
293 WorkList.push_back(SuccSU);
299 if (MaxSuccHeight != Cur->Height) {
300 Cur->setHeightDirty();
301 Cur->Height = MaxSuccHeight;
303 Cur->isHeightCurrent = true;
305 } while (!WorkList.empty());
308 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
309 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
310 /// a group of nodes flagged together.
311 void SUnit::dump(const ScheduleDAG *G) const {
312 dbgs() << "SU(" << NodeNum << "): ";
316 void SUnit::dumpAll(const ScheduleDAG *G) const {
319 dbgs() << " # preds left : " << NumPredsLeft << "\n";
320 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
322 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
324 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
325 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
326 dbgs() << " Latency : " << Latency << "\n";
327 dbgs() << " Depth : " << Depth << "\n";
328 dbgs() << " Height : " << Height << "\n";
330 if (Preds.size() != 0) {
331 dbgs() << " Predecessors:\n";
332 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
335 switch (I->getKind()) {
336 case SDep::Data: dbgs() << "val "; break;
337 case SDep::Anti: dbgs() << "anti"; break;
338 case SDep::Output: dbgs() << "out "; break;
339 case SDep::Order: dbgs() << "ch "; break;
341 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
342 if (I->isArtificial())
344 dbgs() << ": Latency=" << I->getLatency();
345 if (I->isAssignedRegDep())
346 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
350 if (Succs.size() != 0) {
351 dbgs() << " Successors:\n";
352 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
355 switch (I->getKind()) {
356 case SDep::Data: dbgs() << "val "; break;
357 case SDep::Anti: dbgs() << "anti"; break;
358 case SDep::Output: dbgs() << "out "; break;
359 case SDep::Order: dbgs() << "ch "; break;
361 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
362 if (I->isArtificial())
364 dbgs() << ": Latency=" << I->getLatency();
373 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
374 /// their state is consistent. Return the number of scheduled nodes.
376 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
377 bool AnyNotSched = false;
378 unsigned DeadNodes = 0;
379 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
380 if (!SUnits[i].isScheduled) {
381 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
386 dbgs() << "*** Scheduling failed! ***\n";
387 SUnits[i].dump(this);
388 dbgs() << "has not been scheduled!\n";
391 if (SUnits[i].isScheduled &&
392 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
395 dbgs() << "*** Scheduling failed! ***\n";
396 SUnits[i].dump(this);
397 dbgs() << "has an unexpected "
398 << (isBottomUp ? "Height" : "Depth") << " value!\n";
402 if (SUnits[i].NumSuccsLeft != 0) {
404 dbgs() << "*** Scheduling failed! ***\n";
405 SUnits[i].dump(this);
406 dbgs() << "has successors left!\n";
410 if (SUnits[i].NumPredsLeft != 0) {
412 dbgs() << "*** Scheduling failed! ***\n";
413 SUnits[i].dump(this);
414 dbgs() << "has predecessors left!\n";
419 assert(!AnyNotSched);
420 return SUnits.size() - DeadNodes;
424 /// InitDAGTopologicalSorting - create the initial topological
425 /// ordering from the DAG to be scheduled.
427 /// The idea of the algorithm is taken from
428 /// "Online algorithms for managing the topological order of
429 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
430 /// This is the MNR algorithm, which was first introduced by
431 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
432 /// "Maintaining a topological order under edge insertions".
434 /// Short description of the algorithm:
436 /// Topological ordering, ord, of a DAG maps each node to a topological
437 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
439 /// This means that if there is a path from the node X to the node Z,
440 /// then ord(X) < ord(Z).
442 /// This property can be used to check for reachability of nodes:
443 /// if Z is reachable from X, then an insertion of the edge Z->X would
446 /// The algorithm first computes a topological ordering for the DAG by
447 /// initializing the Index2Node and Node2Index arrays and then tries to keep
448 /// the ordering up-to-date after edge insertions by reordering the DAG.
450 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
451 /// the nodes reachable from Y, and then shifts them using Shift to lie
452 /// immediately after X in Index2Node.
453 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
454 unsigned DAGSize = SUnits.size();
455 std::vector<SUnit*> WorkList;
456 WorkList.reserve(DAGSize);
458 Index2Node.resize(DAGSize);
459 Node2Index.resize(DAGSize);
461 // Initialize the data structures.
463 WorkList.push_back(ExitSU);
464 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
465 SUnit *SU = &SUnits[i];
466 int NodeNum = SU->NodeNum;
467 unsigned Degree = SU->Succs.size();
468 // Temporarily use the Node2Index array as scratch space for degree counts.
469 Node2Index[NodeNum] = Degree;
471 // Is it a node without dependencies?
473 assert(SU->Succs.empty() && "SUnit should have no successors");
474 // Collect leaf nodes.
475 WorkList.push_back(SU);
480 while (!WorkList.empty()) {
481 SUnit *SU = WorkList.back();
483 if (SU->NodeNum < DAGSize)
484 Allocate(SU->NodeNum, --Id);
485 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
487 SUnit *SU = I->getSUnit();
488 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
489 // If all dependencies of the node are processed already,
490 // then the node can be computed now.
491 WorkList.push_back(SU);
495 Visited.resize(DAGSize);
498 // Check correctness of the ordering
499 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
500 SUnit *SU = &SUnits[i];
501 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
503 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
504 "Wrong topological sorting");
510 /// AddPred - Updates the topological ordering to accommodate an edge
511 /// to be added from SUnit X to SUnit Y.
512 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
513 int UpperBound, LowerBound;
514 LowerBound = Node2Index[Y->NodeNum];
515 UpperBound = Node2Index[X->NodeNum];
516 bool HasLoop = false;
517 // Is Ord(X) < Ord(Y) ?
518 if (LowerBound < UpperBound) {
519 // Update the topological order.
521 DFS(Y, UpperBound, HasLoop);
522 assert(!HasLoop && "Inserted edge creates a loop!");
523 // Recompute topological indexes.
524 Shift(Visited, LowerBound, UpperBound);
528 /// RemovePred - Updates the topological ordering to accommodate an
529 /// an edge to be removed from the specified node N from the predecessors
530 /// of the current node M.
531 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
532 // InitDAGTopologicalSorting();
535 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
536 /// all nodes affected by the edge insertion. These nodes will later get new
537 /// topological indexes by means of the Shift method.
538 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
540 std::vector<const SUnit*> WorkList;
541 WorkList.reserve(SUnits.size());
543 WorkList.push_back(SU);
545 SU = WorkList.back();
547 Visited.set(SU->NodeNum);
548 for (int I = SU->Succs.size()-1; I >= 0; --I) {
549 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
550 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
551 if (s >= Node2Index.size())
553 if (Node2Index[s] == UpperBound) {
557 // Visit successors if not already and in affected region.
558 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
559 WorkList.push_back(SU->Succs[I].getSUnit());
562 } while (!WorkList.empty());
565 /// Shift - Renumber the nodes so that the topological ordering is
567 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
573 for (i = LowerBound; i <= UpperBound; ++i) {
574 // w is node at topological index i.
575 int w = Index2Node[i];
576 if (Visited.test(w)) {
582 Allocate(w, i - shift);
586 for (unsigned j = 0; j < L.size(); ++j) {
587 Allocate(L[j], i - shift);
593 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
594 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
595 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
596 // Is SU reachable from TargetSU via successor edges?
597 if (IsReachable(SU, TargetSU))
599 for (SUnit::pred_iterator
600 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
601 if (I->isAssignedRegDep() &&
602 IsReachable(SU, I->getSUnit()))
607 /// IsReachable - Checks if SU is reachable from TargetSU.
608 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
609 const SUnit *TargetSU) {
610 // If insertion of the edge SU->TargetSU would create a cycle
611 // then there is a path from TargetSU to SU.
612 int UpperBound, LowerBound;
613 LowerBound = Node2Index[TargetSU->NodeNum];
614 UpperBound = Node2Index[SU->NodeNum];
615 bool HasLoop = false;
616 // Is Ord(TargetSU) < Ord(SU) ?
617 if (LowerBound < UpperBound) {
619 // There may be a path from TargetSU to SU. Check for it.
620 DFS(TargetSU, UpperBound, HasLoop);
625 /// Allocate - assign the topological index to the node n.
626 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
627 Node2Index[n] = index;
628 Index2Node[index] = n;
631 ScheduleDAGTopologicalSort::
632 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
633 : SUnits(sunits), ExitSU(exitsu) {}
635 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}