blob: 5b973382b21ebe8bdeaa2892d0297c50fd03c313 [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>
Chris Lattnerd4130372006-03-09 07:15:18 +000032#include "llvm/Support/CommandLine.h"
Evan Cheng31272342006-01-23 08:26:10 +000033using namespace llvm;
34
Evan Chengab495562006-01-25 09:14:32 +000035namespace {
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000036 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
Evan Cheng31272342006-01-23 08:26:10 +000038
Chris Lattner12c6d892006-03-08 04:41:06 +000039 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40 /// a group of nodes flagged together.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000041 struct SUnit {
42 SDNode *Node; // Representative node.
43 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
Chris Lattner578d8fc2006-03-11 22:24:20 +000044
45 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
46 // is true if the edge is a token chain edge, false if it is a value edge.
47 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
48 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
49
Chris Lattner12c6d892006-03-08 04:41:06 +000050 short NumPredsLeft; // # of preds not scheduled.
51 short NumSuccsLeft; // # of succs not scheduled.
52 short NumChainPredsLeft; // # of chain preds not scheduled.
53 short NumChainSuccsLeft; // # of chain succs not scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000054 bool isTwoAddress : 1; // Is a two-address instruction.
55 bool isDefNUseOperand : 1; // Is a def&use operand.
Chris Lattner349e9dd2006-03-10 05:51:05 +000056 bool isAvailable : 1; // True once available.
57 bool isScheduled : 1; // True once scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000058 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000059 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattner356183d2006-03-11 22:44:37 +000060 unsigned Cycle; // Once scheduled, the cycle of the op.
Chris Lattnerfd22d422006-03-08 05:18:27 +000061 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000062
Chris Lattnerfd22d422006-03-08 05:18:27 +000063 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000064 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng4e3904f2006-03-02 21:38:29 +000065 NumChainPredsLeft(0), NumChainSuccsLeft(0),
Evan Cheng5e9a6952006-03-03 06:23:43 +000066 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattner349e9dd2006-03-10 05:51:05 +000067 isAvailable(false), isScheduled(false),
Chris Lattner356183d2006-03-11 22:44:37 +000068 Latency(0), CycleBound(0), Cycle(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000069
Chris Lattnerd4130372006-03-09 07:15:18 +000070 void dump(const SelectionDAG *G) const;
71 void dumpAll(const SelectionDAG *G) const;
Chris Lattneraf5e26c2006-03-08 04:37:58 +000072 };
73}
Evan Chengab495562006-01-25 09:14:32 +000074
Chris Lattnerd4130372006-03-09 07:15:18 +000075void SUnit::dump(const SelectionDAG *G) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000076 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000077 Node->dump(G);
78 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000079 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000080 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000081 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000082 FlaggedNodes[i]->dump(G);
83 std::cerr << "\n";
84 }
85 }
Chris Lattnerd4130372006-03-09 07:15:18 +000086}
Evan Chengab495562006-01-25 09:14:32 +000087
Chris Lattnerd4130372006-03-09 07:15:18 +000088void SUnit::dumpAll(const SelectionDAG *G) const {
89 dump(G);
Evan Chengc4c339c2006-01-26 00:30:29 +000090
Chris Lattnerd4130372006-03-09 07:15:18 +000091 std::cerr << " # preds left : " << NumPredsLeft << "\n";
92 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
93 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
94 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
95 std::cerr << " Latency : " << Latency << "\n";
96
97 if (Preds.size() != 0) {
98 std::cerr << " Predecessors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +000099 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000100 E = Preds.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000101 if (I->second)
102 std::cerr << " ch ";
103 else
104 std::cerr << " val ";
105 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000106 }
107 }
108 if (Succs.size() != 0) {
109 std::cerr << " Successors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000110 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000111 E = Succs.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000112 if (I->second)
113 std::cerr << " ch ";
114 else
115 std::cerr << " val ";
116 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000117 }
118 }
119 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +0000120}
121
Chris Lattner9df64752006-03-09 06:35:14 +0000122//===----------------------------------------------------------------------===//
Chris Lattner9e95acc2006-03-09 06:37:29 +0000123/// SchedulingPriorityQueue - This interface is used to plug different
124/// priorities computation algorithms into the list scheduler. It implements the
125/// interface of a standard priority queue, where nodes are inserted in
126/// arbitrary order and returned in priority order. The computation of the
127/// priority and the representation of the queue are totally up to the
128/// implementation to decide.
129///
130namespace {
Chris Lattner9df64752006-03-09 06:35:14 +0000131class SchedulingPriorityQueue {
132public:
133 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000134
Chris Lattner9df64752006-03-09 06:35:14 +0000135 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
136 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000137
Chris Lattner9df64752006-03-09 06:35:14 +0000138 virtual bool empty() const = 0;
139 virtual void push(SUnit *U) = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000140
141 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
Chris Lattner9df64752006-03-09 06:35:14 +0000142 virtual SUnit *pop() = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000143
144 /// ScheduledNode - As each node is scheduled, this method is invoked. This
145 /// allows the priority function to adjust the priority of node that have
146 /// already been emitted.
147 virtual void ScheduledNode(SUnit *Node) {}
Chris Lattner9df64752006-03-09 06:35:14 +0000148};
Chris Lattner9e95acc2006-03-09 06:37:29 +0000149}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000150
151
Chris Lattnere50c0922006-03-05 22:45:01 +0000152
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000153namespace {
Chris Lattner9e95acc2006-03-09 06:37:29 +0000154//===----------------------------------------------------------------------===//
155/// ScheduleDAGList - The actual list scheduler implementation. This supports
156/// both top-down and bottom-up scheduling.
157///
Evan Cheng31272342006-01-23 08:26:10 +0000158class ScheduleDAGList : public ScheduleDAG {
159private:
Evan Chengab495562006-01-25 09:14:32 +0000160 // SDNode to SUnit mapping (many to one).
161 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000162 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000163 std::vector<SUnit*> Sequence;
Chris Lattner42e20262006-03-08 04:54:34 +0000164
165 // The scheduling units.
166 std::vector<SUnit> SUnits;
Evan Cheng31272342006-01-23 08:26:10 +0000167
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000168 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
169 /// it is top-down.
170 bool isBottomUp;
171
Chris Lattner356183d2006-03-11 22:44:37 +0000172 /// AvailableQueue - The priority queue to use for the available SUnits.
173 ///
174 SchedulingPriorityQueue *AvailableQueue;
Chris Lattner9df64752006-03-09 06:35:14 +0000175
Chris Lattnere50c0922006-03-05 22:45:01 +0000176 /// HazardRec - The hazard recognizer to use.
Chris Lattner543832d2006-03-08 04:25:59 +0000177 HazardRecognizer *HazardRec;
Chris Lattnere50c0922006-03-05 22:45:01 +0000178
Evan Cheng31272342006-01-23 08:26:10 +0000179public:
180 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
Chris Lattnere50c0922006-03-05 22:45:01 +0000181 const TargetMachine &tm, bool isbottomup,
Chris Lattner356183d2006-03-11 22:44:37 +0000182 SchedulingPriorityQueue *availqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000183 HazardRecognizer *HR)
Chris Lattner063086b2006-03-11 22:34:41 +0000184 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
Chris Lattner356183d2006-03-11 22:44:37 +0000185 AvailableQueue(availqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000186 }
Evan Chengab495562006-01-25 09:14:32 +0000187
188 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000189 delete HazardRec;
Chris Lattner356183d2006-03-11 22:44:37 +0000190 delete AvailableQueue;
Evan Chengab495562006-01-25 09:14:32 +0000191 }
Evan Cheng31272342006-01-23 08:26:10 +0000192
193 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000194
Chris Lattnerd4130372006-03-09 07:15:18 +0000195 void dumpSchedule() const;
Evan Chengab495562006-01-25 09:14:32 +0000196
197private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000198 SUnit *NewSUnit(SDNode *N);
Chris Lattner063086b2006-03-11 22:34:41 +0000199 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
200 void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
201 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
202 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
Chris Lattner399bee22006-03-09 06:48:37 +0000203 void ListScheduleTopDown();
204 void ListScheduleBottomUp();
Evan Chengab495562006-01-25 09:14:32 +0000205 void BuildSchedUnits();
206 void EmitSchedule();
207};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000208} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000209
Chris Lattner47639db2006-03-06 00:22:00 +0000210HazardRecognizer::~HazardRecognizer() {}
211
Evan Chengc4c339c2006-01-26 00:30:29 +0000212
213/// NewSUnit - Creates a new SUnit and return a ptr to it.
214SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000215 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000216 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000217}
218
Chris Lattner9995a0c2006-03-11 22:28:35 +0000219/// BuildSchedUnits - Build SUnits from the selection dag that we are input.
220/// This SUnit graph is similar to the SelectionDAG, but represents flagged
221/// together nodes with a single SUnit.
222void ScheduleDAGList::BuildSchedUnits() {
223 // Reserve entries in the vector for each of the SUnits we are creating. This
224 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
225 // invalidated.
226 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
227
228 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
229
230 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
231 E = DAG.allnodes_end(); NI != E; ++NI) {
232 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
233 continue;
234
235 // If this node has already been processed, stop now.
236 if (SUnitMap[NI]) continue;
237
238 SUnit *NodeSUnit = NewSUnit(NI);
239
240 // See if anything is flagged to this node, if so, add them to flagged
241 // nodes. Nodes can have at most one flag input and one flag output. Flags
242 // are required the be the last operand and result of a node.
243
244 // Scan up, adding flagged preds to FlaggedNodes.
245 SDNode *N = NI;
246 while (N->getNumOperands() &&
247 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
248 N = N->getOperand(N->getNumOperands()-1).Val;
249 NodeSUnit->FlaggedNodes.push_back(N);
250 SUnitMap[N] = NodeSUnit;
251 }
252
253 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
254 // have a user of the flag operand.
255 N = NI;
256 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
257 SDOperand FlagVal(N, N->getNumValues()-1);
258
259 // There are either zero or one users of the Flag result.
260 bool HasFlagUse = false;
261 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
262 UI != E; ++UI)
263 if (FlagVal.isOperand(*UI)) {
264 HasFlagUse = true;
265 NodeSUnit->FlaggedNodes.push_back(N);
266 SUnitMap[N] = NodeSUnit;
267 N = *UI;
268 break;
269 }
270 if (!HasFlagUse) break;
271 }
272
273 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
274 // Update the SUnit
275 NodeSUnit->Node = N;
276 SUnitMap[N] = NodeSUnit;
277
278 // Compute the latency for the node. We use the sum of the latencies for
279 // all nodes flagged together into this SUnit.
280 if (InstrItins.isEmpty()) {
281 // No latency information.
282 NodeSUnit->Latency = 1;
283 } else {
284 NodeSUnit->Latency = 0;
285 if (N->isTargetOpcode()) {
286 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
287 InstrStage *S = InstrItins.begin(SchedClass);
288 InstrStage *E = InstrItins.end(SchedClass);
289 for (; S != E; ++S)
290 NodeSUnit->Latency += S->Cycles;
291 }
292 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
293 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
294 if (FNode->isTargetOpcode()) {
295 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
296 InstrStage *S = InstrItins.begin(SchedClass);
297 InstrStage *E = InstrItins.end(SchedClass);
298 for (; S != E; ++S)
299 NodeSUnit->Latency += S->Cycles;
300 }
301 }
302 }
303 }
304
305 // Pass 2: add the preds, succs, etc.
306 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
307 SUnit *SU = &SUnits[su];
308 SDNode *MainNode = SU->Node;
309
310 if (MainNode->isTargetOpcode() &&
311 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
312 SU->isTwoAddress = true;
313
314 // Find all predecessors and successors of the group.
315 // Temporarily add N to make code simpler.
316 SU->FlaggedNodes.push_back(MainNode);
317
318 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
319 SDNode *N = SU->FlaggedNodes[n];
320
321 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
322 SDNode *OpN = N->getOperand(i).Val;
323 if (isPassiveNode(OpN)) continue; // Not scheduled.
324 SUnit *OpSU = SUnitMap[OpN];
325 assert(OpSU && "Node has no SUnit!");
326 if (OpSU == SU) continue; // In the same group.
327
328 MVT::ValueType OpVT = N->getOperand(i).getValueType();
329 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
330 bool isChain = OpVT == MVT::Other;
331
332 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
333 if (!isChain) {
334 SU->NumPredsLeft++;
335 } else {
336 SU->NumChainPredsLeft++;
337 }
338 }
339 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
340 if (!isChain) {
341 OpSU->NumSuccsLeft++;
342 } else {
343 OpSU->NumChainSuccsLeft++;
344 }
345 }
346 }
347 }
348
349 // Remove MainNode from FlaggedNodes again.
350 SU->FlaggedNodes.pop_back();
351 }
352 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
353 SUnits[su].dumpAll(&DAG));
354}
355
356/// EmitSchedule - Emit the machine code in scheduled order.
357void ScheduleDAGList::EmitSchedule() {
358 std::map<SDNode*, unsigned> VRBaseMap;
359 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
360 if (SUnit *SU = Sequence[i]) {
361 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
362 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
363 EmitNode(SU->Node, VRBaseMap);
364 } else {
365 // Null SUnit* is a noop.
366 EmitNoop();
367 }
368 }
369}
370
371/// dump - dump the schedule.
372void ScheduleDAGList::dumpSchedule() const {
373 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
374 if (SUnit *SU = Sequence[i])
375 SU->dump(&DAG);
376 else
377 std::cerr << "**** NOOP ****\n";
378 }
379}
380
381/// Schedule - Schedule the DAG using list scheduling.
382/// FIXME: Right now it only supports the burr (bottom up register reducing)
383/// heuristic.
384void ScheduleDAGList::Schedule() {
385 DEBUG(std::cerr << "********** List Scheduling **********\n");
386
387 // Build scheduling units.
388 BuildSchedUnits();
389
Chris Lattner356183d2006-03-11 22:44:37 +0000390 AvailableQueue->initNodes(SUnits);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000391
392 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
393 if (isBottomUp)
394 ListScheduleBottomUp();
395 else
396 ListScheduleTopDown();
397
Chris Lattner356183d2006-03-11 22:44:37 +0000398 AvailableQueue->releaseState();
Chris Lattner9995a0c2006-03-11 22:28:35 +0000399
400 DEBUG(std::cerr << "*** Final schedule ***\n");
401 DEBUG(dumpSchedule());
402 DEBUG(std::cerr << "\n");
403
404 // Emit in scheduled order
405 EmitSchedule();
406}
407
408//===----------------------------------------------------------------------===//
409// Bottom-Up Scheduling
410//===----------------------------------------------------------------------===//
411
Evan Chengc4c339c2006-01-26 00:30:29 +0000412/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
413/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner063086b2006-03-11 22:34:41 +0000414void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
Chris Lattner356183d2006-03-11 22:44:37 +0000415 unsigned CurCycle) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000416 // FIXME: the distance between two nodes is not always == the predecessor's
417 // latency. For example, the reader can very well read the register written
418 // by the predecessor later than the issue cycle. It also depends on the
419 // interrupt model (drain vs. freeze).
Chris Lattner356183d2006-03-11 22:44:37 +0000420 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000421
Evan Chengc5c06582006-03-06 06:08:54 +0000422 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000423 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000424 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000425 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000426
Evan Chengab495562006-01-25 09:14:32 +0000427#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000428 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000429 std::cerr << "*** List scheduling failed! ***\n";
430 PredSU->dump(&DAG);
431 std::cerr << " has been released too many times!\n";
432 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000433 }
Evan Chengab495562006-01-25 09:14:32 +0000434#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000435
436 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
437 // EntryToken has to go last! Special case it here.
Chris Lattner349e9dd2006-03-10 05:51:05 +0000438 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
439 PredSU->isAvailable = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000440 AvailableQueue->push(PredSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000441 }
Evan Chengab495562006-01-25 09:14:32 +0000442 }
Evan Chengab495562006-01-25 09:14:32 +0000443}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000444/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
445/// count of its predecessors. If a predecessor pending count is zero, add it to
446/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000447void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Evan Cheng5e9a6952006-03-03 06:23:43 +0000448 DEBUG(std::cerr << "*** Scheduling: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000449 DEBUG(SU->dump(&DAG));
Chris Lattner356183d2006-03-11 22:44:37 +0000450 SU->Cycle = CurCycle;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000451
Evan Chengab495562006-01-25 09:14:32 +0000452 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000453
454 // Bottom up: release predecessors
Chris Lattner578d8fc2006-03-11 22:24:20 +0000455 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
456 E = SU->Preds.end(); I != E; ++I) {
Chris Lattner356183d2006-03-11 22:44:37 +0000457 ReleasePred(I->first, I->second, CurCycle);
458 // FIXME: This is something used by the priority function that it should
459 // calculate directly.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000460 if (!I->second)
461 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000462 }
Evan Chengab495562006-01-25 09:14:32 +0000463}
464
465/// isReady - True if node's lower cycle bound is less or equal to the current
466/// scheduling cycle. Always true if all nodes have uniform latency 1.
467static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
468 return SU->CycleBound <= CurrCycle;
469}
470
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000471/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
472/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000473void ScheduleDAGList::ListScheduleBottomUp() {
Chris Lattner063086b2006-03-11 22:34:41 +0000474 unsigned CurrCycle = 0;
Chris Lattner7a36d972006-03-05 20:21:55 +0000475 // Add root to Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000476 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000477
478 // While Available queue is not empty, grab the node with the highest
479 // priority. If it is not ready put it back. Schedule the node.
480 std::vector<SUnit*> NotReady;
Chris Lattner356183d2006-03-11 22:44:37 +0000481 while (!AvailableQueue->empty()) {
482 SUnit *CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000483
Evan Chengab495562006-01-25 09:14:32 +0000484 while (!isReady(CurrNode, CurrCycle)) {
485 NotReady.push_back(CurrNode);
Chris Lattner356183d2006-03-11 22:44:37 +0000486 CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000487 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000488
489 // Add the nodes that aren't ready back onto the available list.
Chris Lattner356183d2006-03-11 22:44:37 +0000490 AvailableQueue->push_all(NotReady);
Chris Lattner25e25562006-03-10 04:32:49 +0000491 NotReady.clear();
Evan Chengab495562006-01-25 09:14:32 +0000492
Chris Lattner063086b2006-03-11 22:34:41 +0000493 ScheduleNodeBottomUp(CurrNode, CurrCycle);
494 CurrCycle++;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000495 CurrNode->isScheduled = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000496 AvailableQueue->ScheduledNode(CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000497 }
498
499 // Add entry node last
500 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
501 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000502 Sequence.push_back(Entry);
503 }
504
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000505 // Reverse the order if it is bottom up.
506 std::reverse(Sequence.begin(), Sequence.end());
507
508
Evan Chengab495562006-01-25 09:14:32 +0000509#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000510 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000511 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000512 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
513 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000514 if (!AnyNotSched)
515 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000516 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000517 std::cerr << "has not been scheduled!\n";
518 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000519 }
Evan Chengab495562006-01-25 09:14:32 +0000520 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000521 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000522#endif
Evan Chengab495562006-01-25 09:14:32 +0000523}
524
Chris Lattner9995a0c2006-03-11 22:28:35 +0000525//===----------------------------------------------------------------------===//
526// Top-Down Scheduling
527//===----------------------------------------------------------------------===//
528
529/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
530/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner063086b2006-03-11 22:34:41 +0000531void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain,
Chris Lattner356183d2006-03-11 22:44:37 +0000532 unsigned CurCycle) {
Chris Lattner9995a0c2006-03-11 22:28:35 +0000533 // FIXME: the distance between two nodes is not always == the predecessor's
534 // latency. For example, the reader can very well read the register written
535 // by the predecessor later than the issue cycle. It also depends on the
536 // interrupt model (drain vs. freeze).
Chris Lattner356183d2006-03-11 22:44:37 +0000537 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000538
539 if (!isChain)
540 SuccSU->NumPredsLeft--;
541 else
542 SuccSU->NumChainPredsLeft--;
543
544#ifndef NDEBUG
545 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
546 std::cerr << "*** List scheduling failed! ***\n";
547 SuccSU->dump(&DAG);
548 std::cerr << " has been released too many times!\n";
549 abort();
550 }
551#endif
552
553 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
554 SuccSU->isAvailable = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000555 AvailableQueue->push(SuccSU);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000556 }
557}
558
559/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
560/// count of its successors. If a successor pending count is zero, add it to
561/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000562void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Chris Lattner9995a0c2006-03-11 22:28:35 +0000563 DEBUG(std::cerr << "*** Scheduling: ");
564 DEBUG(SU->dump(&DAG));
565
566 Sequence.push_back(SU);
Chris Lattner356183d2006-03-11 22:44:37 +0000567 SU->Cycle = CurCycle;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000568
569 // Bottom up: release successors.
570 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
Chris Lattner356183d2006-03-11 22:44:37 +0000571 E = SU->Succs.end(); I != E; ++I)
572 ReleaseSucc(I->first, I->second, CurCycle);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000573}
574
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000575/// ListScheduleTopDown - The main loop of list scheduling for top-down
576/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000577void ScheduleDAGList::ListScheduleTopDown() {
Chris Lattner063086b2006-03-11 22:34:41 +0000578 unsigned CurrCycle = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000579 // Emit the entry node first.
580 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Chris Lattner063086b2006-03-11 22:34:41 +0000581 ScheduleNodeTopDown(Entry, CurrCycle);
Chris Lattner543832d2006-03-08 04:25:59 +0000582 HazardRec->EmitInstruction(Entry->Node);
Chris Lattnere50c0922006-03-05 22:45:01 +0000583
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000584 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000585 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000586 // It is available if it has no predecessors.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000587 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
Chris Lattner356183d2006-03-11 22:44:37 +0000588 AvailableQueue->push(&SUnits[i]);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000589 }
590
591 // While Available queue is not empty, grab the node with the highest
592 // priority. If it is not ready put it back. Schedule the node.
593 std::vector<SUnit*> NotReady;
Chris Lattner356183d2006-03-11 22:44:37 +0000594 while (!AvailableQueue->empty()) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000595 SUnit *FoundNode = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000596
Chris Lattnere50c0922006-03-05 22:45:01 +0000597 bool HasNoopHazards = false;
598 do {
Chris Lattner356183d2006-03-11 22:44:37 +0000599 SUnit *CurNode = AvailableQueue->pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000600
601 // Get the node represented by this SUnit.
602 SDNode *N = CurNode->Node;
603 // If this is a pseudo op, like copyfromreg, look to see if there is a
604 // real target node flagged to it. If so, use the target node.
605 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
606 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
607 N = CurNode->FlaggedNodes[i];
608
Chris Lattner543832d2006-03-08 04:25:59 +0000609 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
Chris Lattnere50c0922006-03-05 22:45:01 +0000610 if (HT == HazardRecognizer::NoHazard) {
Chris Lattner0c801bd2006-03-07 05:40:43 +0000611 FoundNode = CurNode;
Chris Lattnere50c0922006-03-05 22:45:01 +0000612 break;
613 }
614
615 // Remember if this is a noop hazard.
616 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
617
Chris Lattner0c801bd2006-03-07 05:40:43 +0000618 NotReady.push_back(CurNode);
Chris Lattner356183d2006-03-11 22:44:37 +0000619 } while (!AvailableQueue->empty());
Chris Lattnere50c0922006-03-05 22:45:01 +0000620
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000621 // Add the nodes that aren't ready back onto the available list.
Chris Lattner356183d2006-03-11 22:44:37 +0000622 AvailableQueue->push_all(NotReady);
Chris Lattner25e25562006-03-10 04:32:49 +0000623 NotReady.clear();
Chris Lattnere50c0922006-03-05 22:45:01 +0000624
625 // If we found a node to schedule, do it now.
626 if (FoundNode) {
Chris Lattner063086b2006-03-11 22:34:41 +0000627 ScheduleNodeTopDown(FoundNode, CurrCycle);
628 CurrCycle++; // Fixme don't increment for pseudo-ops!
Chris Lattner543832d2006-03-08 04:25:59 +0000629 HazardRec->EmitInstruction(FoundNode->Node);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000630 FoundNode->isScheduled = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000631 AvailableQueue->ScheduledNode(FoundNode);
Chris Lattnere50c0922006-03-05 22:45:01 +0000632 } else if (!HasNoopHazards) {
633 // Otherwise, we have a pipeline stall, but no other problem, just advance
634 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000635 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000636 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000637 ++NumStalls;
Chris Lattnere50c0922006-03-05 22:45:01 +0000638 } else {
639 // Otherwise, we have no instructions to issue and we have instructions
640 // that will fault if we don't do this right. This is the case for
641 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000642 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000643 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000644 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000645 ++NumNoops;
Chris Lattnere50c0922006-03-05 22:45:01 +0000646 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000647 }
648
649#ifndef NDEBUG
650 // Verify that all SUnits were scheduled.
651 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000652 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
653 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000654 if (!AnyNotSched)
655 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000656 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000657 std::cerr << "has not been scheduled!\n";
658 AnyNotSched = true;
659 }
660 }
661 assert(!AnyNotSched);
662#endif
663}
664
Chris Lattner9df64752006-03-09 06:35:14 +0000665//===----------------------------------------------------------------------===//
666// RegReductionPriorityQueue Implementation
667//===----------------------------------------------------------------------===//
668//
669// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
670// to reduce register pressure.
671//
672namespace {
673 class RegReductionPriorityQueue;
674
675 /// Sorting functions for the Available queue.
676 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
677 RegReductionPriorityQueue *SPQ;
678 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
679 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
680
681 bool operator()(const SUnit* left, const SUnit* right) const;
682 };
683} // end anonymous namespace
684
685namespace {
686 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
687 // SUnits - The SUnits for the current graph.
688 const std::vector<SUnit> *SUnits;
689
690 // SethiUllmanNumbers - The SethiUllman number for each node.
691 std::vector<int> SethiUllmanNumbers;
692
693 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
694 public:
695 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
696 }
697
698 void initNodes(const std::vector<SUnit> &sunits) {
699 SUnits = &sunits;
700 // Calculate node priorities.
701 CalculatePriorities();
702 }
703 void releaseState() {
704 SUnits = 0;
705 SethiUllmanNumbers.clear();
706 }
707
708 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
709 assert(NodeNum < SethiUllmanNumbers.size());
710 return SethiUllmanNumbers[NodeNum];
711 }
712
713 bool empty() const { return Queue.empty(); }
714
715 void push(SUnit *U) {
716 Queue.push(U);
717 }
Chris Lattner25e25562006-03-10 04:32:49 +0000718 void push_all(const std::vector<SUnit *> &Nodes) {
719 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
720 Queue.push(Nodes[i]);
721 }
722
Chris Lattner9df64752006-03-09 06:35:14 +0000723 SUnit *pop() {
724 SUnit *V = Queue.top();
725 Queue.pop();
726 return V;
727 }
728 private:
729 void CalculatePriorities();
730 int CalcNodePriority(const SUnit *SU);
731 };
732}
733
734bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
735 unsigned LeftNum = left->NodeNum;
736 unsigned RightNum = right->NodeNum;
737
738 int LBonus = (int)left ->isDefNUseOperand;
739 int RBonus = (int)right->isDefNUseOperand;
740
741 // Special tie breaker: if two nodes share a operand, the one that
742 // use it as a def&use operand is preferred.
743 if (left->isTwoAddress && !right->isTwoAddress) {
744 SDNode *DUNode = left->Node->getOperand(0).Val;
745 if (DUNode->isOperand(right->Node))
746 LBonus++;
747 }
748 if (!left->isTwoAddress && right->isTwoAddress) {
749 SDNode *DUNode = right->Node->getOperand(0).Val;
750 if (DUNode->isOperand(left->Node))
751 RBonus++;
752 }
753
754 // Priority1 is just the number of live range genned.
755 int LPriority1 = left ->NumPredsLeft - LBonus;
756 int RPriority1 = right->NumPredsLeft - RBonus;
757 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
758 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
759
760 if (LPriority1 > RPriority1)
761 return true;
762 else if (LPriority1 == RPriority1)
763 if (LPriority2 < RPriority2)
764 return true;
765 else if (LPriority2 == RPriority2)
766 if (left->CycleBound > right->CycleBound)
767 return true;
768
769 return false;
770}
771
772
773/// CalcNodePriority - Priority is the Sethi Ullman number.
774/// Smaller number is the higher priority.
775int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
776 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
777 if (SethiUllmanNumber != INT_MIN)
778 return SethiUllmanNumber;
779
780 if (SU->Preds.size() == 0) {
781 SethiUllmanNumber = 1;
782 } else {
783 int Extra = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000784 for (std::set<std::pair<SUnit*, bool> >::const_iterator
785 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
786 if (I->second) continue; // ignore chain preds.
787 SUnit *PredSU = I->first;
Chris Lattner9df64752006-03-09 06:35:14 +0000788 int PredSethiUllman = CalcNodePriority(PredSU);
789 if (PredSethiUllman > SethiUllmanNumber) {
790 SethiUllmanNumber = PredSethiUllman;
791 Extra = 0;
792 } else if (PredSethiUllman == SethiUllmanNumber)
793 Extra++;
794 }
795
796 if (SU->Node->getOpcode() != ISD::TokenFactor)
797 SethiUllmanNumber += Extra;
798 else
799 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
800 }
801
802 return SethiUllmanNumber;
803}
804
805/// CalculatePriorities - Calculate priorities of all scheduling units.
806void RegReductionPriorityQueue::CalculatePriorities() {
807 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
808
809 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
810 CalcNodePriority(&(*SUnits)[i]);
811}
812
Chris Lattner6398c132006-03-09 07:38:27 +0000813//===----------------------------------------------------------------------===//
814// LatencyPriorityQueue Implementation
815//===----------------------------------------------------------------------===//
816//
817// This is a SchedulingPriorityQueue that schedules using latency information to
818// reduce the length of the critical path through the basic block.
819//
820namespace {
821 class LatencyPriorityQueue;
822
823 /// Sorting functions for the Available queue.
824 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
825 LatencyPriorityQueue *PQ;
826 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
827 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
828
829 bool operator()(const SUnit* left, const SUnit* right) const;
830 };
831} // end anonymous namespace
832
833namespace {
834 class LatencyPriorityQueue : public SchedulingPriorityQueue {
835 // SUnits - The SUnits for the current graph.
836 const std::vector<SUnit> *SUnits;
837
838 // Latencies - The latency (max of latency from this node to the bb exit)
839 // for each node.
840 std::vector<int> Latencies;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000841
842 /// NumNodesSolelyBlocking - This vector contains, for every node in the
843 /// Queue, the number of nodes that the node is the sole unscheduled
844 /// predecessor for. This is used as a tie-breaker heuristic for better
845 /// mobility.
846 std::vector<unsigned> NumNodesSolelyBlocking;
847
Chris Lattner6398c132006-03-09 07:38:27 +0000848 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
849public:
850 LatencyPriorityQueue() : Queue(latency_sort(this)) {
851 }
852
853 void initNodes(const std::vector<SUnit> &sunits) {
854 SUnits = &sunits;
855 // Calculate node priorities.
856 CalculatePriorities();
857 }
858 void releaseState() {
859 SUnits = 0;
860 Latencies.clear();
861 }
862
863 unsigned getLatency(unsigned NodeNum) const {
864 assert(NodeNum < Latencies.size());
865 return Latencies[NodeNum];
866 }
867
Chris Lattner349e9dd2006-03-10 05:51:05 +0000868 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
869 assert(NodeNum < NumNodesSolelyBlocking.size());
870 return NumNodesSolelyBlocking[NodeNum];
871 }
872
Chris Lattner6398c132006-03-09 07:38:27 +0000873 bool empty() const { return Queue.empty(); }
874
Chris Lattner349e9dd2006-03-10 05:51:05 +0000875 virtual void push(SUnit *U) {
876 push_impl(U);
Chris Lattner6398c132006-03-09 07:38:27 +0000877 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000878 void push_impl(SUnit *U);
879
Chris Lattner25e25562006-03-10 04:32:49 +0000880 void push_all(const std::vector<SUnit *> &Nodes) {
881 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000882 push_impl(Nodes[i]);
Chris Lattner25e25562006-03-10 04:32:49 +0000883 }
884
Chris Lattner6398c132006-03-09 07:38:27 +0000885 SUnit *pop() {
886 SUnit *V = Queue.top();
887 Queue.pop();
Chris Lattner6398c132006-03-09 07:38:27 +0000888 return V;
889 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000890
891 // ScheduledNode - As nodes are scheduled, we look to see if there are any
892 // successor nodes that have a single unscheduled predecessor. If so, that
893 // single predecessor has a higher priority, since scheduling it will make
894 // the node available.
895 void ScheduledNode(SUnit *Node);
896
Chris Lattner6398c132006-03-09 07:38:27 +0000897private:
898 void CalculatePriorities();
899 int CalcLatency(const SUnit &SU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000900 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
901
902 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
903 /// node from a priority queue. We should roll our own heap to make this
904 /// better or something.
905 void RemoveFromPriorityQueue(SUnit *SU) {
906 std::vector<SUnit*> Temp;
907
908 assert(!Queue.empty() && "Not in queue!");
909 while (Queue.top() != SU) {
910 Temp.push_back(Queue.top());
911 Queue.pop();
912 assert(!Queue.empty() && "Not in queue!");
913 }
914
915 // Remove the node from the PQ.
916 Queue.pop();
917
918 // Add all the other nodes back.
919 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
920 Queue.push(Temp[i]);
921 }
Chris Lattner6398c132006-03-09 07:38:27 +0000922 };
923}
924
925bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
926 unsigned LHSNum = LHS->NodeNum;
927 unsigned RHSNum = RHS->NodeNum;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000928
929 // The most important heuristic is scheduling the critical path.
930 unsigned LHSLatency = PQ->getLatency(LHSNum);
931 unsigned RHSLatency = PQ->getLatency(RHSNum);
932 if (LHSLatency < RHSLatency) return true;
933 if (LHSLatency > RHSLatency) return false;
Chris Lattner6398c132006-03-09 07:38:27 +0000934
Chris Lattner349e9dd2006-03-10 05:51:05 +0000935 // After that, if two nodes have identical latencies, look to see if one will
936 // unblock more other nodes than the other.
937 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
938 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
939 if (LHSBlocked < RHSBlocked) return true;
940 if (LHSBlocked > RHSBlocked) return false;
941
942 // Finally, just to provide a stable ordering, use the node number as a
943 // deciding factor.
944 return LHSNum < RHSNum;
Chris Lattner6398c132006-03-09 07:38:27 +0000945}
946
947
948/// CalcNodePriority - Calculate the maximal path from the node to the exit.
949///
950int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
951 int &Latency = Latencies[SU.NodeNum];
952 if (Latency != -1)
953 return Latency;
954
955 int MaxSuccLatency = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000956 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +0000957 E = SU.Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000958 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
Chris Lattner6398c132006-03-09 07:38:27 +0000959
960 return Latency = MaxSuccLatency + SU.Latency;
961}
962
963/// CalculatePriorities - Calculate priorities of all scheduling units.
964void LatencyPriorityQueue::CalculatePriorities() {
965 Latencies.assign(SUnits->size(), -1);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000966 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
Chris Lattner6398c132006-03-09 07:38:27 +0000967
968 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
969 CalcLatency((*SUnits)[i]);
970}
971
Chris Lattner349e9dd2006-03-10 05:51:05 +0000972/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
973/// of SU, return it, otherwise return null.
974static SUnit *getSingleUnscheduledPred(SUnit *SU) {
975 SUnit *OnlyAvailablePred = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000976 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +0000977 E = SU->Preds.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000978 if (!I->first->isScheduled) {
Chris Lattner349e9dd2006-03-10 05:51:05 +0000979 // We found an available, but not scheduled, predecessor. If it's the
980 // only one we have found, keep track of it... otherwise give up.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000981 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000982 return 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000983 OnlyAvailablePred = I->first;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000984 }
985
986 return OnlyAvailablePred;
987}
988
989void LatencyPriorityQueue::push_impl(SUnit *SU) {
990 // Look at all of the successors of this node. Count the number of nodes that
991 // this node is the sole unscheduled node for.
992 unsigned NumNodesBlocking = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000993 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +0000994 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000995 if (getSingleUnscheduledPred(I->first) == SU)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000996 ++NumNodesBlocking;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000997 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000998
999 Queue.push(SU);
1000}
1001
1002
1003// ScheduledNode - As nodes are scheduled, we look to see if there are any
1004// successor nodes that have a single unscheduled predecessor. If so, that
1005// single predecessor has a higher priority, since scheduling it will make
1006// the node available.
1007void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
Chris Lattner578d8fc2006-03-11 22:24:20 +00001008 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001009 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001010 AdjustPriorityOfUnscheduledPreds(I->first);
Chris Lattner349e9dd2006-03-10 05:51:05 +00001011}
1012
1013/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1014/// scheduled. If SU is not itself available, then there is at least one
1015/// predecessor node that has not been scheduled yet. If SU has exactly ONE
1016/// unscheduled predecessor, we want to increase its priority: it getting
1017/// scheduled will make this node available, so it is better than some other
1018/// node of the same priority that will not make a node available.
1019void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1020 if (SU->isAvailable) return; // All preds scheduled.
1021
1022 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1023 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1024
1025 // Okay, we found a single predecessor that is available, but not scheduled.
1026 // Since it is available, it must be in the priority queue. First remove it.
1027 RemoveFromPriorityQueue(OnlyAvailablePred);
1028
1029 // Reinsert the node into the priority queue, which recomputes its
1030 // NumNodesSolelyBlocking value.
1031 push(OnlyAvailablePred);
1032}
1033
Chris Lattner9df64752006-03-09 06:35:14 +00001034
1035//===----------------------------------------------------------------------===//
1036// Public Constructor Functions
1037//===----------------------------------------------------------------------===//
1038
Evan Chengab495562006-01-25 09:14:32 +00001039llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1040 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +00001041 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +00001042 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +00001043 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00001044}
1045
Chris Lattner47639db2006-03-06 00:22:00 +00001046/// createTDListDAGScheduler - This creates a top-down list scheduler with the
1047/// specified hazard recognizer.
1048ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1049 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +00001050 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +00001051 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
Chris Lattner6398c132006-03-09 07:38:27 +00001052 new LatencyPriorityQueue(),
Chris Lattner9df64752006-03-09 06:35:14 +00001053 HR);
Evan Cheng31272342006-01-23 08:26:10 +00001054}