spillPhysRegAroundRegDefsUses() may have invalidated iterators stored in fixed_ Inter...
[llvm/msp430.git] / lib / CodeGen / ScheduleDAG.cpp
bloba8452dff272b8d741898d56d76efcb4c8b9d9c0f
1 //===---- 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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include <climits>
23 using namespace llvm;
25 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
26 : TM(mf.getTarget()),
27 TII(TM.getInstrInfo()),
28 TRI(TM.getRegisterInfo()),
29 TLI(TM.getTargetLowering()),
30 MF(mf), MRI(mf.getRegInfo()),
31 ConstPool(MF.getConstantPool()),
32 EntrySU(), ExitSU() {
35 ScheduleDAG::~ScheduleDAG() {}
37 /// dump - dump the schedule.
38 void ScheduleDAG::dumpSchedule() const {
39 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
40 if (SUnit *SU = Sequence[i])
41 SU->dump(this);
42 else
43 cerr << "**** NOOP ****\n";
48 /// Run - perform scheduling.
49 ///
50 void ScheduleDAG::Run(MachineBasicBlock *bb,
51 MachineBasicBlock::iterator insertPos) {
52 BB = bb;
53 InsertPos = insertPos;
55 SUnits.clear();
56 Sequence.clear();
57 EntrySU = SUnit();
58 ExitSU = SUnit();
60 Schedule();
62 DOUT << "*** Final schedule ***\n";
63 DEBUG(dumpSchedule());
64 DOUT << "\n";
67 /// addPred - This adds the specified edge as a pred of the current node if
68 /// not already. It also adds the current node as a successor of the
69 /// specified node.
70 void SUnit::addPred(const SDep &D) {
71 // If this node already has this depenence, don't add a redundant one.
72 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
73 I != E; ++I)
74 if (*I == D)
75 return;
76 // Now add a corresponding succ to N.
77 SDep P = D;
78 P.setSUnit(this);
79 SUnit *N = D.getSUnit();
80 // Update the bookkeeping.
81 if (D.getKind() == SDep::Data) {
82 ++NumPreds;
83 ++N->NumSuccs;
85 if (!N->isScheduled)
86 ++NumPredsLeft;
87 if (!isScheduled)
88 ++N->NumSuccsLeft;
89 Preds.push_back(D);
90 N->Succs.push_back(P);
91 if (P.getLatency() != 0) {
92 this->setDepthDirty();
93 N->setHeightDirty();
97 /// removePred - This removes the specified edge as a pred of the current
98 /// node if it exists. It also removes the current node as a successor of
99 /// the specified node.
100 void SUnit::removePred(const SDep &D) {
101 // Find the matching predecessor.
102 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
103 I != E; ++I)
104 if (*I == D) {
105 bool FoundSucc = false;
106 // Find the corresponding successor in N.
107 SDep P = D;
108 P.setSUnit(this);
109 SUnit *N = D.getSUnit();
110 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
111 EE = N->Succs.end(); II != EE; ++II)
112 if (*II == P) {
113 FoundSucc = true;
114 N->Succs.erase(II);
115 break;
117 assert(FoundSucc && "Mismatching preds / succs lists!");
118 Preds.erase(I);
119 // Update the bookkeeping.
120 if (P.getKind() == SDep::Data) {
121 --NumPreds;
122 --N->NumSuccs;
124 if (!N->isScheduled)
125 --NumPredsLeft;
126 if (!isScheduled)
127 --N->NumSuccsLeft;
128 if (P.getLatency() != 0) {
129 this->setDepthDirty();
130 N->setHeightDirty();
132 return;
136 void SUnit::setDepthDirty() {
137 if (!isDepthCurrent) return;
138 SmallVector<SUnit*, 8> WorkList;
139 WorkList.push_back(this);
140 do {
141 SUnit *SU = WorkList.pop_back_val();
142 SU->isDepthCurrent = false;
143 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
144 E = SU->Succs.end(); I != E; ++I) {
145 SUnit *SuccSU = I->getSUnit();
146 if (SuccSU->isDepthCurrent)
147 WorkList.push_back(SuccSU);
149 } while (!WorkList.empty());
152 void SUnit::setHeightDirty() {
153 if (!isHeightCurrent) return;
154 SmallVector<SUnit*, 8> WorkList;
155 WorkList.push_back(this);
156 do {
157 SUnit *SU = WorkList.pop_back_val();
158 SU->isHeightCurrent = false;
159 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
160 E = SU->Preds.end(); I != E; ++I) {
161 SUnit *PredSU = I->getSUnit();
162 if (PredSU->isHeightCurrent)
163 WorkList.push_back(PredSU);
165 } while (!WorkList.empty());
168 /// setDepthToAtLeast - Update this node's successors to reflect the
169 /// fact that this node's depth just increased.
171 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
172 if (NewDepth <= getDepth())
173 return;
174 setDepthDirty();
175 Depth = NewDepth;
176 isDepthCurrent = true;
179 /// setHeightToAtLeast - Update this node's predecessors to reflect the
180 /// fact that this node's height just increased.
182 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
183 if (NewHeight <= getHeight())
184 return;
185 setHeightDirty();
186 Height = NewHeight;
187 isHeightCurrent = true;
190 /// ComputeDepth - Calculate the maximal path from the node to the exit.
192 void SUnit::ComputeDepth() {
193 SmallVector<SUnit*, 8> WorkList;
194 WorkList.push_back(this);
195 do {
196 SUnit *Cur = WorkList.back();
198 bool Done = true;
199 unsigned MaxPredDepth = 0;
200 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
201 E = Cur->Preds.end(); I != E; ++I) {
202 SUnit *PredSU = I->getSUnit();
203 if (PredSU->isDepthCurrent)
204 MaxPredDepth = std::max(MaxPredDepth,
205 PredSU->Depth + I->getLatency());
206 else {
207 Done = false;
208 WorkList.push_back(PredSU);
212 if (Done) {
213 WorkList.pop_back();
214 if (MaxPredDepth != Cur->Depth) {
215 Cur->setDepthDirty();
216 Cur->Depth = MaxPredDepth;
218 Cur->isDepthCurrent = true;
220 } while (!WorkList.empty());
223 /// ComputeHeight - Calculate the maximal path from the node to the entry.
225 void SUnit::ComputeHeight() {
226 SmallVector<SUnit*, 8> WorkList;
227 WorkList.push_back(this);
228 do {
229 SUnit *Cur = WorkList.back();
231 bool Done = true;
232 unsigned MaxSuccHeight = 0;
233 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
234 E = Cur->Succs.end(); I != E; ++I) {
235 SUnit *SuccSU = I->getSUnit();
236 if (SuccSU->isHeightCurrent)
237 MaxSuccHeight = std::max(MaxSuccHeight,
238 SuccSU->Height + I->getLatency());
239 else {
240 Done = false;
241 WorkList.push_back(SuccSU);
245 if (Done) {
246 WorkList.pop_back();
247 if (MaxSuccHeight != Cur->Height) {
248 Cur->setHeightDirty();
249 Cur->Height = MaxSuccHeight;
251 Cur->isHeightCurrent = true;
253 } while (!WorkList.empty());
256 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
257 /// a group of nodes flagged together.
258 void SUnit::dump(const ScheduleDAG *G) const {
259 cerr << "SU(" << NodeNum << "): ";
260 G->dumpNode(this);
263 void SUnit::dumpAll(const ScheduleDAG *G) const {
264 dump(G);
266 cerr << " # preds left : " << NumPredsLeft << "\n";
267 cerr << " # succs left : " << NumSuccsLeft << "\n";
268 cerr << " Latency : " << Latency << "\n";
269 cerr << " Depth : " << Depth << "\n";
270 cerr << " Height : " << Height << "\n";
272 if (Preds.size() != 0) {
273 cerr << " Predecessors:\n";
274 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
275 I != E; ++I) {
276 cerr << " ";
277 switch (I->getKind()) {
278 case SDep::Data: cerr << "val "; break;
279 case SDep::Anti: cerr << "anti"; break;
280 case SDep::Output: cerr << "out "; break;
281 case SDep::Order: cerr << "ch "; break;
283 cerr << "#";
284 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
285 if (I->isArtificial())
286 cerr << " *";
287 cerr << "\n";
290 if (Succs.size() != 0) {
291 cerr << " Successors:\n";
292 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
293 I != E; ++I) {
294 cerr << " ";
295 switch (I->getKind()) {
296 case SDep::Data: cerr << "val "; break;
297 case SDep::Anti: cerr << "anti"; break;
298 case SDep::Output: cerr << "out "; break;
299 case SDep::Order: cerr << "ch "; break;
301 cerr << "#";
302 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
303 if (I->isArtificial())
304 cerr << " *";
305 cerr << "\n";
308 cerr << "\n";
311 #ifndef NDEBUG
312 /// VerifySchedule - Verify that all SUnits were scheduled and that
313 /// their state is consistent.
315 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
316 bool AnyNotSched = false;
317 unsigned DeadNodes = 0;
318 unsigned Noops = 0;
319 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
320 if (!SUnits[i].isScheduled) {
321 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
322 ++DeadNodes;
323 continue;
325 if (!AnyNotSched)
326 cerr << "*** Scheduling failed! ***\n";
327 SUnits[i].dump(this);
328 cerr << "has not been scheduled!\n";
329 AnyNotSched = true;
331 if (SUnits[i].isScheduled &&
332 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
333 unsigned(INT_MAX)) {
334 if (!AnyNotSched)
335 cerr << "*** Scheduling failed! ***\n";
336 SUnits[i].dump(this);
337 cerr << "has an unexpected "
338 << (isBottomUp ? "Height" : "Depth") << " value!\n";
339 AnyNotSched = true;
341 if (isBottomUp) {
342 if (SUnits[i].NumSuccsLeft != 0) {
343 if (!AnyNotSched)
344 cerr << "*** Scheduling failed! ***\n";
345 SUnits[i].dump(this);
346 cerr << "has successors left!\n";
347 AnyNotSched = true;
349 } else {
350 if (SUnits[i].NumPredsLeft != 0) {
351 if (!AnyNotSched)
352 cerr << "*** Scheduling failed! ***\n";
353 SUnits[i].dump(this);
354 cerr << "has predecessors left!\n";
355 AnyNotSched = true;
359 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
360 if (!Sequence[i])
361 ++Noops;
362 assert(!AnyNotSched);
363 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
364 "The number of nodes scheduled doesn't match the expected number!");
366 #endif
368 /// InitDAGTopologicalSorting - create the initial topological
369 /// ordering from the DAG to be scheduled.
371 /// The idea of the algorithm is taken from
372 /// "Online algorithms for managing the topological order of
373 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
374 /// This is the MNR algorithm, which was first introduced by
375 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
376 /// "Maintaining a topological order under edge insertions".
378 /// Short description of the algorithm:
380 /// Topological ordering, ord, of a DAG maps each node to a topological
381 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
383 /// This means that if there is a path from the node X to the node Z,
384 /// then ord(X) < ord(Z).
386 /// This property can be used to check for reachability of nodes:
387 /// if Z is reachable from X, then an insertion of the edge Z->X would
388 /// create a cycle.
390 /// The algorithm first computes a topological ordering for the DAG by
391 /// initializing the Index2Node and Node2Index arrays and then tries to keep
392 /// the ordering up-to-date after edge insertions by reordering the DAG.
394 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
395 /// the nodes reachable from Y, and then shifts them using Shift to lie
396 /// immediately after X in Index2Node.
397 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
398 unsigned DAGSize = SUnits.size();
399 std::vector<SUnit*> WorkList;
400 WorkList.reserve(DAGSize);
402 Index2Node.resize(DAGSize);
403 Node2Index.resize(DAGSize);
405 // Initialize the data structures.
406 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
407 SUnit *SU = &SUnits[i];
408 int NodeNum = SU->NodeNum;
409 unsigned Degree = SU->Succs.size();
410 // Temporarily use the Node2Index array as scratch space for degree counts.
411 Node2Index[NodeNum] = Degree;
413 // Is it a node without dependencies?
414 if (Degree == 0) {
415 assert(SU->Succs.empty() && "SUnit should have no successors");
416 // Collect leaf nodes.
417 WorkList.push_back(SU);
421 int Id = DAGSize;
422 while (!WorkList.empty()) {
423 SUnit *SU = WorkList.back();
424 WorkList.pop_back();
425 Allocate(SU->NodeNum, --Id);
426 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
427 I != E; ++I) {
428 SUnit *SU = I->getSUnit();
429 if (!--Node2Index[SU->NodeNum])
430 // If all dependencies of the node are processed already,
431 // then the node can be computed now.
432 WorkList.push_back(SU);
436 Visited.resize(DAGSize);
438 #ifndef NDEBUG
439 // Check correctness of the ordering
440 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
441 SUnit *SU = &SUnits[i];
442 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
443 I != E; ++I) {
444 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
445 "Wrong topological sorting");
448 #endif
451 /// AddPred - Updates the topological ordering to accomodate an edge
452 /// to be added from SUnit X to SUnit Y.
453 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
454 int UpperBound, LowerBound;
455 LowerBound = Node2Index[Y->NodeNum];
456 UpperBound = Node2Index[X->NodeNum];
457 bool HasLoop = false;
458 // Is Ord(X) < Ord(Y) ?
459 if (LowerBound < UpperBound) {
460 // Update the topological order.
461 Visited.reset();
462 DFS(Y, UpperBound, HasLoop);
463 assert(!HasLoop && "Inserted edge creates a loop!");
464 // Recompute topological indexes.
465 Shift(Visited, LowerBound, UpperBound);
469 /// RemovePred - Updates the topological ordering to accomodate an
470 /// an edge to be removed from the specified node N from the predecessors
471 /// of the current node M.
472 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
473 // InitDAGTopologicalSorting();
476 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
477 /// all nodes affected by the edge insertion. These nodes will later get new
478 /// topological indexes by means of the Shift method.
479 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
480 bool& HasLoop) {
481 std::vector<const SUnit*> WorkList;
482 WorkList.reserve(SUnits.size());
484 WorkList.push_back(SU);
485 do {
486 SU = WorkList.back();
487 WorkList.pop_back();
488 Visited.set(SU->NodeNum);
489 for (int I = SU->Succs.size()-1; I >= 0; --I) {
490 int s = SU->Succs[I].getSUnit()->NodeNum;
491 if (Node2Index[s] == UpperBound) {
492 HasLoop = true;
493 return;
495 // Visit successors if not already and in affected region.
496 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
497 WorkList.push_back(SU->Succs[I].getSUnit());
500 } while (!WorkList.empty());
503 /// Shift - Renumber the nodes so that the topological ordering is
504 /// preserved.
505 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
506 int UpperBound) {
507 std::vector<int> L;
508 int shift = 0;
509 int i;
511 for (i = LowerBound; i <= UpperBound; ++i) {
512 // w is node at topological index i.
513 int w = Index2Node[i];
514 if (Visited.test(w)) {
515 // Unmark.
516 Visited.reset(w);
517 L.push_back(w);
518 shift = shift + 1;
519 } else {
520 Allocate(w, i - shift);
524 for (unsigned j = 0; j < L.size(); ++j) {
525 Allocate(L[j], i - shift);
526 i = i + 1;
531 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
532 /// create a cycle.
533 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
534 if (IsReachable(TargetSU, SU))
535 return true;
536 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
537 I != E; ++I)
538 if (I->isAssignedRegDep() &&
539 IsReachable(TargetSU, I->getSUnit()))
540 return true;
541 return false;
544 /// IsReachable - Checks if SU is reachable from TargetSU.
545 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
546 const SUnit *TargetSU) {
547 // If insertion of the edge SU->TargetSU would create a cycle
548 // then there is a path from TargetSU to SU.
549 int UpperBound, LowerBound;
550 LowerBound = Node2Index[TargetSU->NodeNum];
551 UpperBound = Node2Index[SU->NodeNum];
552 bool HasLoop = false;
553 // Is Ord(TargetSU) < Ord(SU) ?
554 if (LowerBound < UpperBound) {
555 Visited.reset();
556 // There may be a path from TargetSU to SU. Check for it.
557 DFS(TargetSU, UpperBound, HasLoop);
559 return HasLoop;
562 /// Allocate - assign the topological index to the node n.
563 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
564 Node2Index[n] = index;
565 Index2Node[index] = n;
568 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
569 std::vector<SUnit> &sunits)
570 : SUnits(sunits) {}
572 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}