blob: 561633701c16a16881ec6907146710cc3afea57a [file] [log] [blame]
Evan Chengab495562006-01-25 09:14:32 +00001//===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
Evan Cheng31272342006-01-23 08:26:10 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Evan Cheng and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner01aa7522006-03-06 17:58:04 +000010// This implements bottom-up and top-down list schedulers, using standard
11// algorithms. The basic approach uses a priority queue of available nodes to
12// schedule. One at a time, nodes are taken from the priority queue (thus in
13// priority order), checked for legality to schedule, and emitted if legal.
14//
15// Nodes may not be legal to schedule either due to structural hazards (e.g.
16// pipeline or resource constraints) or because an input to the instruction has
17// not completed execution.
Evan Cheng31272342006-01-23 08:26:10 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "sched"
22#include "llvm/CodeGen/ScheduleDAG.h"
Evan Cheng31272342006-01-23 08:26:10 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
Evan Chengab495562006-01-25 09:14:32 +000025#include "llvm/Support/Debug.h"
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000026#include "llvm/ADT/Statistic.h"
Evan Chengab495562006-01-25 09:14:32 +000027#include <climits>
28#include <iostream>
Evan Cheng31272342006-01-23 08:26:10 +000029#include <queue>
Evan Cheng4e3904f2006-03-02 21:38:29 +000030#include <set>
31#include <vector>
Evan Cheng31272342006-01-23 08:26:10 +000032using namespace llvm;
33
Evan Chengab495562006-01-25 09:14:32 +000034namespace {
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000035 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
36 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
Evan Cheng31272342006-01-23 08:26:10 +000037
Chris Lattner12c6d892006-03-08 04:41:06 +000038 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
39 /// a group of nodes flagged together.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000040 struct SUnit {
41 SDNode *Node; // Representative node.
42 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
43 std::set<SUnit*> Preds; // All real predecessors.
44 std::set<SUnit*> ChainPreds; // All chain predecessors.
45 std::set<SUnit*> Succs; // All real successors.
46 std::set<SUnit*> ChainSuccs; // All chain successors.
Chris Lattner12c6d892006-03-08 04:41:06 +000047 short NumPredsLeft; // # of preds not scheduled.
48 short NumSuccsLeft; // # of succs not scheduled.
49 short NumChainPredsLeft; // # of chain preds not scheduled.
50 short NumChainSuccsLeft; // # of chain succs not scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000051 bool isTwoAddress : 1; // Is a two-address instruction.
52 bool isDefNUseOperand : 1; // Is a def&use operand.
53 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000054 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattnerfd22d422006-03-08 05:18:27 +000055 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000056
Chris Lattnerfd22d422006-03-08 05:18:27 +000057 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000058 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng4e3904f2006-03-02 21:38:29 +000059 NumChainPredsLeft(0), NumChainSuccsLeft(0),
Evan Cheng5e9a6952006-03-03 06:23:43 +000060 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattnerfd22d422006-03-08 05:18:27 +000061 Latency(0), CycleBound(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000062
63 void dump(const SelectionDAG *G, bool All=true) const;
64 };
65}
Evan Chengab495562006-01-25 09:14:32 +000066
67void SUnit::dump(const SelectionDAG *G, bool All) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000068 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000069 Node->dump(G);
70 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000071 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000072 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000073 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000074 FlaggedNodes[i]->dump(G);
75 std::cerr << "\n";
76 }
77 }
78
79 if (All) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +000080 std::cerr << " # preds left : " << NumPredsLeft << "\n";
81 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
82 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
83 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
84 std::cerr << " Latency : " << Latency << "\n";
Evan Chengc4c339c2006-01-26 00:30:29 +000085
Evan Chengab495562006-01-25 09:14:32 +000086 if (Preds.size() != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +000087 std::cerr << " Predecessors:\n";
Jeff Cohen55c11732006-03-03 03:25:07 +000088 for (std::set<SUnit*>::const_iterator I = Preds.begin(),
Evan Cheng4e3904f2006-03-02 21:38:29 +000089 E = Preds.end(); I != E; ++I) {
Evan Chengab495562006-01-25 09:14:32 +000090 std::cerr << " ";
Evan Cheng4e3904f2006-03-02 21:38:29 +000091 (*I)->dump(G, false);
Evan Chengab495562006-01-25 09:14:32 +000092 }
93 }
94 if (ChainPreds.size() != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +000095 std::cerr << " Chained Preds:\n";
Jeff Cohen55c11732006-03-03 03:25:07 +000096 for (std::set<SUnit*>::const_iterator I = ChainPreds.begin(),
Evan Cheng4e3904f2006-03-02 21:38:29 +000097 E = ChainPreds.end(); I != E; ++I) {
Evan Chengab495562006-01-25 09:14:32 +000098 std::cerr << " ";
Evan Cheng4e3904f2006-03-02 21:38:29 +000099 (*I)->dump(G, false);
Evan Chengab495562006-01-25 09:14:32 +0000100 }
101 }
102 if (Succs.size() != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000103 std::cerr << " Successors:\n";
Jeff Cohen55c11732006-03-03 03:25:07 +0000104 for (std::set<SUnit*>::const_iterator I = Succs.begin(),
Evan Cheng4e3904f2006-03-02 21:38:29 +0000105 E = Succs.end(); I != E; ++I) {
Evan Chengab495562006-01-25 09:14:32 +0000106 std::cerr << " ";
Evan Cheng4e3904f2006-03-02 21:38:29 +0000107 (*I)->dump(G, false);
Evan Chengab495562006-01-25 09:14:32 +0000108 }
109 }
110 if (ChainSuccs.size() != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000111 std::cerr << " Chained succs:\n";
Jeff Cohen55c11732006-03-03 03:25:07 +0000112 for (std::set<SUnit*>::const_iterator I = ChainSuccs.begin(),
Evan Cheng4e3904f2006-03-02 21:38:29 +0000113 E = ChainSuccs.end(); I != E; ++I) {
Evan Chengab495562006-01-25 09:14:32 +0000114 std::cerr << " ";
Evan Cheng4e3904f2006-03-02 21:38:29 +0000115 (*I)->dump(G, false);
Evan Chengab495562006-01-25 09:14:32 +0000116 }
117 }
118 }
119}
120
Chris Lattner9df64752006-03-09 06:35:14 +0000121//===----------------------------------------------------------------------===//
122// SchedulingPriorityQueue - This interface is used to plug different
123// priorities computation algorithms into the list scheduler. It implements the
124// interface of a standard priority queue, where nodes are inserted in arbitrary
125// order and returned in priority order. The computation of the priority and
126// the representation of the queue are totally up to the implementation to
127// decide.
128//
129class SchedulingPriorityQueue {
130public:
131 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000132
Chris Lattner9df64752006-03-09 06:35:14 +0000133 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
134 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000135
Chris Lattner9df64752006-03-09 06:35:14 +0000136 virtual bool empty() const = 0;
137 virtual void push(SUnit *U) = 0;
138 virtual SUnit *pop() = 0;
139};
Chris Lattnerfd22d422006-03-08 05:18:27 +0000140
141
Chris Lattnere50c0922006-03-05 22:45:01 +0000142
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000143namespace {
Evan Cheng31272342006-01-23 08:26:10 +0000144/// ScheduleDAGList - List scheduler.
Evan Cheng31272342006-01-23 08:26:10 +0000145class ScheduleDAGList : public ScheduleDAG {
146private:
Evan Chengab495562006-01-25 09:14:32 +0000147 // SDNode to SUnit mapping (many to one).
148 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000149 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000150 std::vector<SUnit*> Sequence;
151 // Current scheduling cycle.
152 unsigned CurrCycle;
Chris Lattner42e20262006-03-08 04:54:34 +0000153
154 // The scheduling units.
155 std::vector<SUnit> SUnits;
Evan Cheng31272342006-01-23 08:26:10 +0000156
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000157 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
158 /// it is top-down.
159 bool isBottomUp;
160
Chris Lattner9df64752006-03-09 06:35:14 +0000161 /// PriorityQueue - The priority queue to use.
162 SchedulingPriorityQueue *PriorityQueue;
163
Chris Lattnere50c0922006-03-05 22:45:01 +0000164 /// HazardRec - The hazard recognizer to use.
Chris Lattner543832d2006-03-08 04:25:59 +0000165 HazardRecognizer *HazardRec;
Chris Lattnere50c0922006-03-05 22:45:01 +0000166
Evan Cheng31272342006-01-23 08:26:10 +0000167public:
168 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
Chris Lattnere50c0922006-03-05 22:45:01 +0000169 const TargetMachine &tm, bool isbottomup,
Chris Lattner9df64752006-03-09 06:35:14 +0000170 SchedulingPriorityQueue *priorityqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000171 HazardRecognizer *HR)
Evan Chengc4c339c2006-01-26 00:30:29 +0000172 : ScheduleDAG(listSchedulingBURR, dag, bb, tm),
Chris Lattner9df64752006-03-09 06:35:14 +0000173 CurrCycle(0), isBottomUp(isbottomup),
174 PriorityQueue(priorityqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000175 }
Evan Chengab495562006-01-25 09:14:32 +0000176
177 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000178 delete HazardRec;
Chris Lattner9df64752006-03-09 06:35:14 +0000179 delete PriorityQueue;
Evan Chengab495562006-01-25 09:14:32 +0000180 }
Evan Cheng31272342006-01-23 08:26:10 +0000181
182 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000183
Evan Chengab495562006-01-25 09:14:32 +0000184 void dump() const;
185
186private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000187 SUnit *NewSUnit(SDNode *N);
Chris Lattnerfd22d422006-03-08 05:18:27 +0000188 void ReleasePred(SchedulingPriorityQueue &Avail,
189 SUnit *PredSU, bool isChain = false);
190 void ReleaseSucc(SchedulingPriorityQueue &Avail,
191 SUnit *SuccSU, bool isChain = false);
192 void ScheduleNodeBottomUp(SchedulingPriorityQueue &Avail, SUnit *SU);
193 void ScheduleNodeTopDown(SchedulingPriorityQueue &Avail, SUnit *SU);
194 void ListScheduleTopDown(SchedulingPriorityQueue &Available);
195 void ListScheduleBottomUp(SchedulingPriorityQueue &Available);
Evan Chengab495562006-01-25 09:14:32 +0000196 void BuildSchedUnits();
197 void EmitSchedule();
198};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000199} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000200
Chris Lattner47639db2006-03-06 00:22:00 +0000201HazardRecognizer::~HazardRecognizer() {}
202
Evan Chengc4c339c2006-01-26 00:30:29 +0000203
204/// NewSUnit - Creates a new SUnit and return a ptr to it.
205SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000206 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000207 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000208}
209
210/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
211/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000212void ScheduleDAGList::ReleasePred(SchedulingPriorityQueue &Available,
Chris Lattner7a36d972006-03-05 20:21:55 +0000213 SUnit *PredSU, bool isChain) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000214 // FIXME: the distance between two nodes is not always == the predecessor's
215 // latency. For example, the reader can very well read the register written
216 // by the predecessor later than the issue cycle. It also depends on the
217 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000218 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000219
Evan Chengc5c06582006-03-06 06:08:54 +0000220 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000221 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000222 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000223 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000224
Evan Chengab495562006-01-25 09:14:32 +0000225#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000226 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000227 std::cerr << "*** List scheduling failed! ***\n";
228 PredSU->dump(&DAG);
229 std::cerr << " has been released too many times!\n";
230 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000231 }
Evan Chengab495562006-01-25 09:14:32 +0000232#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000233
234 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
235 // EntryToken has to go last! Special case it here.
236 if (PredSU->Node->getOpcode() != ISD::EntryToken)
237 Available.push(PredSU);
Evan Chengab495562006-01-25 09:14:32 +0000238 }
Evan Chengab495562006-01-25 09:14:32 +0000239}
240
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000241/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
242/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000243void ScheduleDAGList::ReleaseSucc(SchedulingPriorityQueue &Available,
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000244 SUnit *SuccSU, bool isChain) {
245 // FIXME: the distance between two nodes is not always == the predecessor's
246 // latency. For example, the reader can very well read the register written
247 // by the predecessor later than the issue cycle. It also depends on the
248 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000249 SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000250
Evan Chengc5c06582006-03-06 06:08:54 +0000251 if (!isChain)
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000252 SuccSU->NumPredsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000253 else
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000254 SuccSU->NumChainPredsLeft--;
255
256#ifndef NDEBUG
257 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
258 std::cerr << "*** List scheduling failed! ***\n";
259 SuccSU->dump(&DAG);
260 std::cerr << " has been released too many times!\n";
261 abort();
262 }
263#endif
264
265 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0)
266 Available.push(SuccSU);
267}
268
269/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
270/// count of its predecessors. If a predecessor pending count is zero, add it to
271/// the Available queue.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000272void ScheduleDAGList::ScheduleNodeBottomUp(SchedulingPriorityQueue &Available,
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000273 SUnit *SU) {
Evan Cheng5e9a6952006-03-03 06:23:43 +0000274 DEBUG(std::cerr << "*** Scheduling: ");
275 DEBUG(SU->dump(&DAG, false));
276
Evan Chengab495562006-01-25 09:14:32 +0000277 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000278
279 // Bottom up: release predecessors
Evan Cheng4e3904f2006-03-02 21:38:29 +0000280 for (std::set<SUnit*>::iterator I1 = SU->Preds.begin(),
281 E1 = SU->Preds.end(); I1 != E1; ++I1) {
Chris Lattner7a36d972006-03-05 20:21:55 +0000282 ReleasePred(Available, *I1);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000283 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000284 }
285 for (std::set<SUnit*>::iterator I2 = SU->ChainPreds.begin(),
286 E2 = SU->ChainPreds.end(); I2 != E2; ++I2)
Chris Lattner7a36d972006-03-05 20:21:55 +0000287 ReleasePred(Available, *I2, true);
Evan Chengab495562006-01-25 09:14:32 +0000288
289 CurrCycle++;
290}
291
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000292/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
293/// count of its successors. If a successor pending count is zero, add it to
294/// the Available queue.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000295void ScheduleDAGList::ScheduleNodeTopDown(SchedulingPriorityQueue &Available,
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000296 SUnit *SU) {
297 DEBUG(std::cerr << "*** Scheduling: ");
298 DEBUG(SU->dump(&DAG, false));
299
300 Sequence.push_back(SU);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000301
302 // Bottom up: release successors.
303 for (std::set<SUnit*>::iterator I1 = SU->Succs.begin(),
304 E1 = SU->Succs.end(); I1 != E1; ++I1) {
305 ReleaseSucc(Available, *I1);
306 SU->NumSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000307 }
308 for (std::set<SUnit*>::iterator I2 = SU->ChainSuccs.begin(),
309 E2 = SU->ChainSuccs.end(); I2 != E2; ++I2)
310 ReleaseSucc(Available, *I2, true);
311
312 CurrCycle++;
313}
314
Evan Chengab495562006-01-25 09:14:32 +0000315/// isReady - True if node's lower cycle bound is less or equal to the current
316/// scheduling cycle. Always true if all nodes have uniform latency 1.
317static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
318 return SU->CycleBound <= CurrCycle;
319}
320
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000321/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
322/// schedulers.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000323void ScheduleDAGList::ListScheduleBottomUp(SchedulingPriorityQueue &Available) {
Chris Lattner7a36d972006-03-05 20:21:55 +0000324 // Add root to Available queue.
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000325 Available.push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000326
327 // While Available queue is not empty, grab the node with the highest
328 // priority. If it is not ready put it back. Schedule the node.
329 std::vector<SUnit*> NotReady;
330 while (!Available.empty()) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000331 SUnit *CurrNode = Available.pop();
Evan Chengab495562006-01-25 09:14:32 +0000332
Evan Chengab495562006-01-25 09:14:32 +0000333 while (!isReady(CurrNode, CurrCycle)) {
334 NotReady.push_back(CurrNode);
Chris Lattnerfd22d422006-03-08 05:18:27 +0000335 CurrNode = Available.pop();
Evan Chengab495562006-01-25 09:14:32 +0000336 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000337
338 // Add the nodes that aren't ready back onto the available list.
339 while (!NotReady.empty()) {
340 Available.push(NotReady.back());
341 NotReady.pop_back();
342 }
Evan Chengab495562006-01-25 09:14:32 +0000343
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000344 ScheduleNodeBottomUp(Available, CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000345 }
346
347 // Add entry node last
348 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
349 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000350 Sequence.push_back(Entry);
351 }
352
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000353 // Reverse the order if it is bottom up.
354 std::reverse(Sequence.begin(), Sequence.end());
355
356
Evan Chengab495562006-01-25 09:14:32 +0000357#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000358 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000359 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000360 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
361 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000362 if (!AnyNotSched)
363 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000364 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000365 std::cerr << "has not been scheduled!\n";
366 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000367 }
Evan Chengab495562006-01-25 09:14:32 +0000368 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000369 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000370#endif
Evan Chengab495562006-01-25 09:14:32 +0000371}
372
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000373/// ListScheduleTopDown - The main loop of list scheduling for top-down
374/// schedulers.
Chris Lattnerfd22d422006-03-08 05:18:27 +0000375void ScheduleDAGList::ListScheduleTopDown(SchedulingPriorityQueue &Available) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000376 // Emit the entry node first.
377 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
378 ScheduleNodeTopDown(Available, Entry);
Chris Lattner543832d2006-03-08 04:25:59 +0000379 HazardRec->EmitInstruction(Entry->Node);
Chris Lattnere50c0922006-03-05 22:45:01 +0000380
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000381 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000382 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000383 // It is available if it has no predecessors.
Chris Lattner42e20262006-03-08 04:54:34 +0000384 if ((SUnits[i].Preds.size() + SUnits[i].ChainPreds.size()) == 0 &&
385 &SUnits[i] != Entry)
386 Available.push(&SUnits[i]);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000387 }
388
389 // While Available queue is not empty, grab the node with the highest
390 // priority. If it is not ready put it back. Schedule the node.
391 std::vector<SUnit*> NotReady;
392 while (!Available.empty()) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000393 SUnit *FoundNode = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000394
Chris Lattnere50c0922006-03-05 22:45:01 +0000395 bool HasNoopHazards = false;
396 do {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000397 SUnit *CurNode = Available.pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000398
399 // Get the node represented by this SUnit.
400 SDNode *N = CurNode->Node;
401 // If this is a pseudo op, like copyfromreg, look to see if there is a
402 // real target node flagged to it. If so, use the target node.
403 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
404 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
405 N = CurNode->FlaggedNodes[i];
406
Chris Lattner543832d2006-03-08 04:25:59 +0000407 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
Chris Lattnere50c0922006-03-05 22:45:01 +0000408 if (HT == HazardRecognizer::NoHazard) {
Chris Lattner0c801bd2006-03-07 05:40:43 +0000409 FoundNode = CurNode;
Chris Lattnere50c0922006-03-05 22:45:01 +0000410 break;
411 }
412
413 // Remember if this is a noop hazard.
414 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
415
Chris Lattner0c801bd2006-03-07 05:40:43 +0000416 NotReady.push_back(CurNode);
Chris Lattnere50c0922006-03-05 22:45:01 +0000417 } while (!Available.empty());
418
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000419 // Add the nodes that aren't ready back onto the available list.
420 while (!NotReady.empty()) {
421 Available.push(NotReady.back());
422 NotReady.pop_back();
423 }
Chris Lattnere50c0922006-03-05 22:45:01 +0000424
425 // If we found a node to schedule, do it now.
426 if (FoundNode) {
427 ScheduleNodeTopDown(Available, FoundNode);
Chris Lattner543832d2006-03-08 04:25:59 +0000428 HazardRec->EmitInstruction(FoundNode->Node);
Chris Lattnere50c0922006-03-05 22:45:01 +0000429 } else if (!HasNoopHazards) {
430 // Otherwise, we have a pipeline stall, but no other problem, just advance
431 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000432 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000433 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000434 ++NumStalls;
Chris Lattnere50c0922006-03-05 22:45:01 +0000435 } else {
436 // Otherwise, we have no instructions to issue and we have instructions
437 // that will fault if we don't do this right. This is the case for
438 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000439 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000440 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000441 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000442 ++NumNoops;
Chris Lattnere50c0922006-03-05 22:45:01 +0000443 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000444 }
445
446#ifndef NDEBUG
447 // Verify that all SUnits were scheduled.
448 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000449 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
450 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000451 if (!AnyNotSched)
452 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000453 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000454 std::cerr << "has not been scheduled!\n";
455 AnyNotSched = true;
456 }
457 }
458 assert(!AnyNotSched);
459#endif
460}
461
462
Evan Chengab495562006-01-25 09:14:32 +0000463void ScheduleDAGList::BuildSchedUnits() {
Chris Lattner42e20262006-03-08 04:54:34 +0000464 // Reserve entries in the vector for each of the SUnits we are creating. This
465 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
466 // invalidated.
467 SUnits.reserve(NodeCount);
468
Evan Chengc4c339c2006-01-26 00:30:29 +0000469 // Pass 1: create the SUnit's.
Jeff Cohenfb206162006-01-25 17:17:49 +0000470 for (unsigned i = 0, NC = NodeCount; i < NC; i++) {
Evan Chengab495562006-01-25 09:14:32 +0000471 NodeInfo *NI = &Info[i];
472 SDNode *N = NI->Node;
Evan Chengc4c339c2006-01-26 00:30:29 +0000473 if (isPassiveNode(N))
474 continue;
Evan Chengab495562006-01-25 09:14:32 +0000475
Evan Chengc4c339c2006-01-26 00:30:29 +0000476 SUnit *SU;
477 if (NI->isInGroup()) {
478 if (NI != NI->Group->getBottom()) // Bottom up, so only look at bottom
479 continue; // node of the NodeGroup
Evan Chengab495562006-01-25 09:14:32 +0000480
Evan Chengc4c339c2006-01-26 00:30:29 +0000481 SU = NewSUnit(N);
482 // Find the flagged nodes.
483 SDOperand FlagOp = N->getOperand(N->getNumOperands() - 1);
484 SDNode *Flag = FlagOp.Val;
485 unsigned ResNo = FlagOp.ResNo;
486 while (Flag->getValueType(ResNo) == MVT::Flag) {
487 NodeInfo *FNI = getNI(Flag);
488 assert(FNI->Group == NI->Group);
489 SU->FlaggedNodes.insert(SU->FlaggedNodes.begin(), Flag);
490 SUnitMap[Flag] = SU;
Evan Chengab495562006-01-25 09:14:32 +0000491
Evan Chengc4c339c2006-01-26 00:30:29 +0000492 FlagOp = Flag->getOperand(Flag->getNumOperands() - 1);
493 Flag = FlagOp.Val;
494 ResNo = FlagOp.ResNo;
495 }
496 } else {
497 SU = NewSUnit(N);
498 }
499 SUnitMap[N] = SU;
Chris Lattner9df64752006-03-09 06:35:14 +0000500
501 // FIXME: assumes uniform latency for now.
502 SU->Latency = 1;
Evan Chengc4c339c2006-01-26 00:30:29 +0000503 }
Evan Chengab495562006-01-25 09:14:32 +0000504
Evan Chengc4c339c2006-01-26 00:30:29 +0000505 // Pass 2: add the preds, succs, etc.
Chris Lattner42e20262006-03-08 04:54:34 +0000506 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
507 SUnit *SU = &SUnits[i];
Evan Chengc4c339c2006-01-26 00:30:29 +0000508 SDNode *N = SU->Node;
509 NodeInfo *NI = getNI(N);
Evan Cheng5e9a6952006-03-03 06:23:43 +0000510
511 if (N->isTargetOpcode() && TII->isTwoAddrInstr(N->getTargetOpcode()))
512 SU->isTwoAddress = true;
Evan Chengc4c339c2006-01-26 00:30:29 +0000513
514 if (NI->isInGroup()) {
515 // Find all predecessors (of the group).
516 NodeGroupOpIterator NGOI(NI);
517 while (!NGOI.isEnd()) {
518 SDOperand Op = NGOI.next();
519 SDNode *OpN = Op.Val;
520 MVT::ValueType VT = OpN->getValueType(Op.ResNo);
521 NodeInfo *OpNI = getNI(OpN);
522 if (OpNI->Group != NI->Group && !isPassiveNode(OpN)) {
523 assert(VT != MVT::Flag);
524 SUnit *OpSU = SUnitMap[OpN];
525 if (VT == MVT::Other) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000526 if (SU->ChainPreds.insert(OpSU).second)
527 SU->NumChainPredsLeft++;
528 if (OpSU->ChainSuccs.insert(SU).second)
529 OpSU->NumChainSuccsLeft++;
Evan Chengc4c339c2006-01-26 00:30:29 +0000530 } else {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000531 if (SU->Preds.insert(OpSU).second)
532 SU->NumPredsLeft++;
533 if (OpSU->Succs.insert(SU).second)
534 OpSU->NumSuccsLeft++;
Evan Chengab495562006-01-25 09:14:32 +0000535 }
Evan Chengab495562006-01-25 09:14:32 +0000536 }
537 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000538 } else {
539 // Find node predecessors.
540 for (unsigned j = 0, e = N->getNumOperands(); j != e; j++) {
541 SDOperand Op = N->getOperand(j);
542 SDNode *OpN = Op.Val;
543 MVT::ValueType VT = OpN->getValueType(Op.ResNo);
544 if (!isPassiveNode(OpN)) {
545 assert(VT != MVT::Flag);
546 SUnit *OpSU = SUnitMap[OpN];
547 if (VT == MVT::Other) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000548 if (SU->ChainPreds.insert(OpSU).second)
549 SU->NumChainPredsLeft++;
550 if (OpSU->ChainSuccs.insert(SU).second)
551 OpSU->NumChainSuccsLeft++;
Evan Chengc4c339c2006-01-26 00:30:29 +0000552 } else {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000553 if (SU->Preds.insert(OpSU).second)
554 SU->NumPredsLeft++;
555 if (OpSU->Succs.insert(SU).second)
556 OpSU->NumSuccsLeft++;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000557 if (j == 0 && SU->isTwoAddress)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000558 OpSU->isDefNUseOperand = true;
Evan Chengc4c339c2006-01-26 00:30:29 +0000559 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000560 }
561 }
Evan Chengab495562006-01-25 09:14:32 +0000562 }
563 }
Evan Chengab495562006-01-25 09:14:32 +0000564}
565
566/// EmitSchedule - Emit the machine code in scheduled order.
567void ScheduleDAGList::EmitSchedule() {
568 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000569 if (SUnit *SU = Sequence[i]) {
570 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++) {
571 SDNode *N = SU->FlaggedNodes[j];
572 EmitNode(getNI(N));
573 }
574 EmitNode(getNI(SU->Node));
575 } else {
576 // Null SUnit* is a noop.
577 EmitNoop();
Evan Chengab495562006-01-25 09:14:32 +0000578 }
Evan Chengab495562006-01-25 09:14:32 +0000579 }
580}
581
582/// dump - dump the schedule.
583void ScheduleDAGList::dump() const {
584 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000585 if (SUnit *SU = Sequence[i])
586 SU->dump(&DAG, false);
587 else
588 std::cerr << "**** NOOP ****\n";
Evan Chengab495562006-01-25 09:14:32 +0000589 }
590}
591
592/// Schedule - Schedule the DAG using list scheduling.
593/// FIXME: Right now it only supports the burr (bottom up register reducing)
594/// heuristic.
Evan Cheng31272342006-01-23 08:26:10 +0000595void ScheduleDAGList::Schedule() {
Evan Chengab495562006-01-25 09:14:32 +0000596 DEBUG(std::cerr << "********** List Scheduling **********\n");
597
598 // Build scheduling units.
599 BuildSchedUnits();
Chris Lattnerfd22d422006-03-08 05:18:27 +0000600
Chris Lattner9df64752006-03-09 06:35:14 +0000601 PriorityQueue->initNodes(SUnits);
602
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000603 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
604 if (isBottomUp)
Chris Lattner9df64752006-03-09 06:35:14 +0000605 ListScheduleBottomUp(*PriorityQueue);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000606 else
Chris Lattner9df64752006-03-09 06:35:14 +0000607 ListScheduleTopDown(*PriorityQueue);
608
609 PriorityQueue->releaseState();
610
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000611 DEBUG(std::cerr << "*** Final schedule ***\n");
612 DEBUG(dump());
613 DEBUG(std::cerr << "\n");
614
Evan Chengab495562006-01-25 09:14:32 +0000615 // Emit in scheduled order
616 EmitSchedule();
Evan Cheng31272342006-01-23 08:26:10 +0000617}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000618
Chris Lattner9df64752006-03-09 06:35:14 +0000619//===----------------------------------------------------------------------===//
620// RegReductionPriorityQueue Implementation
621//===----------------------------------------------------------------------===//
622//
623// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
624// to reduce register pressure.
625//
626namespace {
627 class RegReductionPriorityQueue;
628
629 /// Sorting functions for the Available queue.
630 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
631 RegReductionPriorityQueue *SPQ;
632 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
633 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
634
635 bool operator()(const SUnit* left, const SUnit* right) const;
636 };
637} // end anonymous namespace
638
639namespace {
640 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
641 // SUnits - The SUnits for the current graph.
642 const std::vector<SUnit> *SUnits;
643
644 // SethiUllmanNumbers - The SethiUllman number for each node.
645 std::vector<int> SethiUllmanNumbers;
646
647 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
648 public:
649 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
650 }
651
652 void initNodes(const std::vector<SUnit> &sunits) {
653 SUnits = &sunits;
654 // Calculate node priorities.
655 CalculatePriorities();
656 }
657 void releaseState() {
658 SUnits = 0;
659 SethiUllmanNumbers.clear();
660 }
661
662 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
663 assert(NodeNum < SethiUllmanNumbers.size());
664 return SethiUllmanNumbers[NodeNum];
665 }
666
667 bool empty() const { return Queue.empty(); }
668
669 void push(SUnit *U) {
670 Queue.push(U);
671 }
672 SUnit *pop() {
673 SUnit *V = Queue.top();
674 Queue.pop();
675 return V;
676 }
677 private:
678 void CalculatePriorities();
679 int CalcNodePriority(const SUnit *SU);
680 };
681}
682
683bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
684 unsigned LeftNum = left->NodeNum;
685 unsigned RightNum = right->NodeNum;
686
687 int LBonus = (int)left ->isDefNUseOperand;
688 int RBonus = (int)right->isDefNUseOperand;
689
690 // Special tie breaker: if two nodes share a operand, the one that
691 // use it as a def&use operand is preferred.
692 if (left->isTwoAddress && !right->isTwoAddress) {
693 SDNode *DUNode = left->Node->getOperand(0).Val;
694 if (DUNode->isOperand(right->Node))
695 LBonus++;
696 }
697 if (!left->isTwoAddress && right->isTwoAddress) {
698 SDNode *DUNode = right->Node->getOperand(0).Val;
699 if (DUNode->isOperand(left->Node))
700 RBonus++;
701 }
702
703 // Priority1 is just the number of live range genned.
704 int LPriority1 = left ->NumPredsLeft - LBonus;
705 int RPriority1 = right->NumPredsLeft - RBonus;
706 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
707 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
708
709 if (LPriority1 > RPriority1)
710 return true;
711 else if (LPriority1 == RPriority1)
712 if (LPriority2 < RPriority2)
713 return true;
714 else if (LPriority2 == RPriority2)
715 if (left->CycleBound > right->CycleBound)
716 return true;
717
718 return false;
719}
720
721
722/// CalcNodePriority - Priority is the Sethi Ullman number.
723/// Smaller number is the higher priority.
724int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
725 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
726 if (SethiUllmanNumber != INT_MIN)
727 return SethiUllmanNumber;
728
729 if (SU->Preds.size() == 0) {
730 SethiUllmanNumber = 1;
731 } else {
732 int Extra = 0;
733 for (std::set<SUnit*>::iterator I = SU->Preds.begin(),
734 E = SU->Preds.end(); I != E; ++I) {
735 SUnit *PredSU = *I;
736 int PredSethiUllman = CalcNodePriority(PredSU);
737 if (PredSethiUllman > SethiUllmanNumber) {
738 SethiUllmanNumber = PredSethiUllman;
739 Extra = 0;
740 } else if (PredSethiUllman == SethiUllmanNumber)
741 Extra++;
742 }
743
744 if (SU->Node->getOpcode() != ISD::TokenFactor)
745 SethiUllmanNumber += Extra;
746 else
747 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
748 }
749
750 return SethiUllmanNumber;
751}
752
753/// CalculatePriorities - Calculate priorities of all scheduling units.
754void RegReductionPriorityQueue::CalculatePriorities() {
755 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
756
757 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
758 CalcNodePriority(&(*SUnits)[i]);
759}
760
761
762//===----------------------------------------------------------------------===//
763// Public Constructor Functions
764//===----------------------------------------------------------------------===//
765
Evan Chengab495562006-01-25 09:14:32 +0000766llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
767 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +0000768 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +0000769 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +0000770 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000771}
772
Chris Lattner47639db2006-03-06 00:22:00 +0000773/// createTDListDAGScheduler - This creates a top-down list scheduler with the
774/// specified hazard recognizer.
775ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
776 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +0000777 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +0000778 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
779 new RegReductionPriorityQueue(),
780 HR);
Evan Cheng31272342006-01-23 08:26:10 +0000781}