blob: d686267e404df22e8b52bdce3163f909e3918bc7 [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 {
Evan Cheng24e79542006-05-01 09:14:40 +000036 // TEMPORARY option to test a fix.
37 cl::opt<bool>
38 SchedIgnorStore("sched-ignore-store", cl::Hidden);
39
40}
41
42namespace {
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000043 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
44 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
Evan Cheng31272342006-01-23 08:26:10 +000045
Chris Lattner12c6d892006-03-08 04:41:06 +000046 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
47 /// a group of nodes flagged together.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000048 struct SUnit {
49 SDNode *Node; // Representative node.
50 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
Chris Lattner578d8fc2006-03-11 22:24:20 +000051
52 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
53 // is true if the edge is a token chain edge, false if it is a value edge.
54 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
55 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
56
Chris Lattner12c6d892006-03-08 04:41:06 +000057 short NumPredsLeft; // # of preds not scheduled.
58 short NumSuccsLeft; // # of succs not scheduled.
59 short NumChainPredsLeft; // # of chain preds not scheduled.
60 short NumChainSuccsLeft; // # of chain succs not scheduled.
Evan Cheng24e79542006-05-01 09:14:40 +000061 bool isStore : 1; // Is a store.
Chris Lattner12c6d892006-03-08 04:41:06 +000062 bool isTwoAddress : 1; // Is a two-address instruction.
63 bool isDefNUseOperand : 1; // Is a def&use operand.
Chris Lattner572003c2006-03-12 00:38:57 +000064 bool isPending : 1; // True once pending.
Chris Lattner349e9dd2006-03-10 05:51:05 +000065 bool isAvailable : 1; // True once available.
66 bool isScheduled : 1; // True once scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000067 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000068 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattner356183d2006-03-11 22:44:37 +000069 unsigned Cycle; // Once scheduled, the cycle of the op.
Chris Lattnerfd22d422006-03-08 05:18:27 +000070 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000071
Chris Lattnerfd22d422006-03-08 05:18:27 +000072 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000073 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng24e79542006-05-01 09:14:40 +000074 NumChainPredsLeft(0), NumChainSuccsLeft(0), isStore(false),
Evan Cheng5e9a6952006-03-03 06:23:43 +000075 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattner572003c2006-03-12 00:38:57 +000076 isPending(false), isAvailable(false), isScheduled(false),
Chris Lattner356183d2006-03-11 22:44:37 +000077 Latency(0), CycleBound(0), Cycle(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000078
Chris Lattnerd4130372006-03-09 07:15:18 +000079 void dump(const SelectionDAG *G) const;
80 void dumpAll(const SelectionDAG *G) const;
Chris Lattneraf5e26c2006-03-08 04:37:58 +000081 };
82}
Evan Chengab495562006-01-25 09:14:32 +000083
Chris Lattnerd4130372006-03-09 07:15:18 +000084void SUnit::dump(const SelectionDAG *G) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000085 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000086 Node->dump(G);
87 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000088 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000089 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000090 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000091 FlaggedNodes[i]->dump(G);
92 std::cerr << "\n";
93 }
94 }
Chris Lattnerd4130372006-03-09 07:15:18 +000095}
Evan Chengab495562006-01-25 09:14:32 +000096
Chris Lattnerd4130372006-03-09 07:15:18 +000097void SUnit::dumpAll(const SelectionDAG *G) const {
98 dump(G);
Evan Chengc4c339c2006-01-26 00:30:29 +000099
Chris Lattnerd4130372006-03-09 07:15:18 +0000100 std::cerr << " # preds left : " << NumPredsLeft << "\n";
101 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
102 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
103 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
104 std::cerr << " Latency : " << Latency << "\n";
105
106 if (Preds.size() != 0) {
107 std::cerr << " Predecessors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000108 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000109 E = Preds.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000110 if (I->second)
111 std::cerr << " ch ";
112 else
113 std::cerr << " val ";
114 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000115 }
116 }
117 if (Succs.size() != 0) {
118 std::cerr << " Successors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000119 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000120 E = Succs.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000121 if (I->second)
122 std::cerr << " ch ";
123 else
124 std::cerr << " val ";
125 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000126 }
127 }
128 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +0000129}
130
Chris Lattner9df64752006-03-09 06:35:14 +0000131//===----------------------------------------------------------------------===//
Chris Lattner9e95acc2006-03-09 06:37:29 +0000132/// SchedulingPriorityQueue - This interface is used to plug different
133/// priorities computation algorithms into the list scheduler. It implements the
134/// interface of a standard priority queue, where nodes are inserted in
135/// arbitrary order and returned in priority order. The computation of the
136/// priority and the representation of the queue are totally up to the
137/// implementation to decide.
138///
139namespace {
Chris Lattner9df64752006-03-09 06:35:14 +0000140class SchedulingPriorityQueue {
141public:
142 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000143
Chris Lattner9df64752006-03-09 06:35:14 +0000144 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
145 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000146
Chris Lattner9df64752006-03-09 06:35:14 +0000147 virtual bool empty() const = 0;
148 virtual void push(SUnit *U) = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000149
150 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
Chris Lattner9df64752006-03-09 06:35:14 +0000151 virtual SUnit *pop() = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000152
153 /// ScheduledNode - As each node is scheduled, this method is invoked. This
154 /// allows the priority function to adjust the priority of node that have
155 /// already been emitted.
156 virtual void ScheduledNode(SUnit *Node) {}
Chris Lattner9df64752006-03-09 06:35:14 +0000157};
Chris Lattner9e95acc2006-03-09 06:37:29 +0000158}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000159
160
Chris Lattnere50c0922006-03-05 22:45:01 +0000161
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000162namespace {
Chris Lattner9e95acc2006-03-09 06:37:29 +0000163//===----------------------------------------------------------------------===//
164/// ScheduleDAGList - The actual list scheduler implementation. This supports
165/// both top-down and bottom-up scheduling.
166///
Evan Cheng31272342006-01-23 08:26:10 +0000167class ScheduleDAGList : public ScheduleDAG {
168private:
Evan Chengab495562006-01-25 09:14:32 +0000169 // SDNode to SUnit mapping (many to one).
170 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000171 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000172 std::vector<SUnit*> Sequence;
Chris Lattner42e20262006-03-08 04:54:34 +0000173
174 // The scheduling units.
175 std::vector<SUnit> SUnits;
Evan Cheng31272342006-01-23 08:26:10 +0000176
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000177 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
178 /// it is top-down.
179 bool isBottomUp;
180
Chris Lattner356183d2006-03-11 22:44:37 +0000181 /// AvailableQueue - The priority queue to use for the available SUnits.
182 ///
183 SchedulingPriorityQueue *AvailableQueue;
Chris Lattner9df64752006-03-09 06:35:14 +0000184
Chris Lattner572003c2006-03-12 00:38:57 +0000185 /// PendingQueue - This contains all of the instructions whose operands have
186 /// been issued, but their results are not ready yet (due to the latency of
187 /// the operation). Once the operands becomes available, the instruction is
188 /// added to the AvailableQueue. This keeps track of each SUnit and the
189 /// number of cycles left to execute before the operation is available.
190 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
191
Chris Lattnere50c0922006-03-05 22:45:01 +0000192 /// HazardRec - The hazard recognizer to use.
Chris Lattner543832d2006-03-08 04:25:59 +0000193 HazardRecognizer *HazardRec;
Chris Lattnere50c0922006-03-05 22:45:01 +0000194
Evan Cheng31272342006-01-23 08:26:10 +0000195public:
196 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
Chris Lattnere50c0922006-03-05 22:45:01 +0000197 const TargetMachine &tm, bool isbottomup,
Chris Lattner356183d2006-03-11 22:44:37 +0000198 SchedulingPriorityQueue *availqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000199 HazardRecognizer *HR)
Chris Lattner063086b2006-03-11 22:34:41 +0000200 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
Chris Lattner356183d2006-03-11 22:44:37 +0000201 AvailableQueue(availqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000202 }
Evan Chengab495562006-01-25 09:14:32 +0000203
204 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000205 delete HazardRec;
Chris Lattner356183d2006-03-11 22:44:37 +0000206 delete AvailableQueue;
Evan Chengab495562006-01-25 09:14:32 +0000207 }
Evan Cheng31272342006-01-23 08:26:10 +0000208
209 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000210
Chris Lattnerd4130372006-03-09 07:15:18 +0000211 void dumpSchedule() const;
Evan Chengab495562006-01-25 09:14:32 +0000212
213private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000214 SUnit *NewSUnit(SDNode *N);
Chris Lattner063086b2006-03-11 22:34:41 +0000215 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
Chris Lattner572003c2006-03-12 00:38:57 +0000216 void ReleaseSucc(SUnit *SuccSU, bool isChain);
Chris Lattner063086b2006-03-11 22:34:41 +0000217 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
218 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
Chris Lattner399bee22006-03-09 06:48:37 +0000219 void ListScheduleTopDown();
220 void ListScheduleBottomUp();
Evan Chengab495562006-01-25 09:14:32 +0000221 void BuildSchedUnits();
222 void EmitSchedule();
223};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000224} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000225
Chris Lattner47639db2006-03-06 00:22:00 +0000226HazardRecognizer::~HazardRecognizer() {}
227
Evan Chengc4c339c2006-01-26 00:30:29 +0000228
229/// NewSUnit - Creates a new SUnit and return a ptr to it.
230SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000231 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000232 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000233}
234
Chris Lattner9995a0c2006-03-11 22:28:35 +0000235/// BuildSchedUnits - Build SUnits from the selection dag that we are input.
236/// This SUnit graph is similar to the SelectionDAG, but represents flagged
237/// together nodes with a single SUnit.
238void ScheduleDAGList::BuildSchedUnits() {
239 // Reserve entries in the vector for each of the SUnits we are creating. This
240 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
241 // invalidated.
242 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
243
244 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
245
246 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
247 E = DAG.allnodes_end(); NI != E; ++NI) {
248 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
249 continue;
250
251 // If this node has already been processed, stop now.
252 if (SUnitMap[NI]) continue;
253
254 SUnit *NodeSUnit = NewSUnit(NI);
255
256 // See if anything is flagged to this node, if so, add them to flagged
257 // nodes. Nodes can have at most one flag input and one flag output. Flags
258 // are required the be the last operand and result of a node.
259
260 // Scan up, adding flagged preds to FlaggedNodes.
261 SDNode *N = NI;
262 while (N->getNumOperands() &&
263 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
264 N = N->getOperand(N->getNumOperands()-1).Val;
265 NodeSUnit->FlaggedNodes.push_back(N);
266 SUnitMap[N] = NodeSUnit;
267 }
268
269 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
270 // have a user of the flag operand.
271 N = NI;
272 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
273 SDOperand FlagVal(N, N->getNumValues()-1);
274
275 // There are either zero or one users of the Flag result.
276 bool HasFlagUse = false;
277 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
278 UI != E; ++UI)
279 if (FlagVal.isOperand(*UI)) {
280 HasFlagUse = true;
281 NodeSUnit->FlaggedNodes.push_back(N);
282 SUnitMap[N] = NodeSUnit;
283 N = *UI;
284 break;
285 }
286 if (!HasFlagUse) break;
287 }
288
289 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
290 // Update the SUnit
291 NodeSUnit->Node = N;
292 SUnitMap[N] = NodeSUnit;
293
294 // Compute the latency for the node. We use the sum of the latencies for
295 // all nodes flagged together into this SUnit.
296 if (InstrItins.isEmpty()) {
297 // No latency information.
298 NodeSUnit->Latency = 1;
299 } else {
300 NodeSUnit->Latency = 0;
301 if (N->isTargetOpcode()) {
302 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
303 InstrStage *S = InstrItins.begin(SchedClass);
304 InstrStage *E = InstrItins.end(SchedClass);
305 for (; S != E; ++S)
306 NodeSUnit->Latency += S->Cycles;
307 }
308 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
309 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
310 if (FNode->isTargetOpcode()) {
311 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
312 InstrStage *S = InstrItins.begin(SchedClass);
313 InstrStage *E = InstrItins.end(SchedClass);
314 for (; S != E; ++S)
315 NodeSUnit->Latency += S->Cycles;
316 }
317 }
318 }
319 }
320
321 // Pass 2: add the preds, succs, etc.
322 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
323 SUnit *SU = &SUnits[su];
324 SDNode *MainNode = SU->Node;
325
Evan Cheng24e79542006-05-01 09:14:40 +0000326 if (MainNode->isTargetOpcode()) {
327 unsigned Opc = MainNode->getTargetOpcode();
328 if (TII->isTwoAddrInstr(Opc))
329 SU->isTwoAddress = true;
330 if (TII->isStore(Opc))
331 if (!SchedIgnorStore)
332 SU->isStore = true;
333 }
Chris Lattner9995a0c2006-03-11 22:28:35 +0000334
335 // Find all predecessors and successors of the group.
336 // Temporarily add N to make code simpler.
337 SU->FlaggedNodes.push_back(MainNode);
338
339 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
340 SDNode *N = SU->FlaggedNodes[n];
341
342 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
343 SDNode *OpN = N->getOperand(i).Val;
344 if (isPassiveNode(OpN)) continue; // Not scheduled.
345 SUnit *OpSU = SUnitMap[OpN];
346 assert(OpSU && "Node has no SUnit!");
347 if (OpSU == SU) continue; // In the same group.
348
349 MVT::ValueType OpVT = N->getOperand(i).getValueType();
350 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
351 bool isChain = OpVT == MVT::Other;
352
353 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
354 if (!isChain) {
355 SU->NumPredsLeft++;
356 } else {
357 SU->NumChainPredsLeft++;
358 }
359 }
360 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
361 if (!isChain) {
362 OpSU->NumSuccsLeft++;
363 } else {
364 OpSU->NumChainSuccsLeft++;
365 }
366 }
367 }
368 }
369
370 // Remove MainNode from FlaggedNodes again.
371 SU->FlaggedNodes.pop_back();
372 }
Chris Lattnera767dbf2006-03-12 09:01:41 +0000373
Chris Lattner9995a0c2006-03-11 22:28:35 +0000374 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
375 SUnits[su].dumpAll(&DAG));
Evan Cheng24e79542006-05-01 09:14:40 +0000376 return;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000377}
378
379/// EmitSchedule - Emit the machine code in scheduled order.
380void ScheduleDAGList::EmitSchedule() {
381 std::map<SDNode*, unsigned> VRBaseMap;
382 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
383 if (SUnit *SU = Sequence[i]) {
384 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
385 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
386 EmitNode(SU->Node, VRBaseMap);
387 } else {
388 // Null SUnit* is a noop.
389 EmitNoop();
390 }
391 }
392}
393
394/// dump - dump the schedule.
395void ScheduleDAGList::dumpSchedule() const {
396 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
397 if (SUnit *SU = Sequence[i])
398 SU->dump(&DAG);
399 else
400 std::cerr << "**** NOOP ****\n";
401 }
402}
403
404/// Schedule - Schedule the DAG using list scheduling.
Chris Lattner9995a0c2006-03-11 22:28:35 +0000405void ScheduleDAGList::Schedule() {
406 DEBUG(std::cerr << "********** List Scheduling **********\n");
407
408 // Build scheduling units.
409 BuildSchedUnits();
410
Chris Lattner356183d2006-03-11 22:44:37 +0000411 AvailableQueue->initNodes(SUnits);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000412
413 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
414 if (isBottomUp)
415 ListScheduleBottomUp();
416 else
417 ListScheduleTopDown();
418
Chris Lattner356183d2006-03-11 22:44:37 +0000419 AvailableQueue->releaseState();
Chris Lattner9995a0c2006-03-11 22:28:35 +0000420
421 DEBUG(std::cerr << "*** Final schedule ***\n");
422 DEBUG(dumpSchedule());
423 DEBUG(std::cerr << "\n");
424
425 // Emit in scheduled order
426 EmitSchedule();
427}
428
429//===----------------------------------------------------------------------===//
430// Bottom-Up Scheduling
431//===----------------------------------------------------------------------===//
432
Evan Chengc4c339c2006-01-26 00:30:29 +0000433/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
434/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner063086b2006-03-11 22:34:41 +0000435void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
Chris Lattner356183d2006-03-11 22:44:37 +0000436 unsigned CurCycle) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000437 // FIXME: the distance between two nodes is not always == the predecessor's
438 // latency. For example, the reader can very well read the register written
439 // by the predecessor later than the issue cycle. It also depends on the
440 // interrupt model (drain vs. freeze).
Chris Lattner356183d2006-03-11 22:44:37 +0000441 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000442
Evan Chengc5c06582006-03-06 06:08:54 +0000443 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000444 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000445 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000446 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000447
Evan Chengab495562006-01-25 09:14:32 +0000448#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000449 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000450 std::cerr << "*** List scheduling failed! ***\n";
451 PredSU->dump(&DAG);
452 std::cerr << " has been released too many times!\n";
453 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000454 }
Evan Chengab495562006-01-25 09:14:32 +0000455#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000456
457 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
458 // EntryToken has to go last! Special case it here.
Chris Lattner349e9dd2006-03-10 05:51:05 +0000459 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
460 PredSU->isAvailable = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000461 AvailableQueue->push(PredSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000462 }
Evan Chengab495562006-01-25 09:14:32 +0000463 }
Evan Chengab495562006-01-25 09:14:32 +0000464}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000465/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
466/// count of its predecessors. If a predecessor pending count is zero, add it to
467/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000468void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Chris Lattner572003c2006-03-12 00:38:57 +0000469 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000470 DEBUG(SU->dump(&DAG));
Chris Lattner356183d2006-03-11 22:44:37 +0000471 SU->Cycle = CurCycle;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000472
Evan Chengab495562006-01-25 09:14:32 +0000473 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000474
475 // Bottom up: release predecessors
Chris Lattner578d8fc2006-03-11 22:24:20 +0000476 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
477 E = SU->Preds.end(); I != E; ++I) {
Chris Lattner356183d2006-03-11 22:44:37 +0000478 ReleasePred(I->first, I->second, CurCycle);
479 // FIXME: This is something used by the priority function that it should
480 // calculate directly.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000481 if (!I->second)
482 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000483 }
Evan Chengab495562006-01-25 09:14:32 +0000484}
485
486/// isReady - True if node's lower cycle bound is less or equal to the current
487/// scheduling cycle. Always true if all nodes have uniform latency 1.
488static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
489 return SU->CycleBound <= CurrCycle;
490}
491
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000492/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
493/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000494void ScheduleDAGList::ListScheduleBottomUp() {
Chris Lattner063086b2006-03-11 22:34:41 +0000495 unsigned CurrCycle = 0;
Chris Lattner7a36d972006-03-05 20:21:55 +0000496 // Add root to Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000497 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000498
499 // While Available queue is not empty, grab the node with the highest
500 // priority. If it is not ready put it back. Schedule the node.
501 std::vector<SUnit*> NotReady;
Chris Lattner356183d2006-03-11 22:44:37 +0000502 while (!AvailableQueue->empty()) {
503 SUnit *CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000504
Evan Chengab495562006-01-25 09:14:32 +0000505 while (!isReady(CurrNode, CurrCycle)) {
506 NotReady.push_back(CurrNode);
Chris Lattner356183d2006-03-11 22:44:37 +0000507 CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000508 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000509
510 // Add the nodes that aren't ready back onto the available list.
Chris Lattner356183d2006-03-11 22:44:37 +0000511 AvailableQueue->push_all(NotReady);
Chris Lattner25e25562006-03-10 04:32:49 +0000512 NotReady.clear();
Evan Chengab495562006-01-25 09:14:32 +0000513
Chris Lattner063086b2006-03-11 22:34:41 +0000514 ScheduleNodeBottomUp(CurrNode, CurrCycle);
515 CurrCycle++;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000516 CurrNode->isScheduled = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000517 AvailableQueue->ScheduledNode(CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000518 }
519
520 // Add entry node last
521 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
522 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000523 Sequence.push_back(Entry);
524 }
525
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000526 // Reverse the order if it is bottom up.
527 std::reverse(Sequence.begin(), Sequence.end());
528
529
Evan Chengab495562006-01-25 09:14:32 +0000530#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000531 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000532 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000533 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
534 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000535 if (!AnyNotSched)
536 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000537 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000538 std::cerr << "has not been scheduled!\n";
539 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000540 }
Evan Chengab495562006-01-25 09:14:32 +0000541 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000542 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000543#endif
Evan Chengab495562006-01-25 09:14:32 +0000544}
545
Chris Lattner9995a0c2006-03-11 22:28:35 +0000546//===----------------------------------------------------------------------===//
547// Top-Down Scheduling
548//===----------------------------------------------------------------------===//
549
550/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Chris Lattner572003c2006-03-12 00:38:57 +0000551/// the PendingQueue if the count reaches zero.
552void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
Chris Lattner9995a0c2006-03-11 22:28:35 +0000553 if (!isChain)
554 SuccSU->NumPredsLeft--;
555 else
556 SuccSU->NumChainPredsLeft--;
557
Chris Lattner572003c2006-03-12 00:38:57 +0000558 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
559 "List scheduling internal error");
Chris Lattner9995a0c2006-03-11 22:28:35 +0000560
561 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
Chris Lattner572003c2006-03-12 00:38:57 +0000562 // Compute how many cycles it will be before this actually becomes
563 // available. This is the max of the start time of all predecessors plus
564 // their latencies.
565 unsigned AvailableCycle = 0;
566 for (std::set<std::pair<SUnit*, bool> >::iterator I = SuccSU->Preds.begin(),
567 E = SuccSU->Preds.end(); I != E; ++I) {
Chris Lattnera767dbf2006-03-12 09:01:41 +0000568 // If this is a token edge, we don't need to wait for the latency of the
569 // preceeding instruction (e.g. a long-latency load) unless there is also
570 // some other data dependence.
Chris Lattner86a9b602006-03-12 03:52:09 +0000571 unsigned PredDoneCycle = I->first->Cycle;
572 if (!I->second)
573 PredDoneCycle += I->first->Latency;
Chris Lattnera767dbf2006-03-12 09:01:41 +0000574 else if (I->first->Latency)
575 PredDoneCycle += 1;
Chris Lattner86a9b602006-03-12 03:52:09 +0000576
577 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
Chris Lattner572003c2006-03-12 00:38:57 +0000578 }
579
580 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
581 SuccSU->isPending = true;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000582 }
583}
584
585/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
586/// count of its successors. If a successor pending count is zero, add it to
587/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000588void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Chris Lattner572003c2006-03-12 00:38:57 +0000589 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
Chris Lattner9995a0c2006-03-11 22:28:35 +0000590 DEBUG(SU->dump(&DAG));
591
592 Sequence.push_back(SU);
Chris Lattner356183d2006-03-11 22:44:37 +0000593 SU->Cycle = CurCycle;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000594
595 // Bottom up: release successors.
596 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
Chris Lattner356183d2006-03-11 22:44:37 +0000597 E = SU->Succs.end(); I != E; ++I)
Chris Lattner572003c2006-03-12 00:38:57 +0000598 ReleaseSucc(I->first, I->second);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000599}
600
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000601/// ListScheduleTopDown - The main loop of list scheduling for top-down
602/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000603void ScheduleDAGList::ListScheduleTopDown() {
Chris Lattner572003c2006-03-12 00:38:57 +0000604 unsigned CurCycle = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000605 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Chris Lattner572003c2006-03-12 00:38:57 +0000606
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000607 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000608 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000609 // It is available if it has no predecessors.
Chris Lattner572003c2006-03-12 00:38:57 +0000610 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
Chris Lattner356183d2006-03-11 22:44:37 +0000611 AvailableQueue->push(&SUnits[i]);
Chris Lattner572003c2006-03-12 00:38:57 +0000612 SUnits[i].isAvailable = SUnits[i].isPending = true;
613 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000614 }
615
Chris Lattner572003c2006-03-12 00:38:57 +0000616 // Emit the entry node first.
617 ScheduleNodeTopDown(Entry, CurCycle);
618 HazardRec->EmitInstruction(Entry->Node);
619
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000620 // While Available queue is not empty, grab the node with the highest
621 // priority. If it is not ready put it back. Schedule the node.
622 std::vector<SUnit*> NotReady;
Chris Lattner572003c2006-03-12 00:38:57 +0000623 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
624 // Check to see if any of the pending instructions are ready to issue. If
625 // so, add them to the available queue.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000626 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Chris Lattner572003c2006-03-12 00:38:57 +0000627 if (PendingQueue[i].first == CurCycle) {
628 AvailableQueue->push(PendingQueue[i].second);
629 PendingQueue[i].second->isAvailable = true;
630 PendingQueue[i] = PendingQueue.back();
631 PendingQueue.pop_back();
632 --i; --e;
633 } else {
634 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
635 }
Chris Lattnera767dbf2006-03-12 09:01:41 +0000636 }
Chris Lattner572003c2006-03-12 00:38:57 +0000637
Chris Lattnera767dbf2006-03-12 09:01:41 +0000638 // If there are no instructions available, don't try to issue anything, and
639 // don't advance the hazard recognizer.
640 if (AvailableQueue->empty()) {
641 ++CurCycle;
642 continue;
643 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000644
Chris Lattnera767dbf2006-03-12 09:01:41 +0000645 SUnit *FoundSUnit = 0;
646 SDNode *FoundNode = 0;
647
Chris Lattnere50c0922006-03-05 22:45:01 +0000648 bool HasNoopHazards = false;
Chris Lattner572003c2006-03-12 00:38:57 +0000649 while (!AvailableQueue->empty()) {
Chris Lattnera767dbf2006-03-12 09:01:41 +0000650 SUnit *CurSUnit = AvailableQueue->pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000651
652 // Get the node represented by this SUnit.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000653 FoundNode = CurSUnit->Node;
654
Chris Lattner0c801bd2006-03-07 05:40:43 +0000655 // If this is a pseudo op, like copyfromreg, look to see if there is a
656 // real target node flagged to it. If so, use the target node.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000657 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
658 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
659 FoundNode = CurSUnit->FlaggedNodes[i];
Chris Lattner0c801bd2006-03-07 05:40:43 +0000660
Chris Lattnera767dbf2006-03-12 09:01:41 +0000661 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
Chris Lattnere50c0922006-03-05 22:45:01 +0000662 if (HT == HazardRecognizer::NoHazard) {
Chris Lattnera767dbf2006-03-12 09:01:41 +0000663 FoundSUnit = CurSUnit;
Chris Lattnere50c0922006-03-05 22:45:01 +0000664 break;
665 }
666
667 // Remember if this is a noop hazard.
668 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
669
Chris Lattnera767dbf2006-03-12 09:01:41 +0000670 NotReady.push_back(CurSUnit);
Chris Lattner572003c2006-03-12 00:38:57 +0000671 }
Chris Lattnere50c0922006-03-05 22:45:01 +0000672
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000673 // Add the nodes that aren't ready back onto the available list.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000674 if (!NotReady.empty()) {
675 AvailableQueue->push_all(NotReady);
676 NotReady.clear();
677 }
Chris Lattnere50c0922006-03-05 22:45:01 +0000678
679 // If we found a node to schedule, do it now.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000680 if (FoundSUnit) {
681 ScheduleNodeTopDown(FoundSUnit, CurCycle);
682 HazardRec->EmitInstruction(FoundNode);
683 FoundSUnit->isScheduled = true;
684 AvailableQueue->ScheduledNode(FoundSUnit);
Chris Lattner572003c2006-03-12 00:38:57 +0000685
686 // If this is a pseudo-op node, we don't want to increment the current
687 // cycle.
Chris Lattnera767dbf2006-03-12 09:01:41 +0000688 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
689 ++CurCycle;
Chris Lattnere50c0922006-03-05 22:45:01 +0000690 } else if (!HasNoopHazards) {
691 // Otherwise, we have a pipeline stall, but no other problem, just advance
692 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000693 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000694 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000695 ++NumStalls;
Chris Lattnera767dbf2006-03-12 09:01:41 +0000696 ++CurCycle;
Chris Lattnere50c0922006-03-05 22:45:01 +0000697 } else {
698 // Otherwise, we have no instructions to issue and we have instructions
699 // that will fault if we don't do this right. This is the case for
700 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000701 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000702 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000703 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000704 ++NumNoops;
Chris Lattnera767dbf2006-03-12 09:01:41 +0000705 ++CurCycle;
Chris Lattnere50c0922006-03-05 22:45:01 +0000706 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000707 }
708
709#ifndef NDEBUG
710 // Verify that all SUnits were scheduled.
711 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000712 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
713 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000714 if (!AnyNotSched)
715 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000716 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000717 std::cerr << "has not been scheduled!\n";
718 AnyNotSched = true;
719 }
720 }
721 assert(!AnyNotSched);
722#endif
723}
724
Chris Lattner9df64752006-03-09 06:35:14 +0000725//===----------------------------------------------------------------------===//
726// RegReductionPriorityQueue Implementation
727//===----------------------------------------------------------------------===//
728//
729// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
730// to reduce register pressure.
731//
732namespace {
733 class RegReductionPriorityQueue;
734
735 /// Sorting functions for the Available queue.
736 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
737 RegReductionPriorityQueue *SPQ;
738 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
739 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
740
741 bool operator()(const SUnit* left, const SUnit* right) const;
742 };
743} // end anonymous namespace
744
745namespace {
746 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
747 // SUnits - The SUnits for the current graph.
748 const std::vector<SUnit> *SUnits;
749
750 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng24e79542006-05-01 09:14:40 +0000751 std::vector<unsigned> SethiUllmanNumbers;
Chris Lattner9df64752006-03-09 06:35:14 +0000752
753 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
754 public:
755 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
756 }
757
758 void initNodes(const std::vector<SUnit> &sunits) {
759 SUnits = &sunits;
760 // Calculate node priorities.
761 CalculatePriorities();
762 }
763 void releaseState() {
764 SUnits = 0;
765 SethiUllmanNumbers.clear();
766 }
767
768 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
769 assert(NodeNum < SethiUllmanNumbers.size());
770 return SethiUllmanNumbers[NodeNum];
771 }
772
773 bool empty() const { return Queue.empty(); }
774
775 void push(SUnit *U) {
776 Queue.push(U);
777 }
Chris Lattner25e25562006-03-10 04:32:49 +0000778 void push_all(const std::vector<SUnit *> &Nodes) {
779 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
780 Queue.push(Nodes[i]);
781 }
782
Chris Lattner9df64752006-03-09 06:35:14 +0000783 SUnit *pop() {
784 SUnit *V = Queue.top();
785 Queue.pop();
786 return V;
787 }
788 private:
789 void CalculatePriorities();
Evan Cheng24e79542006-05-01 09:14:40 +0000790 unsigned CalcNodePriority(const SUnit *SU);
Chris Lattner9df64752006-03-09 06:35:14 +0000791 };
792}
793
794bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
795 unsigned LeftNum = left->NodeNum;
796 unsigned RightNum = right->NodeNum;
797
798 int LBonus = (int)left ->isDefNUseOperand;
799 int RBonus = (int)right->isDefNUseOperand;
Evan Cheng24e79542006-05-01 09:14:40 +0000800
Chris Lattner9df64752006-03-09 06:35:14 +0000801 // Special tie breaker: if two nodes share a operand, the one that
802 // use it as a def&use operand is preferred.
803 if (left->isTwoAddress && !right->isTwoAddress) {
804 SDNode *DUNode = left->Node->getOperand(0).Val;
805 if (DUNode->isOperand(right->Node))
806 LBonus++;
807 }
808 if (!left->isTwoAddress && right->isTwoAddress) {
809 SDNode *DUNode = right->Node->getOperand(0).Val;
810 if (DUNode->isOperand(left->Node))
811 RBonus++;
812 }
813
Evan Cheng24e79542006-05-01 09:14:40 +0000814 // Push stores up as much as possible. This really help code like this:
815 // load
816 // compute
817 // store
818 // load
819 // compute
820 // store
821 // This would make sure the scheduled code completed all computations and
822 // the stores before the next series of computation starts.
823 if (!left->isStore && right->isStore)
824 LBonus += 2;
825 if (left->isStore && !right->isStore)
826 RBonus += 2;
827
Chris Lattner9df64752006-03-09 06:35:14 +0000828 // Priority1 is just the number of live range genned.
829 int LPriority1 = left ->NumPredsLeft - LBonus;
830 int RPriority1 = right->NumPredsLeft - RBonus;
831 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
832 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
833
834 if (LPriority1 > RPriority1)
835 return true;
836 else if (LPriority1 == RPriority1)
837 if (LPriority2 < RPriority2)
838 return true;
839 else if (LPriority2 == RPriority2)
840 if (left->CycleBound > right->CycleBound)
841 return true;
842
843 return false;
844}
845
846
847/// CalcNodePriority - Priority is the Sethi Ullman number.
848/// Smaller number is the higher priority.
Evan Cheng24e79542006-05-01 09:14:40 +0000849unsigned RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
850 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
851 if (SethiUllmanNumber != 0)
Chris Lattner9df64752006-03-09 06:35:14 +0000852 return SethiUllmanNumber;
853
854 if (SU->Preds.size() == 0) {
855 SethiUllmanNumber = 1;
856 } else {
857 int Extra = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000858 for (std::set<std::pair<SUnit*, bool> >::const_iterator
859 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
860 if (I->second) continue; // ignore chain preds.
861 SUnit *PredSU = I->first;
Evan Cheng24e79542006-05-01 09:14:40 +0000862 unsigned PredSethiUllman = CalcNodePriority(PredSU);
Chris Lattner9df64752006-03-09 06:35:14 +0000863 if (PredSethiUllman > SethiUllmanNumber) {
864 SethiUllmanNumber = PredSethiUllman;
865 Extra = 0;
866 } else if (PredSethiUllman == SethiUllmanNumber)
867 Extra++;
868 }
869
Evan Cheng24e79542006-05-01 09:14:40 +0000870 SethiUllmanNumber += Extra;
Chris Lattner9df64752006-03-09 06:35:14 +0000871 }
872
873 return SethiUllmanNumber;
874}
875
876/// CalculatePriorities - Calculate priorities of all scheduling units.
877void RegReductionPriorityQueue::CalculatePriorities() {
Evan Cheng24e79542006-05-01 09:14:40 +0000878 SethiUllmanNumbers.assign(SUnits->size(), 0);
Chris Lattner9df64752006-03-09 06:35:14 +0000879
880 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
881 CalcNodePriority(&(*SUnits)[i]);
882}
883
Chris Lattner6398c132006-03-09 07:38:27 +0000884//===----------------------------------------------------------------------===//
885// LatencyPriorityQueue Implementation
886//===----------------------------------------------------------------------===//
887//
888// This is a SchedulingPriorityQueue that schedules using latency information to
889// reduce the length of the critical path through the basic block.
890//
891namespace {
892 class LatencyPriorityQueue;
893
894 /// Sorting functions for the Available queue.
895 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
896 LatencyPriorityQueue *PQ;
897 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
898 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
899
900 bool operator()(const SUnit* left, const SUnit* right) const;
901 };
902} // end anonymous namespace
903
904namespace {
905 class LatencyPriorityQueue : public SchedulingPriorityQueue {
906 // SUnits - The SUnits for the current graph.
907 const std::vector<SUnit> *SUnits;
908
909 // Latencies - The latency (max of latency from this node to the bb exit)
910 // for each node.
911 std::vector<int> Latencies;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000912
913 /// NumNodesSolelyBlocking - This vector contains, for every node in the
914 /// Queue, the number of nodes that the node is the sole unscheduled
915 /// predecessor for. This is used as a tie-breaker heuristic for better
916 /// mobility.
917 std::vector<unsigned> NumNodesSolelyBlocking;
918
Chris Lattner6398c132006-03-09 07:38:27 +0000919 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
920public:
921 LatencyPriorityQueue() : Queue(latency_sort(this)) {
922 }
923
924 void initNodes(const std::vector<SUnit> &sunits) {
925 SUnits = &sunits;
926 // Calculate node priorities.
927 CalculatePriorities();
928 }
929 void releaseState() {
930 SUnits = 0;
931 Latencies.clear();
932 }
933
934 unsigned getLatency(unsigned NodeNum) const {
935 assert(NodeNum < Latencies.size());
936 return Latencies[NodeNum];
937 }
938
Chris Lattner349e9dd2006-03-10 05:51:05 +0000939 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
940 assert(NodeNum < NumNodesSolelyBlocking.size());
941 return NumNodesSolelyBlocking[NodeNum];
942 }
943
Chris Lattner6398c132006-03-09 07:38:27 +0000944 bool empty() const { return Queue.empty(); }
945
Chris Lattner349e9dd2006-03-10 05:51:05 +0000946 virtual void push(SUnit *U) {
947 push_impl(U);
Chris Lattner6398c132006-03-09 07:38:27 +0000948 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000949 void push_impl(SUnit *U);
950
Chris Lattner25e25562006-03-10 04:32:49 +0000951 void push_all(const std::vector<SUnit *> &Nodes) {
952 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000953 push_impl(Nodes[i]);
Chris Lattner25e25562006-03-10 04:32:49 +0000954 }
955
Chris Lattner6398c132006-03-09 07:38:27 +0000956 SUnit *pop() {
957 SUnit *V = Queue.top();
958 Queue.pop();
Chris Lattner6398c132006-03-09 07:38:27 +0000959 return V;
960 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000961
962 // ScheduledNode - As nodes are scheduled, we look to see if there are any
963 // successor nodes that have a single unscheduled predecessor. If so, that
964 // single predecessor has a higher priority, since scheduling it will make
965 // the node available.
966 void ScheduledNode(SUnit *Node);
967
Chris Lattner6398c132006-03-09 07:38:27 +0000968private:
969 void CalculatePriorities();
970 int CalcLatency(const SUnit &SU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000971 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
972
973 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
974 /// node from a priority queue. We should roll our own heap to make this
975 /// better or something.
976 void RemoveFromPriorityQueue(SUnit *SU) {
977 std::vector<SUnit*> Temp;
978
979 assert(!Queue.empty() && "Not in queue!");
980 while (Queue.top() != SU) {
981 Temp.push_back(Queue.top());
982 Queue.pop();
983 assert(!Queue.empty() && "Not in queue!");
984 }
985
986 // Remove the node from the PQ.
987 Queue.pop();
988
989 // Add all the other nodes back.
990 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
991 Queue.push(Temp[i]);
992 }
Chris Lattner6398c132006-03-09 07:38:27 +0000993 };
994}
995
996bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
997 unsigned LHSNum = LHS->NodeNum;
998 unsigned RHSNum = RHS->NodeNum;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000999
1000 // The most important heuristic is scheduling the critical path.
1001 unsigned LHSLatency = PQ->getLatency(LHSNum);
1002 unsigned RHSLatency = PQ->getLatency(RHSNum);
1003 if (LHSLatency < RHSLatency) return true;
1004 if (LHSLatency > RHSLatency) return false;
Chris Lattner6398c132006-03-09 07:38:27 +00001005
Chris Lattner349e9dd2006-03-10 05:51:05 +00001006 // After that, if two nodes have identical latencies, look to see if one will
1007 // unblock more other nodes than the other.
1008 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
1009 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
1010 if (LHSBlocked < RHSBlocked) return true;
1011 if (LHSBlocked > RHSBlocked) return false;
1012
1013 // Finally, just to provide a stable ordering, use the node number as a
1014 // deciding factor.
1015 return LHSNum < RHSNum;
Chris Lattner6398c132006-03-09 07:38:27 +00001016}
1017
1018
1019/// CalcNodePriority - Calculate the maximal path from the node to the exit.
1020///
1021int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
1022 int &Latency = Latencies[SU.NodeNum];
1023 if (Latency != -1)
1024 return Latency;
1025
1026 int MaxSuccLatency = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001027 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +00001028 E = SU.Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001029 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
Chris Lattner6398c132006-03-09 07:38:27 +00001030
1031 return Latency = MaxSuccLatency + SU.Latency;
1032}
1033
1034/// CalculatePriorities - Calculate priorities of all scheduling units.
1035void LatencyPriorityQueue::CalculatePriorities() {
1036 Latencies.assign(SUnits->size(), -1);
Chris Lattner349e9dd2006-03-10 05:51:05 +00001037 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
Chris Lattner6398c132006-03-09 07:38:27 +00001038
1039 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1040 CalcLatency((*SUnits)[i]);
1041}
1042
Chris Lattner349e9dd2006-03-10 05:51:05 +00001043/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
1044/// of SU, return it, otherwise return null.
1045static SUnit *getSingleUnscheduledPred(SUnit *SU) {
1046 SUnit *OnlyAvailablePred = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001047 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001048 E = SU->Preds.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001049 if (!I->first->isScheduled) {
Chris Lattner349e9dd2006-03-10 05:51:05 +00001050 // We found an available, but not scheduled, predecessor. If it's the
1051 // only one we have found, keep track of it... otherwise give up.
Chris Lattner578d8fc2006-03-11 22:24:20 +00001052 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
Chris Lattner349e9dd2006-03-10 05:51:05 +00001053 return 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001054 OnlyAvailablePred = I->first;
Chris Lattner349e9dd2006-03-10 05:51:05 +00001055 }
1056
1057 return OnlyAvailablePred;
1058}
1059
1060void LatencyPriorityQueue::push_impl(SUnit *SU) {
1061 // Look at all of the successors of this node. Count the number of nodes that
1062 // this node is the sole unscheduled node for.
1063 unsigned NumNodesBlocking = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001064 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001065 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001066 if (getSingleUnscheduledPred(I->first) == SU)
Chris Lattner349e9dd2006-03-10 05:51:05 +00001067 ++NumNodesBlocking;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001068 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
Chris Lattner349e9dd2006-03-10 05:51:05 +00001069
1070 Queue.push(SU);
1071}
1072
1073
1074// ScheduledNode - As nodes are scheduled, we look to see if there are any
1075// successor nodes that have a single unscheduled predecessor. If so, that
1076// single predecessor has a higher priority, since scheduling it will make
1077// the node available.
1078void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
Chris Lattner578d8fc2006-03-11 22:24:20 +00001079 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001080 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001081 AdjustPriorityOfUnscheduledPreds(I->first);
Chris Lattner349e9dd2006-03-10 05:51:05 +00001082}
1083
1084/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1085/// scheduled. If SU is not itself available, then there is at least one
1086/// predecessor node that has not been scheduled yet. If SU has exactly ONE
1087/// unscheduled predecessor, we want to increase its priority: it getting
1088/// scheduled will make this node available, so it is better than some other
1089/// node of the same priority that will not make a node available.
1090void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
Chris Lattner572003c2006-03-12 00:38:57 +00001091 if (SU->isPending) return; // All preds scheduled.
Chris Lattner349e9dd2006-03-10 05:51:05 +00001092
1093 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1094 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1095
1096 // Okay, we found a single predecessor that is available, but not scheduled.
1097 // Since it is available, it must be in the priority queue. First remove it.
1098 RemoveFromPriorityQueue(OnlyAvailablePred);
1099
1100 // Reinsert the node into the priority queue, which recomputes its
1101 // NumNodesSolelyBlocking value.
1102 push(OnlyAvailablePred);
1103}
1104
Chris Lattner9df64752006-03-09 06:35:14 +00001105
1106//===----------------------------------------------------------------------===//
1107// Public Constructor Functions
1108//===----------------------------------------------------------------------===//
1109
Evan Chengab495562006-01-25 09:14:32 +00001110llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1111 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +00001112 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +00001113 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +00001114 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00001115}
1116
Chris Lattner47639db2006-03-06 00:22:00 +00001117/// createTDListDAGScheduler - This creates a top-down list scheduler with the
1118/// specified hazard recognizer.
1119ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1120 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +00001121 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +00001122 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
Chris Lattner6398c132006-03-09 07:38:27 +00001123 new LatencyPriorityQueue(),
Chris Lattner9df64752006-03-09 06:35:14 +00001124 HR);
Evan Cheng31272342006-01-23 08:26:10 +00001125}