blob: 6cf5a4185f812de61157ded00dcd16ccc66db920 [file] [log] [blame]
Evan Chengd38c22b2006-05-11 23:55:42 +00001//===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
2//
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//
10// This implements bottom-up and top-down register pressure reduction list
11// schedulers, using standard algorithms. The basic approach uses a priority
12// queue of available nodes to schedule. One at a time, nodes are taken from
13// the priority queue (thus in priority order), checked for legality to
14// schedule, and emitted if legal.
15//
16//===----------------------------------------------------------------------===//
17
Dale Johannesen2182f062007-07-13 17:13:54 +000018#define DEBUG_TYPE "pre-RA-sched"
Evan Chengd38c22b2006-05-11 23:55:42 +000019#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000020#include "llvm/CodeGen/SchedulerRegistry.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000021#include "llvm/CodeGen/SSARegMap.h"
22#include "llvm/Target/MRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000023#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000024#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000027#include "llvm/Support/Compiler.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000028#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000029#include "llvm/ADT/Statistic.h"
30#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000031#include <queue>
32#include "llvm/Support/CommandLine.h"
33using namespace llvm;
34
Evan Cheng1ec79b42007-09-27 07:09:03 +000035STATISTIC(NumBacktracks, "Number of times scheduler backtraced");
36STATISTIC(NumDups, "Number of duplicated nodes");
37STATISTIC(NumCCCopies, "Number of cross class copies");
38
Jim Laskey95eda5b2006-08-01 14:21:23 +000039static RegisterScheduler
40 burrListDAGScheduler("list-burr",
41 " Bottom-up register reduction list scheduling",
42 createBURRListDAGScheduler);
43static RegisterScheduler
44 tdrListrDAGScheduler("list-tdrr",
45 " Top-down register reduction list scheduling",
46 createTDRRListDAGScheduler);
47
Evan Chengd38c22b2006-05-11 23:55:42 +000048namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000049//===----------------------------------------------------------------------===//
50/// ScheduleDAGRRList - The actual register reduction list scheduler
51/// implementation. This supports both top-down and bottom-up scheduling.
52///
Chris Lattnere097e6f2006-06-28 22:17:39 +000053class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
Evan Chengd38c22b2006-05-11 23:55:42 +000054private:
55 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
56 /// it is top-down.
57 bool isBottomUp;
58
59 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Cheng5924bf72007-09-25 01:54:36 +000060 ///a
Evan Chengd38c22b2006-05-11 23:55:42 +000061 SchedulingPriorityQueue *AvailableQueue;
62
Evan Cheng5924bf72007-09-25 01:54:36 +000063 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
64 /// that are "live". These nodes must be scheduled before any other nodes that
65 /// modifies the registers can be scheduled.
66 SmallSet<unsigned, 4> LiveRegs;
67 std::vector<SUnit*> LiveRegDefs;
68 std::vector<unsigned> LiveRegCycles;
69
Evan Chengd38c22b2006-05-11 23:55:42 +000070public:
71 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
72 const TargetMachine &tm, bool isbottomup,
73 SchedulingPriorityQueue *availqueue)
74 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
75 AvailableQueue(availqueue) {
76 }
77
78 ~ScheduleDAGRRList() {
79 delete AvailableQueue;
80 }
81
82 void Schedule();
83
84private:
Evan Cheng8e136a92007-09-26 21:36:17 +000085 void ReleasePred(SUnit*, bool, unsigned);
86 void ReleaseSucc(SUnit*, bool isChain, unsigned);
87 void CapturePred(SUnit*, SUnit*, bool);
88 void ScheduleNodeBottomUp(SUnit*, unsigned);
89 void ScheduleNodeTopDown(SUnit*, unsigned);
90 void UnscheduleNodeBottomUp(SUnit*);
91 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
92 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Cheng1ec79b42007-09-27 07:09:03 +000093 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
Evan Cheng8e136a92007-09-26 21:36:17 +000094 const TargetRegisterClass*,
Evan Cheng1ec79b42007-09-27 07:09:03 +000095 const TargetRegisterClass*,
96 SmallVector<SUnit*, 2>&);
97 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Evan Chengd38c22b2006-05-11 23:55:42 +000098 void ListScheduleTopDown();
99 void ListScheduleBottomUp();
Evan Chengafed73e2006-05-12 01:58:24 +0000100 void CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000101};
102} // end anonymous namespace
103
104
105/// Schedule - Schedule the DAG using list scheduling.
106void ScheduleDAGRRList::Schedule() {
Bill Wendling22e978a2006-12-07 20:04:42 +0000107 DOUT << "********** List Scheduling **********\n";
Evan Cheng5924bf72007-09-25 01:54:36 +0000108
109 LiveRegDefs.resize(MRI->getNumRegs(), NULL);
110 LiveRegCycles.resize(MRI->getNumRegs(), 0);
111
Evan Chengd38c22b2006-05-11 23:55:42 +0000112 // Build scheduling units.
113 BuildSchedUnits();
114
Evan Chengd38c22b2006-05-11 23:55:42 +0000115 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Chris Lattnerd86418a2006-08-17 00:09:56 +0000116 SUnits[su].dumpAll(&DAG));
Evan Cheng47fbeda2006-10-14 08:34:06 +0000117 CalculateDepths();
118 CalculateHeights();
Evan Chengd38c22b2006-05-11 23:55:42 +0000119
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000120 AvailableQueue->initNodes(SUnitMap, SUnits);
Dan Gohman54a187e2007-08-20 19:28:38 +0000121
Evan Chengd38c22b2006-05-11 23:55:42 +0000122 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
123 if (isBottomUp)
124 ListScheduleBottomUp();
125 else
126 ListScheduleTopDown();
127
128 AvailableQueue->releaseState();
Dan Gohman54a187e2007-08-20 19:28:38 +0000129
Evan Cheng009f5f52006-05-25 08:37:31 +0000130 CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000131
Bill Wendling22e978a2006-12-07 20:04:42 +0000132 DOUT << "*** Final schedule ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000133 DEBUG(dumpSchedule());
Bill Wendling22e978a2006-12-07 20:04:42 +0000134 DOUT << "\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000135
136 // Emit in scheduled order
137 EmitSchedule();
138}
139
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000140/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
Evan Chengafed73e2006-05-12 01:58:24 +0000141/// it is not the last use of its first operand, add it to the CommuteSet if
142/// possible. It will be commuted when it is translated to a MI.
143void ScheduleDAGRRList::CommuteNodesToReducePressure() {
Evan Chenge3c44192007-06-22 01:35:51 +0000144 SmallPtrSet<SUnit*, 4> OperandSeen;
Evan Chengafed73e2006-05-12 01:58:24 +0000145 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
146 SUnit *SU = Sequence[i];
Evan Cheng8e136a92007-09-26 21:36:17 +0000147 if (!SU || !SU->Node) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000148 if (SU->isCommutable) {
149 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +0000150 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000151 unsigned NumOps = CountOperands(SU->Node);
152 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000153 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000154 continue;
155
156 SDNode *OpN = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000157 SUnit *OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000158 if (OpSU && OperandSeen.count(OpSU) == 1) {
159 // Ok, so SU is not the last use of OpSU, but SU is two-address so
160 // it will clobber OpSU. Try to commute SU if no other source operands
161 // are live below.
162 bool DoCommute = true;
163 for (unsigned k = 0; k < NumOps; ++k) {
164 if (k != j) {
165 OpN = SU->Node->getOperand(k).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000166 OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000167 if (OpSU && OperandSeen.count(OpSU) == 1) {
168 DoCommute = false;
169 break;
170 }
171 }
Evan Chengafed73e2006-05-12 01:58:24 +0000172 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000173 if (DoCommute)
174 CommuteSet.insert(SU->Node);
Evan Chengafed73e2006-05-12 01:58:24 +0000175 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000176
177 // Only look at the first use&def node for now.
178 break;
Evan Chengafed73e2006-05-12 01:58:24 +0000179 }
180 }
181
Chris Lattnerd86418a2006-08-17 00:09:56 +0000182 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
183 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000184 if (!I->isCtrl)
185 OperandSeen.insert(I->Dep);
Evan Chengafed73e2006-05-12 01:58:24 +0000186 }
187 }
188}
Evan Chengd38c22b2006-05-11 23:55:42 +0000189
190//===----------------------------------------------------------------------===//
191// Bottom-Up Scheduling
192//===----------------------------------------------------------------------===//
193
Evan Chengd38c22b2006-05-11 23:55:42 +0000194/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000195/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000196void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
197 unsigned CurCycle) {
198 // FIXME: the distance between two nodes is not always == the predecessor's
199 // latency. For example, the reader can very well read the register written
200 // by the predecessor later than the issue cycle. It also depends on the
201 // interrupt model (drain vs. freeze).
202 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
203
204 if (!isChain)
Evan Cheng5924bf72007-09-25 01:54:36 +0000205 --PredSU->NumSuccsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000206 else
Evan Cheng5924bf72007-09-25 01:54:36 +0000207 --PredSU->NumChainSuccsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000208
209#ifndef NDEBUG
210 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000211 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000212 PredSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000213 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000214 assert(0);
215 }
216#endif
217
218 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
219 // EntryToken has to go last! Special case it here.
Evan Cheng8e136a92007-09-26 21:36:17 +0000220 if (!PredSU->Node || PredSU->Node->getOpcode() != ISD::EntryToken) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000221 PredSU->isAvailable = true;
222 AvailableQueue->push(PredSU);
223 }
224 }
225}
226
227/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
228/// count of its predecessors. If a predecessor pending count is zero, add it to
229/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000230void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000231 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000232 DEBUG(SU->dump(&DAG));
233 SU->Cycle = CurCycle;
234
235 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000236
237 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000238 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000239 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000240 ReleasePred(I->Dep, I->isCtrl, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000241 if (I->Cost < 0) {
242 // This is a physical register dependency and it's impossible or
243 // expensive to copy the register. Make sure nothing that can
244 // clobber the register is scheduled between the predecessor and
245 // this node.
246 if (LiveRegs.insert(I->Reg)) {
247 LiveRegDefs[I->Reg] = I->Dep;
248 LiveRegCycles[I->Reg] = CurCycle;
249 }
250 }
251 }
252
253 // Release all the implicit physical register defs that are live.
254 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
255 I != E; ++I) {
256 if (I->Cost < 0) {
257 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
258 LiveRegs.erase(I->Reg);
259 assert(LiveRegDefs[I->Reg] == SU &&
260 "Physical register dependency violated?");
261 LiveRegDefs[I->Reg] = NULL;
262 LiveRegCycles[I->Reg] = 0;
263 }
264 }
265 }
266
Evan Chengd38c22b2006-05-11 23:55:42 +0000267 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000268}
269
Evan Cheng5924bf72007-09-25 01:54:36 +0000270/// CapturePred - This does the opposite of ReleasePred. Since SU is being
271/// unscheduled, incrcease the succ left count of its predecessors. Remove
272/// them from AvailableQueue if necessary.
273void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
274 PredSU->CycleBound = 0;
275 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
276 I != E; ++I) {
277 if (I->Dep == SU)
278 continue;
279 PredSU->CycleBound = std::max(PredSU->CycleBound,
280 I->Dep->Cycle + PredSU->Latency);
281 }
282
283 if (PredSU->isAvailable) {
284 PredSU->isAvailable = false;
285 if (!PredSU->isPending)
286 AvailableQueue->remove(PredSU);
287 }
288
289 if (!isChain)
290 ++PredSU->NumSuccsLeft;
291 else
292 ++PredSU->NumChainSuccsLeft;
293}
294
295/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
296/// its predecessor states to reflect the change.
297void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
298 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
299 DEBUG(SU->dump(&DAG));
300
301 AvailableQueue->UnscheduledNode(SU);
302
303 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
304 I != E; ++I) {
305 CapturePred(I->Dep, SU, I->isCtrl);
306 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
307 LiveRegs.erase(I->Reg);
308 assert(LiveRegDefs[I->Reg] == I->Dep &&
309 "Physical register dependency violated?");
310 LiveRegDefs[I->Reg] = NULL;
311 LiveRegCycles[I->Reg] = 0;
312 }
313 }
314
315 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
316 I != E; ++I) {
317 if (I->Cost < 0) {
318 if (LiveRegs.insert(I->Reg)) {
319 assert(!LiveRegDefs[I->Reg] &&
320 "Physical register dependency violated?");
321 LiveRegDefs[I->Reg] = SU;
322 }
323 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
324 LiveRegCycles[I->Reg] = I->Dep->Cycle;
325 }
326 }
327
328 SU->Cycle = 0;
329 SU->isScheduled = false;
330 SU->isAvailable = true;
331 AvailableQueue->push(SU);
332}
333
Evan Chengcfd5f822007-09-27 00:25:29 +0000334// FIXME: This is probably too slow!
335static void isReachable(SUnit *SU, SUnit *TargetSU,
336 SmallPtrSet<SUnit*, 32> &Visited, bool &Reached) {
337 if (Reached) return;
338 if (SU == TargetSU) {
339 Reached = true;
340 return;
341 }
342 if (!Visited.insert(SU)) return;
343
344 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
345 ++I)
346 isReachable(I->Dep, TargetSU, Visited, Reached);
347}
348
349static bool isReachable(SUnit *SU, SUnit *TargetSU) {
350 SmallPtrSet<SUnit*, 32> Visited;
351 bool Reached = false;
352 isReachable(SU, TargetSU, Visited, Reached);
353 return Reached;
354}
355
356/// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
357/// create a cycle.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000358static bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
Evan Chengcfd5f822007-09-27 00:25:29 +0000359 if (isReachable(TargetSU, SU))
360 return true;
361 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
362 I != E; ++I)
363 if (I->Cost < 0 && isReachable(TargetSU, I->Dep))
364 return true;
365 return false;
366}
367
Evan Cheng8e136a92007-09-26 21:36:17 +0000368/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Evan Cheng5924bf72007-09-25 01:54:36 +0000369/// BTCycle in order to schedule a specific node. Returns the last unscheduled
370/// SUnit. Also returns if a successor is unscheduled in the process.
Evan Cheng8e136a92007-09-26 21:36:17 +0000371void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
372 unsigned &CurCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000373 SUnit *OldSU = NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000374 while (CurCycle > BtCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000375 OldSU = Sequence.back();
376 Sequence.pop_back();
377 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000378 // Don't try to remove SU from AvailableQueue.
379 SU->isAvailable = false;
Evan Cheng5924bf72007-09-25 01:54:36 +0000380 UnscheduleNodeBottomUp(OldSU);
381 --CurCycle;
382 }
383
384
385 if (SU->isSucc(OldSU)) {
386 assert(false && "Something is wrong!");
387 abort();
388 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000389
390 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000391}
392
393/// isSafeToCopy - True if the SUnit for the given SDNode can safely cloned,
394/// i.e. the node does not produce a flag, it does not read a flag and it does
395/// not have an incoming chain.
396static bool isSafeToCopy(SDNode *N) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000397 if (!N)
398 return true;
399
Evan Cheng5924bf72007-09-25 01:54:36 +0000400 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
401 if (N->getValueType(i) == MVT::Flag)
402 return false;
403 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
404 const SDOperand &Op = N->getOperand(i);
405 MVT::ValueType VT = Op.Val->getValueType(Op.ResNo);
406 if (VT == MVT::Other || VT == MVT::Flag)
407 return false;
408 }
409
410 return true;
411}
412
413/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
414/// successors to the newly created node.
415SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000416 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
417
Evan Cheng5924bf72007-09-25 01:54:36 +0000418 SUnit *NewSU = Clone(SU);
419
420 // New SUnit has the exact same predecessors.
421 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
422 I != E; ++I)
423 if (!I->isSpecial) {
424 NewSU->addPred(I->Dep, I->isCtrl, false, I->Reg, I->Cost);
425 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
426 }
427
428 // Only copy scheduled successors. Cut them from old node's successor
429 // list and move them over.
430 SmallVector<SDep*, 2> DelDeps;
431 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
432 I != E; ++I) {
433 if (I->isSpecial)
434 continue;
435 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
436 if (I->Dep->isScheduled) {
437 I->Dep->addPred(NewSU, I->isCtrl, false, I->Reg, I->Cost);
438 DelDeps.push_back(I);
439 }
440 }
441 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
442 SUnit *Succ = DelDeps[i]->Dep;
443 bool isCtrl = DelDeps[i]->isCtrl;
444 Succ->removePred(SU, isCtrl, false);
445 }
446
447 AvailableQueue->updateNode(SU);
448 AvailableQueue->addNode(NewSU);
449
Evan Cheng1ec79b42007-09-27 07:09:03 +0000450 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000451 return NewSU;
452}
453
Evan Cheng1ec79b42007-09-27 07:09:03 +0000454/// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
455/// and move all scheduled successors of the given SUnit to the last copy.
456void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
457 const TargetRegisterClass *DestRC,
458 const TargetRegisterClass *SrcRC,
459 SmallVector<SUnit*, 2> &Copies) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000460 SUnit *CopyFromSU = NewSUnit(NULL);
461 CopyFromSU->CopySrcRC = SrcRC;
462 CopyFromSU->CopyDstRC = DestRC;
463 CopyFromSU->Depth = SU->Depth;
464 CopyFromSU->Height = SU->Height;
465
466 SUnit *CopyToSU = NewSUnit(NULL);
467 CopyToSU->CopySrcRC = DestRC;
468 CopyToSU->CopyDstRC = SrcRC;
469
470 // Only copy scheduled successors. Cut them from old node's successor
471 // list and move them over.
472 SmallVector<SDep*, 2> DelDeps;
473 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
474 I != E; ++I) {
475 if (I->isSpecial)
476 continue;
477 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
478 if (I->Dep->isScheduled) {
479 I->Dep->addPred(CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
480 DelDeps.push_back(I);
481 }
482 }
483 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
484 SUnit *Succ = DelDeps[i]->Dep;
485 bool isCtrl = DelDeps[i]->isCtrl;
486 Succ->removePred(SU, isCtrl, false);
487 }
488
489 CopyFromSU->addPred(SU, false, false, Reg, -1);
490 CopyToSU->addPred(CopyFromSU, false, false, Reg, 1);
491
492 AvailableQueue->updateNode(SU);
493 AvailableQueue->addNode(CopyFromSU);
494 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000495 Copies.push_back(CopyFromSU);
496 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000497
Evan Cheng1ec79b42007-09-27 07:09:03 +0000498 ++NumCCCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000499}
500
501/// getPhysicalRegisterVT - Returns the ValueType of the physical register
502/// definition of the specified node.
503/// FIXME: Move to SelectionDAG?
504static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
505 const TargetInstrInfo *TII) {
506 const TargetInstrDescriptor &TID = TII->get(N->getTargetOpcode());
507 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
508 unsigned NumRes = TID.numDefs;
509 for (const unsigned *ImpDef = TID.ImplicitDefs; *ImpDef; ++ImpDef) {
510 if (Reg == *ImpDef)
511 break;
512 ++NumRes;
513 }
514 return N->getValueType(NumRes);
515}
516
Evan Cheng5924bf72007-09-25 01:54:36 +0000517/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
518/// scheduling of the given node to satisfy live physical register dependencies.
519/// If the specific node is the last one that's available to schedule, do
520/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000521bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
522 SmallVector<unsigned, 4> &LRegs){
Evan Cheng5924bf72007-09-25 01:54:36 +0000523 if (LiveRegs.empty())
524 return false;
525
526 // If this node would clobber any "live" register, then it's not ready.
Evan Cheng5924bf72007-09-25 01:54:36 +0000527 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
528 I != E; ++I) {
529 if (I->Cost < 0) {
530 unsigned Reg = I->Reg;
531 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep)
532 LRegs.push_back(Reg);
533 for (const unsigned *Alias = MRI->getAliasSet(Reg);
534 *Alias; ++Alias)
535 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep)
536 LRegs.push_back(*Alias);
537 }
538 }
539
540 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
541 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
Evan Cheng8e136a92007-09-26 21:36:17 +0000542 if (!Node || !Node->isTargetOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000543 continue;
544 const TargetInstrDescriptor &TID = TII->get(Node->getTargetOpcode());
545 if (!TID.ImplicitDefs)
546 continue;
547 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
548 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU)
549 LRegs.push_back(*Reg);
550 for (const unsigned *Alias = MRI->getAliasSet(*Reg);
551 *Alias; ++Alias)
552 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU)
553 LRegs.push_back(*Alias);
554 }
555 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000556 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000557}
558
Evan Cheng1ec79b42007-09-27 07:09:03 +0000559
Evan Chengd38c22b2006-05-11 23:55:42 +0000560/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
561/// schedulers.
562void ScheduleDAGRRList::ListScheduleBottomUp() {
563 unsigned CurCycle = 0;
564 // Add root to Available queue.
Evan Cheng5924bf72007-09-25 01:54:36 +0000565 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
566 RootSU->isAvailable = true;
567 AvailableQueue->push(RootSU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000568
569 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000570 // priority. If it is not ready put it back. Schedule the node.
Evan Cheng5924bf72007-09-25 01:54:36 +0000571 SmallVector<SUnit*, 4> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000572 while (!AvailableQueue->empty()) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000573 bool Delayed = false;
574 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
Evan Cheng5924bf72007-09-25 01:54:36 +0000575 SUnit *CurSU = AvailableQueue->pop();
576 while (CurSU) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000577 if (CurSU->CycleBound <= CurCycle) {
578 SmallVector<unsigned, 4> LRegs;
579 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
Evan Cheng5924bf72007-09-25 01:54:36 +0000580 break;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000581 Delayed = true;
582 LRegsMap.insert(std::make_pair(CurSU, LRegs));
Evan Cheng5924bf72007-09-25 01:54:36 +0000583 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000584
585 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
586 NotReady.push_back(CurSU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000587 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000588 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000589
590 // All candidates are delayed due to live physical reg dependencies.
591 // Try backtracking, code duplication, or inserting cross class copies
592 // to resolve it.
593 if (Delayed && !CurSU) {
594 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
595 SUnit *TrySU = NotReady[i];
596 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
597
598 // Try unscheduling up to the point where it's safe to schedule
599 // this node.
600 unsigned LiveCycle = CurCycle;
601 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
602 unsigned Reg = LRegs[j];
603 unsigned LCycle = LiveRegCycles[Reg];
604 LiveCycle = std::min(LiveCycle, LCycle);
605 }
606 SUnit *OldSU = Sequence[LiveCycle];
607 if (!WillCreateCycle(TrySU, OldSU)) {
608 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
609 // Force the current node to be scheduled before the node that
610 // requires the physical reg dep.
611 if (OldSU->isAvailable) {
612 OldSU->isAvailable = false;
613 AvailableQueue->remove(OldSU);
614 }
615 TrySU->addPred(OldSU, true, true);
616 // If one or more successors has been unscheduled, then the current
617 // node is no longer avaialable. Schedule a successor that's now
618 // available instead.
619 if (!TrySU->isAvailable)
620 CurSU = AvailableQueue->pop();
621 else {
622 CurSU = TrySU;
623 TrySU->isPending = false;
624 NotReady.erase(NotReady.begin()+i);
625 }
626 break;
627 }
628 }
629
630 if (!CurSU) {
631 // Can't backtrace. Try duplicating the nodes that produces these
632 // "expensive to copy" values to break the dependency. In case even
633 // that doesn't work, insert cross class copies.
634 SUnit *TrySU = NotReady[0];
635 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
636 assert(LRegs.size() == 1 && "Can't handle this yet!");
637 unsigned Reg = LRegs[0];
638 SUnit *LRDef = LiveRegDefs[Reg];
639 SUnit *NewDef;
640 if (isSafeToCopy(LRDef->Node))
641 NewDef = CopyAndMoveSuccessors(LRDef);
642 else {
643 // Issue expensive cross register class copies.
644 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
645 const TargetRegisterClass *RC =
646 MRI->getPhysicalRegisterRegClass(VT, Reg);
647 const TargetRegisterClass *DestRC = MRI->getCrossCopyRegClass(RC);
648 if (!DestRC) {
649 assert(false && "Don't know how to copy this physical register!");
650 abort();
651 }
652 SmallVector<SUnit*, 2> Copies;
653 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
654 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
655 << " to SU #" << Copies.front()->NodeNum << "\n";
656 TrySU->addPred(Copies.front(), true, true);
657 NewDef = Copies.back();
658 }
659
660 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
661 << " to SU #" << TrySU->NodeNum << "\n";
662 LiveRegDefs[Reg] = NewDef;
663 NewDef->addPred(TrySU, true, true);
664 TrySU->isAvailable = false;
665 CurSU = NewDef;
666 }
667
668 if (!CurSU) {
669 assert(false && "Unable to resolve live physical register dependencies!");
670 abort();
671 }
672 }
673
Evan Chengd38c22b2006-05-11 23:55:42 +0000674 // Add the nodes that aren't ready back onto the available list.
Evan Cheng5924bf72007-09-25 01:54:36 +0000675 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
676 NotReady[i]->isPending = false;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000677 // May no longer be available due to backtracking.
Evan Cheng5924bf72007-09-25 01:54:36 +0000678 if (NotReady[i]->isAvailable)
679 AvailableQueue->push(NotReady[i]);
680 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000681 NotReady.clear();
682
Evan Cheng5924bf72007-09-25 01:54:36 +0000683 if (!CurSU)
684 Sequence.push_back(0);
685 else {
686 ScheduleNodeBottomUp(CurSU, CurCycle);
687 Sequence.push_back(CurSU);
688 }
689 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000690 }
691
692 // Add entry node last
693 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000694 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000695 Sequence.push_back(Entry);
696 }
697
698 // Reverse the order if it is bottom up.
699 std::reverse(Sequence.begin(), Sequence.end());
700
701
702#ifndef NDEBUG
703 // Verify that all SUnits were scheduled.
704 bool AnyNotSched = false;
705 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
706 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
707 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000708 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000709 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000710 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000711 AnyNotSched = true;
712 }
713 }
714 assert(!AnyNotSched);
715#endif
716}
717
718//===----------------------------------------------------------------------===//
719// Top-Down Scheduling
720//===----------------------------------------------------------------------===//
721
722/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000723/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000724void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
725 unsigned CurCycle) {
726 // FIXME: the distance between two nodes is not always == the predecessor's
727 // latency. For example, the reader can very well read the register written
728 // by the predecessor later than the issue cycle. It also depends on the
729 // interrupt model (drain vs. freeze).
730 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
731
732 if (!isChain)
Evan Cheng5924bf72007-09-25 01:54:36 +0000733 --SuccSU->NumPredsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000734 else
Evan Cheng5924bf72007-09-25 01:54:36 +0000735 --SuccSU->NumChainPredsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000736
737#ifndef NDEBUG
738 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000739 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000740 SuccSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000741 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000742 assert(0);
743 }
744#endif
745
746 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
747 SuccSU->isAvailable = true;
748 AvailableQueue->push(SuccSU);
749 }
750}
751
752
753/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
754/// count of its successors. If a successor pending count is zero, add it to
755/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000756void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000757 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000758 DEBUG(SU->dump(&DAG));
759 SU->Cycle = CurCycle;
760
761 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000762
763 // Top down: release successors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000764 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
765 I != E; ++I)
Evan Cheng0effc3a2007-09-19 01:38:40 +0000766 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +0000767 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000768}
769
Dan Gohman54a187e2007-08-20 19:28:38 +0000770/// ListScheduleTopDown - The main loop of list scheduling for top-down
771/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +0000772void ScheduleDAGRRList::ListScheduleTopDown() {
773 unsigned CurCycle = 0;
Evan Cheng5924bf72007-09-25 01:54:36 +0000774 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000775
776 // All leaves to Available queue.
777 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
778 // It is available if it has no predecessors.
779 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
780 AvailableQueue->push(&SUnits[i]);
781 SUnits[i].isAvailable = true;
782 }
783 }
784
785 // Emit the entry node first.
786 ScheduleNodeTopDown(Entry, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000787 Sequence.push_back(Entry);
788 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000789
790 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000791 // priority. If it is not ready put it back. Schedule the node.
Evan Chengd38c22b2006-05-11 23:55:42 +0000792 std::vector<SUnit*> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000793 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000794 SUnit *CurSU = AvailableQueue->pop();
795 while (CurSU && CurSU->CycleBound > CurCycle) {
796 NotReady.push_back(CurSU);
797 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000798 }
799
800 // Add the nodes that aren't ready back onto the available list.
801 AvailableQueue->push_all(NotReady);
802 NotReady.clear();
803
Evan Cheng5924bf72007-09-25 01:54:36 +0000804 if (!CurSU)
805 Sequence.push_back(0);
806 else {
807 ScheduleNodeTopDown(CurSU, CurCycle);
808 Sequence.push_back(CurSU);
809 }
Evan Chengd12c97d2006-05-30 18:05:39 +0000810 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000811 }
812
813
814#ifndef NDEBUG
815 // Verify that all SUnits were scheduled.
816 bool AnyNotSched = false;
817 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
818 if (!SUnits[i].isScheduled) {
819 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000820 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000821 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000822 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000823 AnyNotSched = true;
824 }
825 }
826 assert(!AnyNotSched);
827#endif
828}
829
830
831
832//===----------------------------------------------------------------------===//
833// RegReductionPriorityQueue Implementation
834//===----------------------------------------------------------------------===//
835//
836// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
837// to reduce register pressure.
838//
839namespace {
840 template<class SF>
841 class RegReductionPriorityQueue;
842
843 /// Sorting functions for the Available queue.
844 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
845 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
846 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
847 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
848
849 bool operator()(const SUnit* left, const SUnit* right) const;
850 };
851
852 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
853 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
854 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
855 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
856
857 bool operator()(const SUnit* left, const SUnit* right) const;
858 };
859} // end anonymous namespace
860
Evan Cheng961bbd32007-01-08 23:50:38 +0000861static inline bool isCopyFromLiveIn(const SUnit *SU) {
862 SDNode *N = SU->Node;
Evan Cheng8e136a92007-09-26 21:36:17 +0000863 return N && N->getOpcode() == ISD::CopyFromReg &&
Evan Cheng961bbd32007-01-08 23:50:38 +0000864 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
865}
866
Evan Chengd38c22b2006-05-11 23:55:42 +0000867namespace {
868 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000869 class VISIBILITY_HIDDEN RegReductionPriorityQueue
870 : public SchedulingPriorityQueue {
Evan Chengd38c22b2006-05-11 23:55:42 +0000871 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
872
873 public:
874 RegReductionPriorityQueue() :
875 Queue(SF(this)) {}
876
Evan Cheng5924bf72007-09-25 01:54:36 +0000877 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000878 std::vector<SUnit> &sunits) {}
Evan Cheng5924bf72007-09-25 01:54:36 +0000879
880 virtual void addNode(const SUnit *SU) {}
881
882 virtual void updateNode(const SUnit *SU) {}
883
Evan Chengd38c22b2006-05-11 23:55:42 +0000884 virtual void releaseState() {}
885
Evan Cheng6730f032007-01-08 23:55:53 +0000886 virtual unsigned getNodePriority(const SUnit *SU) const {
Evan Chengd38c22b2006-05-11 23:55:42 +0000887 return 0;
888 }
889
Evan Cheng5924bf72007-09-25 01:54:36 +0000890 unsigned size() const { return Queue.size(); }
891
Evan Chengd38c22b2006-05-11 23:55:42 +0000892 bool empty() const { return Queue.empty(); }
893
894 void push(SUnit *U) {
895 Queue.push(U);
896 }
897 void push_all(const std::vector<SUnit *> &Nodes) {
898 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
899 Queue.push(Nodes[i]);
900 }
901
902 SUnit *pop() {
Evan Chengd12c97d2006-05-30 18:05:39 +0000903 if (empty()) return NULL;
Evan Chengd38c22b2006-05-11 23:55:42 +0000904 SUnit *V = Queue.top();
905 Queue.pop();
906 return V;
907 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000908
Evan Cheng5924bf72007-09-25 01:54:36 +0000909 /// remove - This is a really inefficient way to remove a node from a
910 /// priority queue. We should roll our own heap to make this better or
911 /// something.
912 void remove(SUnit *SU) {
913 std::vector<SUnit*> Temp;
914
915 assert(!Queue.empty() && "Not in queue!");
916 while (Queue.top() != SU) {
917 Temp.push_back(Queue.top());
918 Queue.pop();
919 assert(!Queue.empty() && "Not in queue!");
920 }
921
922 // Remove the node from the PQ.
923 Queue.pop();
924
925 // Add all the other nodes back.
926 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
927 Queue.push(Temp[i]);
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000928 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000929 };
930
931 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000932 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
933 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +0000934 // SUnitMap SDNode to SUnit mapping (n -> n).
935 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000936
Evan Chengd38c22b2006-05-11 23:55:42 +0000937 // SUnits - The SUnits for the current graph.
938 const std::vector<SUnit> *SUnits;
939
940 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +0000941 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +0000942
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000943 const TargetInstrInfo *TII;
Evan Chengd38c22b2006-05-11 23:55:42 +0000944 public:
Dan Gohman54a187e2007-08-20 19:28:38 +0000945 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000946 : TII(tii) {}
Evan Chengd38c22b2006-05-11 23:55:42 +0000947
Evan Cheng5924bf72007-09-25 01:54:36 +0000948 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000949 std::vector<SUnit> &sunits) {
950 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +0000951 SUnits = &sunits;
952 // Add pseudo dependency edges for two-address nodes.
Evan Chengafed73e2006-05-12 01:58:24 +0000953 AddPseudoTwoAddrDeps();
Evan Chengd38c22b2006-05-11 23:55:42 +0000954 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +0000955 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +0000956 }
957
Evan Cheng5924bf72007-09-25 01:54:36 +0000958 void addNode(const SUnit *SU) {
959 SethiUllmanNumbers.resize(SUnits->size(), 0);
960 CalcNodeSethiUllmanNumber(SU);
961 }
962
963 void updateNode(const SUnit *SU) {
964 SethiUllmanNumbers[SU->NodeNum] = 0;
965 CalcNodeSethiUllmanNumber(SU);
966 }
967
Evan Chengd38c22b2006-05-11 23:55:42 +0000968 void releaseState() {
969 SUnits = 0;
970 SethiUllmanNumbers.clear();
971 }
972
Evan Cheng6730f032007-01-08 23:55:53 +0000973 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +0000974 assert(SU->NodeNum < SethiUllmanNumbers.size());
Evan Cheng8e136a92007-09-26 21:36:17 +0000975 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Cheng961bbd32007-01-08 23:50:38 +0000976 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
977 // CopyFromReg should be close to its def because it restricts
978 // allocation choices. But if it is a livein then perhaps we want it
979 // closer to its uses so it can be coalesced.
980 return 0xffff;
981 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
982 // CopyToReg should be close to its uses to facilitate coalescing and
983 // avoid spilling.
984 return 0;
985 else if (SU->NumSuccs == 0)
986 // If SU does not have a use, i.e. it doesn't produce a value that would
987 // be consumed (e.g. store), then it terminates a chain of computation.
988 // Give it a large SethiUllman number so it will be scheduled right
989 // before its predecessors that it doesn't lengthen their live ranges.
990 return 0xffff;
991 else if (SU->NumPreds == 0)
992 // If SU does not have a def, schedule it close to its uses because it
993 // does not lengthen any live ranges.
994 return 0;
995 else
996 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +0000997 }
998
999 private:
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001000 bool canClobber(SUnit *SU, SUnit *Op);
Evan Chengd38c22b2006-05-11 23:55:42 +00001001 void AddPseudoTwoAddrDeps();
Evan Cheng6730f032007-01-08 23:55:53 +00001002 void CalculateSethiUllmanNumbers();
1003 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001004 };
1005
1006
1007 template<class SF>
Dan Gohman54a187e2007-08-20 19:28:38 +00001008 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1009 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +00001010 // SUnitMap SDNode to SUnit mapping (n -> n).
1011 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001012
Evan Chengd38c22b2006-05-11 23:55:42 +00001013 // SUnits - The SUnits for the current graph.
1014 const std::vector<SUnit> *SUnits;
1015
1016 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001017 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001018
1019 public:
1020 TDRegReductionPriorityQueue() {}
1021
Evan Cheng5924bf72007-09-25 01:54:36 +00001022 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001023 std::vector<SUnit> &sunits) {
1024 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +00001025 SUnits = &sunits;
1026 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001027 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001028 }
1029
Evan Cheng5924bf72007-09-25 01:54:36 +00001030 void addNode(const SUnit *SU) {
1031 SethiUllmanNumbers.resize(SUnits->size(), 0);
1032 CalcNodeSethiUllmanNumber(SU);
1033 }
1034
1035 void updateNode(const SUnit *SU) {
1036 SethiUllmanNumbers[SU->NodeNum] = 0;
1037 CalcNodeSethiUllmanNumber(SU);
1038 }
1039
Evan Chengd38c22b2006-05-11 23:55:42 +00001040 void releaseState() {
1041 SUnits = 0;
1042 SethiUllmanNumbers.clear();
1043 }
1044
Evan Cheng6730f032007-01-08 23:55:53 +00001045 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001046 assert(SU->NodeNum < SethiUllmanNumbers.size());
1047 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001048 }
1049
1050 private:
Evan Cheng6730f032007-01-08 23:55:53 +00001051 void CalculateSethiUllmanNumbers();
1052 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001053 };
1054}
1055
Evan Chengb9e3db62007-03-14 22:43:40 +00001056/// closestSucc - Returns the scheduled cycle of the successor which is
1057/// closet to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001058static unsigned closestSucc(const SUnit *SU) {
1059 unsigned MaxCycle = 0;
1060 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001061 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001062 unsigned Cycle = I->Dep->Cycle;
Evan Chengb9e3db62007-03-14 22:43:40 +00001063 // If there are bunch of CopyToRegs stacked up, they should be considered
1064 // to be at the same position.
Evan Cheng8e136a92007-09-26 21:36:17 +00001065 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
Evan Cheng0effc3a2007-09-19 01:38:40 +00001066 Cycle = closestSucc(I->Dep)+1;
Evan Chengb9e3db62007-03-14 22:43:40 +00001067 if (Cycle > MaxCycle)
1068 MaxCycle = Cycle;
1069 }
Evan Cheng28748552007-03-13 23:25:11 +00001070 return MaxCycle;
1071}
1072
Evan Chengb9e3db62007-03-14 22:43:40 +00001073/// calcMaxScratches - Returns an cost estimate of the worse case requirement
1074/// for scratch registers. Live-in operands and live-out results don't count
1075/// since they are "fixed".
1076static unsigned calcMaxScratches(const SUnit *SU) {
1077 unsigned Scratches = 0;
1078 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1079 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001080 if (I->isCtrl) continue; // ignore chain preds
Evan Cheng8e136a92007-09-26 21:36:17 +00001081 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
Evan Chengb9e3db62007-03-14 22:43:40 +00001082 Scratches++;
1083 }
1084 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1085 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001086 if (I->isCtrl) continue; // ignore chain succs
Evan Cheng8e136a92007-09-26 21:36:17 +00001087 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
Evan Chengb9e3db62007-03-14 22:43:40 +00001088 Scratches += 10;
1089 }
1090 return Scratches;
1091}
1092
Evan Chengd38c22b2006-05-11 23:55:42 +00001093// Bottom up
1094bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
David Greene4c1e6f32007-06-29 03:42:23 +00001095 // There used to be a special tie breaker here that looked for
David Greene5b6f7552007-06-29 02:48:09 +00001096 // two-address instructions and preferred the instruction with a
1097 // def&use operand. The special case triggered diagnostics when
1098 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1099 // ordering that priority_queue requires. It didn't help much anyway
1100 // because AddPseudoTwoAddrDeps already covers many of the cases
1101 // where it would have applied. In addition, it's counter-intuitive
1102 // that a tie breaker would be the first thing attempted. There's a
1103 // "real" tie breaker below that is the operation of last resort.
1104 // The fact that the "special tie breaker" would trigger when there
1105 // wasn't otherwise a tie is what broke the strict weak ordering
1106 // constraint.
Evan Cheng99f2f792006-05-13 08:22:24 +00001107
Evan Cheng6730f032007-01-08 23:55:53 +00001108 unsigned LPriority = SPQ->getNodePriority(left);
1109 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng961bbd32007-01-08 23:50:38 +00001110 if (LPriority > RPriority)
Evan Chengd38c22b2006-05-11 23:55:42 +00001111 return true;
Evan Cheng28748552007-03-13 23:25:11 +00001112 else if (LPriority == RPriority) {
Dan Gohmane131e3a2007-04-26 19:40:56 +00001113 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
Evan Cheng28748552007-03-13 23:25:11 +00001114 // e.g.
1115 // t1 = op t2, c1
1116 // t3 = op t4, c2
1117 //
1118 // and the following instructions are both ready.
1119 // t2 = op c3
1120 // t4 = op c4
1121 //
1122 // Then schedule t2 = op first.
1123 // i.e.
1124 // t4 = op c4
1125 // t2 = op c3
1126 // t1 = op t2, c1
1127 // t3 = op t4, c2
1128 //
1129 // This creates more short live intervals.
1130 unsigned LDist = closestSucc(left);
1131 unsigned RDist = closestSucc(right);
1132 if (LDist < RDist)
Evan Chengd38c22b2006-05-11 23:55:42 +00001133 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001134 else if (LDist == RDist) {
1135 // Intuitively, it's good to push down instructions whose results are
1136 // liveout so their long live ranges won't conflict with other values
1137 // which are needed inside the BB. Further prioritize liveout instructions
1138 // by the number of operands which are calculated within the BB.
1139 unsigned LScratch = calcMaxScratches(left);
1140 unsigned RScratch = calcMaxScratches(right);
1141 if (LScratch > RScratch)
Evan Chengd38c22b2006-05-11 23:55:42 +00001142 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001143 else if (LScratch == RScratch)
1144 if (left->Height > right->Height)
Evan Cheng99f2f792006-05-13 08:22:24 +00001145 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001146 else if (left->Height == right->Height)
1147 if (left->Depth < right->Depth)
Evan Cheng28748552007-03-13 23:25:11 +00001148 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001149 else if (left->Depth == right->Depth)
1150 if (left->CycleBound > right->CycleBound)
1151 return true;
1152 }
Evan Cheng28748552007-03-13 23:25:11 +00001153 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001154 return false;
1155}
1156
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001157template<class SF>
1158bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
1159 if (SU->isTwoAddress) {
1160 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001161 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001162 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
1163 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001164 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001165 SDNode *DU = SU->Node->getOperand(i).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001166 if (Op == (*SUnitMap)[DU][SU->InstanceNo])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001167 return true;
1168 }
1169 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001170 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001171 return false;
1172}
1173
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001174
Evan Chengd38c22b2006-05-11 23:55:42 +00001175/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1176/// it as a def&use operand. Add a pseudo control edge from it to the other
1177/// node (if it won't create a cycle) so the two-address one will be scheduled
1178/// first (lower in the schedule).
1179template<class SF>
1180void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001181 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1182 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1183 if (!SU->isTwoAddress)
1184 continue;
1185
1186 SDNode *Node = SU->Node;
Evan Cheng8e136a92007-09-26 21:36:17 +00001187 if (!Node || !Node->isTargetOpcode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001188 continue;
1189
1190 unsigned Opc = Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001191 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001192 unsigned NumOps = ScheduleDAG::CountOperands(Node);
1193 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001194 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001195 SDNode *DU = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001196 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
Evan Chengf24d15f2006-11-06 21:33:46 +00001197 if (!DUSU) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001198 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1199 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001200 if (I->isCtrl) continue;
1201 SUnit *SuccSU = I->Dep;
Evan Cheng5924bf72007-09-25 01:54:36 +00001202 // Don't constraint nodes with implicit defs. It can create cycles
1203 // plus it may increase register pressures.
1204 if (SuccSU == SU || SuccSU->hasImplicitDefs)
1205 continue;
1206 // Be conservative. Ignore if nodes aren't at the same depth.
1207 if (SuccSU->Depth != SU->Depth)
1208 continue;
1209 if ((!canClobber(SuccSU, DUSU) ||
1210 (!SU->isCommutable && SuccSU->isCommutable)) &&
1211 !isReachable(SuccSU, SU)) {
1212 DOUT << "Adding an edge from SU # " << SU->NodeNum
1213 << " to SU #" << SuccSU->NodeNum << "\n";
1214 SU->addPred(SuccSU, true, true);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001215 }
1216 }
1217 }
1218 }
1219 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001220}
1221
Evan Cheng6730f032007-01-08 23:55:53 +00001222/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001223/// Smaller number is the higher priority.
1224template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001225unsigned BURegReductionPriorityQueue<SF>::
1226CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001227 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001228 if (SethiUllmanNumber != 0)
1229 return SethiUllmanNumber;
1230
Evan Cheng961bbd32007-01-08 23:50:38 +00001231 unsigned Extra = 0;
1232 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1233 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001234 if (I->isCtrl) continue; // ignore chain preds
1235 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001236 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Cheng961bbd32007-01-08 23:50:38 +00001237 if (PredSethiUllman > SethiUllmanNumber) {
1238 SethiUllmanNumber = PredSethiUllman;
1239 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001240 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001241 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001242 }
Evan Cheng961bbd32007-01-08 23:50:38 +00001243
1244 SethiUllmanNumber += Extra;
1245
1246 if (SethiUllmanNumber == 0)
1247 SethiUllmanNumber = 1;
Evan Chengd38c22b2006-05-11 23:55:42 +00001248
1249 return SethiUllmanNumber;
1250}
1251
Evan Cheng6730f032007-01-08 23:55:53 +00001252/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1253/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001254template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001255void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001256 SethiUllmanNumbers.assign(SUnits->size(), 0);
1257
1258 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001259 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001260}
1261
1262static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1263 unsigned Sum = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001264 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1265 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001266 SUnit *SuccSU = I->Dep;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001267 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1268 EE = SuccSU->Preds.end(); II != EE; ++II) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001269 SUnit *PredSU = II->Dep;
Evan Chengd38c22b2006-05-11 23:55:42 +00001270 if (!PredSU->isScheduled)
Evan Cheng5924bf72007-09-25 01:54:36 +00001271 ++Sum;
Evan Chengd38c22b2006-05-11 23:55:42 +00001272 }
1273 }
1274
1275 return Sum;
1276}
1277
1278
1279// Top down
1280bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00001281 unsigned LPriority = SPQ->getNodePriority(left);
1282 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng8e136a92007-09-26 21:36:17 +00001283 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1284 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00001285 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1286 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1287 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1288 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1289
1290 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1291 return false;
1292 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1293 return true;
1294
1295 // Special tie breaker: if two nodes share a operand, the one that use it
1296 // as a def&use operand is preferred.
1297 if (LIsTarget && RIsTarget) {
1298 if (left->isTwoAddress && !right->isTwoAddress) {
1299 SDNode *DUNode = left->Node->getOperand(0).Val;
1300 if (DUNode->isOperand(right->Node))
1301 RBonus += 2;
1302 }
1303 if (!left->isTwoAddress && right->isTwoAddress) {
1304 SDNode *DUNode = right->Node->getOperand(0).Val;
1305 if (DUNode->isOperand(left->Node))
1306 LBonus += 2;
1307 }
1308 }
1309 if (LIsFloater)
1310 LBonus -= 2;
1311 if (RIsFloater)
1312 RBonus -= 2;
1313 if (left->NumSuccs == 1)
1314 LBonus += 2;
1315 if (right->NumSuccs == 1)
1316 RBonus += 2;
1317
1318 if (LPriority+LBonus < RPriority+RBonus)
1319 return true;
1320 else if (LPriority == RPriority)
1321 if (left->Depth < right->Depth)
1322 return true;
1323 else if (left->Depth == right->Depth)
1324 if (left->NumSuccsLeft > right->NumSuccsLeft)
1325 return true;
1326 else if (left->NumSuccsLeft == right->NumSuccsLeft)
1327 if (left->CycleBound > right->CycleBound)
1328 return true;
1329 return false;
1330}
1331
Evan Cheng6730f032007-01-08 23:55:53 +00001332/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001333/// Smaller number is the higher priority.
1334template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001335unsigned TDRegReductionPriorityQueue<SF>::
1336CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001337 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001338 if (SethiUllmanNumber != 0)
1339 return SethiUllmanNumber;
1340
Evan Cheng8e136a92007-09-26 21:36:17 +00001341 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001342 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Evan Cheng961bbd32007-01-08 23:50:38 +00001343 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001344 else if (SU->NumSuccsLeft == 0)
1345 // If SU does not have a use, i.e. it doesn't produce a value that would
1346 // be consumed (e.g. store), then it terminates a chain of computation.
Chris Lattner296a83c2007-02-01 04:55:59 +00001347 // Give it a small SethiUllman number so it will be scheduled right before
1348 // its predecessors that it doesn't lengthen their live ranges.
Evan Cheng961bbd32007-01-08 23:50:38 +00001349 SethiUllmanNumber = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001350 else if (SU->NumPredsLeft == 0 &&
1351 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
Evan Cheng961bbd32007-01-08 23:50:38 +00001352 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001353 else {
1354 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001355 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1356 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001357 if (I->isCtrl) continue; // ignore chain preds
1358 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001359 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001360 if (PredSethiUllman > SethiUllmanNumber) {
1361 SethiUllmanNumber = PredSethiUllman;
1362 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001363 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001364 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001365 }
1366
1367 SethiUllmanNumber += Extra;
1368 }
1369
1370 return SethiUllmanNumber;
1371}
1372
Evan Cheng6730f032007-01-08 23:55:53 +00001373/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1374/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001375template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001376void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001377 SethiUllmanNumbers.assign(SUnits->size(), 0);
1378
1379 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001380 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001381}
1382
1383//===----------------------------------------------------------------------===//
1384// Public Constructor Functions
1385//===----------------------------------------------------------------------===//
1386
Jim Laskey03593f72006-08-01 18:29:48 +00001387llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1388 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001389 MachineBasicBlock *BB) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001390 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
Jim Laskey95eda5b2006-08-01 14:21:23 +00001391 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001392 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
Evan Chengd38c22b2006-05-11 23:55:42 +00001393}
1394
Jim Laskey03593f72006-08-01 18:29:48 +00001395llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1396 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001397 MachineBasicBlock *BB) {
Jim Laskey95eda5b2006-08-01 14:21:23 +00001398 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
Chris Lattner296a83c2007-02-01 04:55:59 +00001399 new TDRegReductionPriorityQueue<td_ls_rr_sort>());
Evan Chengd38c22b2006-05-11 23:55:42 +00001400}
1401