blob: 7fae783f8dbbc7595efbb57e925edcd2e697e4fe [file] [log] [blame]
Dan Gohman343f0c02008-11-19 23:18:57 +00001//===---- 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"
Dan Gohmanfc54c552009-01-15 22:18:12 +000017#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick2da8bc82010-12-24 05:03:26 +000018#include "llvm/CodeGen/SelectionDAGNodes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000019#include "llvm/Target/TargetMachine.h"
20#include "llvm/Target/TargetInstrInfo.h"
21#include "llvm/Target/TargetRegisterInfo.h"
Andrew Trick4cb971c2011-06-15 17:16:12 +000022#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/Support/Debug.h"
Daniel Dunbar3f0e8302009-07-24 09:53:24 +000024#include "llvm/Support/raw_ostream.h"
Dan Gohman40362062008-11-20 01:41:34 +000025#include <climits>
Dan Gohman343f0c02008-11-19 23:18:57 +000026using namespace llvm;
27
Andrew Trick4cb971c2011-06-15 17:16:12 +000028#ifndef NDEBUG
Benjamin Kramera67f14b2011-08-19 01:42:18 +000029static cl::opt<bool> StressSchedOpt(
Andrew Trick4cb971c2011-06-15 17:16:12 +000030 "stress-sched", cl::Hidden, cl::init(false),
31 cl::desc("Stress test instruction scheduling"));
32#endif
33
David Blaikie2d24e2a2011-12-20 02:50:00 +000034void SchedulingPriorityQueue::anchor() { }
35
Dan Gohman79ce2762009-01-15 19:20:50 +000036ScheduleDAG::ScheduleDAG(MachineFunction &mf)
Dan Gohman47ac0f02009-02-11 04:27:20 +000037 : TM(mf.getTarget()),
Dan Gohman79ce2762009-01-15 19:20:50 +000038 TII(TM.getInstrInfo()),
39 TRI(TM.getRegisterInfo()),
Dan Gohman79ce2762009-01-15 19:20:50 +000040 MF(mf), MRI(mf.getRegInfo()),
Dan Gohman9e64bbb2009-02-10 23:27:53 +000041 EntrySU(), ExitSU() {
Andrew Trick4cb971c2011-06-15 17:16:12 +000042#ifndef NDEBUG
43 StressSched = StressSchedOpt;
44#endif
Dan Gohman343f0c02008-11-19 23:18:57 +000045}
46
47ScheduleDAG::~ScheduleDAG() {}
48
Andrew Trick2da8bc82010-12-24 05:03:26 +000049/// getInstrDesc helper to handle SDNodes.
Evan Chenge837dea2011-06-28 19:10:37 +000050const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
Andrew Trick24312232010-12-24 06:46:50 +000051 if (!Node || !Node->isMachineOpcode()) return NULL;
Andrew Trick2da8bc82010-12-24 05:03:26 +000052 return &TII->get(Node->getMachineOpcode());
53}
54
Dan Gohman343f0c02008-11-19 23:18:57 +000055/// Run - perform scheduling.
56///
Dan Gohman47ac0f02009-02-11 04:27:20 +000057void ScheduleDAG::Run(MachineBasicBlock *bb,
58 MachineBasicBlock::iterator insertPos) {
59 BB = bb;
60 InsertPos = insertPos;
Dan Gohmanf7119392009-01-16 22:10:20 +000061
Dan Gohman79ce2762009-01-15 19:20:50 +000062 SUnits.clear();
63 Sequence.clear();
Dan Gohman9e64bbb2009-02-10 23:27:53 +000064 EntrySU = SUnit();
65 ExitSU = SUnit();
Dan Gohman79ce2762009-01-15 19:20:50 +000066
Dan Gohman343f0c02008-11-19 23:18:57 +000067 Schedule();
Dan Gohman343f0c02008-11-19 23:18:57 +000068}
69
Dan Gohmanc6b680e2008-12-16 01:05:52 +000070/// 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
72/// specified node.
Andrew Trick92e94662011-02-04 03:18:17 +000073bool SUnit::addPred(const SDep &D) {
Dan Gohmanc6b680e2008-12-16 01:05:52 +000074 // If this node already has this depenence, don't add a redundant one.
Dan Gohman5cffa6f2009-02-11 00:12:28 +000075 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
76 I != E; ++I)
77 if (*I == D)
Andrew Trick92e94662011-02-04 03:18:17 +000078 return false;
Dan Gohmanc6b680e2008-12-16 01:05:52 +000079 // Now add a corresponding succ to N.
80 SDep P = D;
81 P.setSUnit(this);
82 SUnit *N = D.getSUnit();
Dan Gohmanc6b680e2008-12-16 01:05:52 +000083 // Update the bookkeeping.
84 if (D.getKind() == SDep::Data) {
Reid Klecknerc277ab02009-09-30 20:15:38 +000085 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
86 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +000087 ++NumPreds;
88 ++N->NumSuccs;
89 }
Reid Klecknerc277ab02009-09-30 20:15:38 +000090 if (!N->isScheduled) {
91 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +000092 ++NumPredsLeft;
Reid Klecknerc277ab02009-09-30 20:15:38 +000093 }
94 if (!isScheduled) {
95 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +000096 ++N->NumSuccsLeft;
Reid Klecknerc277ab02009-09-30 20:15:38 +000097 }
Dan Gohman3f237442008-12-16 03:25:46 +000098 Preds.push_back(D);
Dan Gohmana1f50e22009-01-13 19:08:45 +000099 N->Succs.push_back(P);
Dan Gohmana80c8592009-01-05 22:40:26 +0000100 if (P.getLatency() != 0) {
101 this->setDepthDirty();
102 N->setHeightDirty();
103 }
Andrew Trick92e94662011-02-04 03:18:17 +0000104 return true;
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000105}
106
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.
110void SUnit::removePred(const SDep &D) {
111 // Find the matching predecessor.
112 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
113 I != E; ++I)
114 if (*I == D) {
115 bool FoundSucc = false;
116 // Find the corresponding successor in N.
117 SDep P = D;
118 P.setSUnit(this);
119 SUnit *N = D.getSUnit();
120 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
121 EE = N->Succs.end(); II != EE; ++II)
122 if (*II == P) {
123 FoundSucc = true;
124 N->Succs.erase(II);
125 break;
126 }
127 assert(FoundSucc && "Mismatching preds / succs lists!");
Duncan Sands1f6a3292011-08-12 14:54:45 +0000128 (void)FoundSucc;
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000129 Preds.erase(I);
Dan Gohmana1f50e22009-01-13 19:08:45 +0000130 // Update the bookkeeping.
131 if (P.getKind() == SDep::Data) {
Reid Klecknerc277ab02009-09-30 20:15:38 +0000132 assert(NumPreds > 0 && "NumPreds will underflow!");
133 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000134 --NumPreds;
135 --N->NumSuccs;
136 }
Reid Klecknerc277ab02009-09-30 20:15:38 +0000137 if (!N->isScheduled) {
138 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000139 --NumPredsLeft;
Reid Klecknerc277ab02009-09-30 20:15:38 +0000140 }
141 if (!isScheduled) {
142 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000143 --N->NumSuccsLeft;
Reid Klecknerc277ab02009-09-30 20:15:38 +0000144 }
Dan Gohmana80c8592009-01-05 22:40:26 +0000145 if (P.getLatency() != 0) {
146 this->setDepthDirty();
147 N->setHeightDirty();
148 }
Dan Gohmanc6b680e2008-12-16 01:05:52 +0000149 return;
150 }
151}
152
Dan Gohman3f237442008-12-16 03:25:46 +0000153void SUnit::setDepthDirty() {
Dan Gohman8044e9b2008-12-22 21:11:33 +0000154 if (!isDepthCurrent) return;
Dan Gohman3f237442008-12-16 03:25:46 +0000155 SmallVector<SUnit*, 8> WorkList;
156 WorkList.push_back(this);
Dan Gohman8044e9b2008-12-22 21:11:33 +0000157 do {
Dan Gohmane19c6362008-12-20 16:42:33 +0000158 SUnit *SU = WorkList.pop_back_val();
Dan Gohman3f237442008-12-16 03:25:46 +0000159 SU->isDepthCurrent = false;
Dan Gohmanf89e6e62008-12-20 16:34:57 +0000160 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
Dan Gohman8044e9b2008-12-22 21:11:33 +0000161 E = SU->Succs.end(); I != E; ++I) {
162 SUnit *SuccSU = I->getSUnit();
163 if (SuccSU->isDepthCurrent)
164 WorkList.push_back(SuccSU);
165 }
166 } while (!WorkList.empty());
Dan Gohman3f237442008-12-16 03:25:46 +0000167}
168
169void SUnit::setHeightDirty() {
Dan Gohman8044e9b2008-12-22 21:11:33 +0000170 if (!isHeightCurrent) return;
Dan Gohman3f237442008-12-16 03:25:46 +0000171 SmallVector<SUnit*, 8> WorkList;
172 WorkList.push_back(this);
Dan Gohman8044e9b2008-12-22 21:11:33 +0000173 do {
Dan Gohmane19c6362008-12-20 16:42:33 +0000174 SUnit *SU = WorkList.pop_back_val();
Dan Gohman3f237442008-12-16 03:25:46 +0000175 SU->isHeightCurrent = false;
Dan Gohmanf89e6e62008-12-20 16:34:57 +0000176 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
Dan Gohman8044e9b2008-12-22 21:11:33 +0000177 E = SU->Preds.end(); I != E; ++I) {
178 SUnit *PredSU = I->getSUnit();
179 if (PredSU->isHeightCurrent)
180 WorkList.push_back(PredSU);
181 }
182 } while (!WorkList.empty());
Dan Gohman3f237442008-12-16 03:25:46 +0000183}
184
185/// setDepthToAtLeast - Update this node's successors to reflect the
186/// fact that this node's depth just increased.
187///
David Goodwin557bbe62009-11-20 19:32:48 +0000188void SUnit::setDepthToAtLeast(unsigned NewDepth) {
189 if (NewDepth <= getDepth())
Dan Gohman3f237442008-12-16 03:25:46 +0000190 return;
191 setDepthDirty();
192 Depth = NewDepth;
193 isDepthCurrent = true;
194}
195
196/// setHeightToAtLeast - Update this node's predecessors to reflect the
197/// fact that this node's height just increased.
198///
David Goodwin557bbe62009-11-20 19:32:48 +0000199void SUnit::setHeightToAtLeast(unsigned NewHeight) {
200 if (NewHeight <= getHeight())
Dan Gohman3f237442008-12-16 03:25:46 +0000201 return;
202 setHeightDirty();
203 Height = NewHeight;
204 isHeightCurrent = true;
205}
206
207/// ComputeDepth - Calculate the maximal path from the node to the exit.
208///
David Goodwin557bbe62009-11-20 19:32:48 +0000209void SUnit::ComputeDepth() {
Dan Gohman3f237442008-12-16 03:25:46 +0000210 SmallVector<SUnit*, 8> WorkList;
211 WorkList.push_back(this);
Dan Gohman1578f842008-12-23 17:22:32 +0000212 do {
Dan Gohman3f237442008-12-16 03:25:46 +0000213 SUnit *Cur = WorkList.back();
214
215 bool Done = true;
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());
223 else {
224 Done = false;
225 WorkList.push_back(PredSU);
226 }
227 }
228
229 if (Done) {
230 WorkList.pop_back();
231 if (MaxPredDepth != Cur->Depth) {
232 Cur->setDepthDirty();
233 Cur->Depth = MaxPredDepth;
234 }
235 Cur->isDepthCurrent = true;
236 }
Dan Gohman1578f842008-12-23 17:22:32 +0000237 } while (!WorkList.empty());
Dan Gohman3f237442008-12-16 03:25:46 +0000238}
239
240/// ComputeHeight - Calculate the maximal path from the node to the entry.
241///
David Goodwin557bbe62009-11-20 19:32:48 +0000242void SUnit::ComputeHeight() {
Dan Gohman3f237442008-12-16 03:25:46 +0000243 SmallVector<SUnit*, 8> WorkList;
244 WorkList.push_back(this);
Dan Gohman1578f842008-12-23 17:22:32 +0000245 do {
Dan Gohman3f237442008-12-16 03:25:46 +0000246 SUnit *Cur = WorkList.back();
247
248 bool Done = true;
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());
256 else {
257 Done = false;
258 WorkList.push_back(SuccSU);
259 }
260 }
261
262 if (Done) {
263 WorkList.pop_back();
264 if (MaxSuccHeight != Cur->Height) {
265 Cur->setHeightDirty();
266 Cur->Height = MaxSuccHeight;
267 }
268 Cur->isHeightCurrent = true;
269 }
Dan Gohman1578f842008-12-23 17:22:32 +0000270 } while (!WorkList.empty());
Dan Gohman3f237442008-12-16 03:25:46 +0000271}
272
Dan Gohman343f0c02008-11-19 23:18:57 +0000273/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
274/// a group of nodes flagged together.
275void SUnit::dump(const ScheduleDAG *G) const {
David Greene4b134d12010-01-05 01:25:41 +0000276 dbgs() << "SU(" << NodeNum << "): ";
Dan Gohman343f0c02008-11-19 23:18:57 +0000277 G->dumpNode(this);
278}
279
280void SUnit::dumpAll(const ScheduleDAG *G) const {
281 dump(G);
282
David Greene4b134d12010-01-05 01:25:41 +0000283 dbgs() << " # preds left : " << NumPredsLeft << "\n";
284 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
Andrew Trick92e94662011-02-04 03:18:17 +0000285 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
David Greene4b134d12010-01-05 01:25:41 +0000286 dbgs() << " Latency : " << Latency << "\n";
287 dbgs() << " Depth : " << Depth << "\n";
288 dbgs() << " Height : " << Height << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000289
290 if (Preds.size() != 0) {
David Greene4b134d12010-01-05 01:25:41 +0000291 dbgs() << " Predecessors:\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000292 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
293 I != E; ++I) {
David Greene4b134d12010-01-05 01:25:41 +0000294 dbgs() << " ";
Dan Gohman54e4c362008-12-09 22:54:47 +0000295 switch (I->getKind()) {
David Greene4b134d12010-01-05 01:25:41 +0000296 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;
Dan Gohman54e4c362008-12-09 22:54:47 +0000300 }
Jakob Stoklund Olesen0b923d92012-02-17 21:44:51 +0000301 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
Dan Gohman54e4c362008-12-09 22:54:47 +0000302 if (I->isArtificial())
David Greene4b134d12010-01-05 01:25:41 +0000303 dbgs() << " *";
304 dbgs() << ": Latency=" << I->getLatency();
Andrew Trick4cb971c2011-06-15 17:16:12 +0000305 if (I->isAssignedRegDep())
Jakob Stoklund Olesen0b923d92012-02-17 21:44:51 +0000306 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
David Greene4b134d12010-01-05 01:25:41 +0000307 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000308 }
309 }
310 if (Succs.size() != 0) {
David Greene4b134d12010-01-05 01:25:41 +0000311 dbgs() << " Successors:\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000312 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
313 I != E; ++I) {
David Greene4b134d12010-01-05 01:25:41 +0000314 dbgs() << " ";
Dan Gohman54e4c362008-12-09 22:54:47 +0000315 switch (I->getKind()) {
David Greene4b134d12010-01-05 01:25:41 +0000316 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;
Dan Gohman54e4c362008-12-09 22:54:47 +0000320 }
Jakob Stoklund Olesen0b923d92012-02-17 21:44:51 +0000321 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
Dan Gohman54e4c362008-12-09 22:54:47 +0000322 if (I->isArtificial())
David Greene4b134d12010-01-05 01:25:41 +0000323 dbgs() << " *";
324 dbgs() << ": Latency=" << I->getLatency();
325 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000326 }
327 }
David Greene4b134d12010-01-05 01:25:41 +0000328 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000329}
Dan Gohmana1e6d362008-11-20 01:26:25 +0000330
331#ifndef NDEBUG
Andrew Trick4c727202012-03-07 05:21:36 +0000332/// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
333/// their state is consistent. Return the number of scheduled nodes.
Dan Gohmana1e6d362008-11-20 01:26:25 +0000334///
Andrew Trick4c727202012-03-07 05:21:36 +0000335unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
Dan Gohmana1e6d362008-11-20 01:26:25 +0000336 bool AnyNotSched = false;
337 unsigned DeadNodes = 0;
Dan Gohmana1e6d362008-11-20 01:26:25 +0000338 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) {
341 ++DeadNodes;
342 continue;
343 }
344 if (!AnyNotSched)
David Greene4b134d12010-01-05 01:25:41 +0000345 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000346 SUnits[i].dump(this);
David Greene4b134d12010-01-05 01:25:41 +0000347 dbgs() << "has not been scheduled!\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000348 AnyNotSched = true;
349 }
Dan Gohman3f237442008-12-16 03:25:46 +0000350 if (SUnits[i].isScheduled &&
David Goodwin4de099d2009-11-03 20:57:50 +0000351 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
Dan Gohman3f237442008-12-16 03:25:46 +0000352 unsigned(INT_MAX)) {
Dan Gohmana1e6d362008-11-20 01:26:25 +0000353 if (!AnyNotSched)
David Greene4b134d12010-01-05 01:25:41 +0000354 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000355 SUnits[i].dump(this);
David Greene4b134d12010-01-05 01:25:41 +0000356 dbgs() << "has an unexpected "
Dan Gohman3f237442008-12-16 03:25:46 +0000357 << (isBottomUp ? "Height" : "Depth") << " value!\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000358 AnyNotSched = true;
359 }
360 if (isBottomUp) {
361 if (SUnits[i].NumSuccsLeft != 0) {
362 if (!AnyNotSched)
David Greene4b134d12010-01-05 01:25:41 +0000363 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000364 SUnits[i].dump(this);
David Greene4b134d12010-01-05 01:25:41 +0000365 dbgs() << "has successors left!\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000366 AnyNotSched = true;
367 }
368 } else {
369 if (SUnits[i].NumPredsLeft != 0) {
370 if (!AnyNotSched)
David Greene4b134d12010-01-05 01:25:41 +0000371 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000372 SUnits[i].dump(this);
David Greene4b134d12010-01-05 01:25:41 +0000373 dbgs() << "has predecessors left!\n";
Dan Gohmana1e6d362008-11-20 01:26:25 +0000374 AnyNotSched = true;
375 }
376 }
377 }
Dan Gohmana1e6d362008-11-20 01:26:25 +0000378 assert(!AnyNotSched);
Andrew Trick4c727202012-03-07 05:21:36 +0000379 return SUnits.size() - DeadNodes;
Dan Gohmana1e6d362008-11-20 01:26:25 +0000380}
381#endif
Dan Gohman21d90032008-11-25 00:52:40 +0000382
John Mosby9f71f802010-06-30 03:40:54 +0000383/// InitDAGTopologicalSorting - create the initial topological
Dan Gohman21d90032008-11-25 00:52:40 +0000384/// ordering from the DAG to be scheduled.
385///
John Mosby9f71f802010-06-30 03:40:54 +0000386/// The idea of the algorithm is taken from
Dan Gohman21d90032008-11-25 00:52:40 +0000387/// "Online algorithms for managing the topological order of
388/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
John Mosby9f71f802010-06-30 03:40:54 +0000389/// This is the MNR algorithm, which was first introduced by
390/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
Dan Gohman21d90032008-11-25 00:52:40 +0000391/// "Maintaining a topological order under edge insertions".
392///
John Mosby9f71f802010-06-30 03:40:54 +0000393/// Short description of the algorithm:
Dan Gohman21d90032008-11-25 00:52:40 +0000394///
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).
397///
John Mosby9f71f802010-06-30 03:40:54 +0000398/// This means that if there is a path from the node X to the node Z,
Dan Gohman21d90032008-11-25 00:52:40 +0000399/// then ord(X) < ord(Z).
400///
401/// This property can be used to check for reachability of nodes:
John Mosby9f71f802010-06-30 03:40:54 +0000402/// if Z is reachable from X, then an insertion of the edge Z->X would
Dan Gohman21d90032008-11-25 00:52:40 +0000403/// create a cycle.
404///
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.
408///
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.
412void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
413 unsigned DAGSize = SUnits.size();
414 std::vector<SUnit*> WorkList;
415 WorkList.reserve(DAGSize);
416
417 Index2Node.resize(DAGSize);
418 Node2Index.resize(DAGSize);
419
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;
427
428 // Is it a node without dependencies?
429 if (Degree == 0) {
430 assert(SU->Succs.empty() && "SUnit should have no successors");
431 // Collect leaf nodes.
432 WorkList.push_back(SU);
433 }
John Mosby9f71f802010-06-30 03:40:54 +0000434 }
Dan Gohman21d90032008-11-25 00:52:40 +0000435
436 int Id = DAGSize;
437 while (!WorkList.empty()) {
438 SUnit *SU = WorkList.back();
439 WorkList.pop_back();
440 Allocate(SU->NodeNum, --Id);
441 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
442 I != E; ++I) {
Dan Gohman54e4c362008-12-09 22:54:47 +0000443 SUnit *SU = I->getSUnit();
Dan Gohman21d90032008-11-25 00:52:40 +0000444 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);
448 }
449 }
450
451 Visited.resize(DAGSize);
452
453#ifndef NDEBUG
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();
458 I != E; ++I) {
John Mosby9f71f802010-06-30 03:40:54 +0000459 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
Dan Gohman21d90032008-11-25 00:52:40 +0000460 "Wrong topological sorting");
461 }
462 }
463#endif
464}
465
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000466/// AddPred - Updates the topological ordering to accommodate an edge
Dan Gohman21d90032008-11-25 00:52:40 +0000467/// to be added from SUnit X to SUnit Y.
468void 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.
476 Visited.reset();
477 DFS(Y, UpperBound, HasLoop);
478 assert(!HasLoop && "Inserted edge creates a loop!");
479 // Recompute topological indexes.
480 Shift(Visited, LowerBound, UpperBound);
481 }
482}
483
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000484/// RemovePred - Updates the topological ordering to accommodate an
Dan Gohman21d90032008-11-25 00:52:40 +0000485/// an edge to be removed from the specified node N from the predecessors
486/// of the current node M.
487void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
488 // InitDAGTopologicalSorting();
489}
490
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.
Dan Gohmane3a49cd2008-12-09 16:37:48 +0000494void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
Chris Lattner50782932010-12-20 00:50:16 +0000495 bool &HasLoop) {
Dan Gohman21d90032008-11-25 00:52:40 +0000496 std::vector<const SUnit*> WorkList;
John Mosby9f71f802010-06-30 03:40:54 +0000497 WorkList.reserve(SUnits.size());
Dan Gohman21d90032008-11-25 00:52:40 +0000498
499 WorkList.push_back(SU);
Dan Gohman1578f842008-12-23 17:22:32 +0000500 do {
Dan Gohman21d90032008-11-25 00:52:40 +0000501 SU = WorkList.back();
502 WorkList.pop_back();
503 Visited.set(SU->NodeNum);
504 for (int I = SU->Succs.size()-1; I >= 0; --I) {
Dan Gohman54e4c362008-12-09 22:54:47 +0000505 int s = SU->Succs[I].getSUnit()->NodeNum;
Dan Gohman21d90032008-11-25 00:52:40 +0000506 if (Node2Index[s] == UpperBound) {
John Mosby9f71f802010-06-30 03:40:54 +0000507 HasLoop = true;
Dan Gohman21d90032008-11-25 00:52:40 +0000508 return;
509 }
510 // Visit successors if not already and in affected region.
511 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
Dan Gohman54e4c362008-12-09 22:54:47 +0000512 WorkList.push_back(SU->Succs[I].getSUnit());
John Mosby9f71f802010-06-30 03:40:54 +0000513 }
514 }
Dan Gohman1578f842008-12-23 17:22:32 +0000515 } while (!WorkList.empty());
Dan Gohman21d90032008-11-25 00:52:40 +0000516}
517
John Mosby9f71f802010-06-30 03:40:54 +0000518/// Shift - Renumber the nodes so that the topological ordering is
Dan Gohman21d90032008-11-25 00:52:40 +0000519/// preserved.
John Mosby9f71f802010-06-30 03:40:54 +0000520void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
Dan Gohmane3a49cd2008-12-09 16:37:48 +0000521 int UpperBound) {
Dan Gohman21d90032008-11-25 00:52:40 +0000522 std::vector<int> L;
523 int shift = 0;
524 int i;
525
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)) {
530 // Unmark.
531 Visited.reset(w);
532 L.push_back(w);
533 shift = shift + 1;
534 } else {
535 Allocate(w, i - shift);
536 }
537 }
538
539 for (unsigned j = 0; j < L.size(); ++j) {
540 Allocate(L[j], i - shift);
541 i = i + 1;
542 }
543}
544
545
546/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
547/// create a cycle.
548bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
549 if (IsReachable(TargetSU, SU))
550 return true;
551 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
552 I != E; ++I)
Dan Gohman54e4c362008-12-09 22:54:47 +0000553 if (I->isAssignedRegDep() &&
554 IsReachable(TargetSU, I->getSUnit()))
Dan Gohman21d90032008-11-25 00:52:40 +0000555 return true;
556 return false;
557}
558
559/// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmane3a49cd2008-12-09 16:37:48 +0000560bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
561 const SUnit *TargetSU) {
Dan Gohman21d90032008-11-25 00:52:40 +0000562 // 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) {
570 Visited.reset();
John Mosby9f71f802010-06-30 03:40:54 +0000571 // There may be a path from TargetSU to SU. Check for it.
Dan Gohman21d90032008-11-25 00:52:40 +0000572 DFS(TargetSU, UpperBound, HasLoop);
573 }
574 return HasLoop;
575}
576
577/// Allocate - assign the topological index to the node n.
578void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
579 Node2Index[n] = index;
580 Index2Node[index] = n;
581}
582
John Mosby9f71f802010-06-30 03:40:54 +0000583ScheduleDAGTopologicalSort::
584ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
Dan Gohmanfc54c552009-01-15 22:18:12 +0000585
586ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}