blob: ff751a944413459ff6bc864e3339467fe3a76f56 [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 Chenge6f92252007-09-27 18:46:06 +000028#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000029#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000030#include "llvm/ADT/Statistic.h"
31#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000032#include <queue>
33#include "llvm/Support/CommandLine.h"
34using namespace llvm;
35
Evan Cheng1ec79b42007-09-27 07:09:03 +000036STATISTIC(NumBacktracks, "Number of times scheduler backtraced");
37STATISTIC(NumDups, "Number of duplicated nodes");
38STATISTIC(NumCCCopies, "Number of cross class copies");
39
Jim Laskey95eda5b2006-08-01 14:21:23 +000040static RegisterScheduler
41 burrListDAGScheduler("list-burr",
42 " Bottom-up register reduction list scheduling",
43 createBURRListDAGScheduler);
44static RegisterScheduler
45 tdrListrDAGScheduler("list-tdrr",
46 " Top-down register reduction list scheduling",
47 createTDRRListDAGScheduler);
48
Evan Chengd38c22b2006-05-11 23:55:42 +000049namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000050//===----------------------------------------------------------------------===//
51/// ScheduleDAGRRList - The actual register reduction list scheduler
52/// implementation. This supports both top-down and bottom-up scheduling.
53///
Chris Lattnere097e6f2006-06-28 22:17:39 +000054class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
Evan Chengd38c22b2006-05-11 23:55:42 +000055private:
56 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
57 /// it is top-down.
58 bool isBottomUp;
59
60 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Cheng5924bf72007-09-25 01:54:36 +000061 ///a
Evan Chengd38c22b2006-05-11 23:55:42 +000062 SchedulingPriorityQueue *AvailableQueue;
63
Evan Cheng5924bf72007-09-25 01:54:36 +000064 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
65 /// that are "live". These nodes must be scheduled before any other nodes that
66 /// modifies the registers can be scheduled.
67 SmallSet<unsigned, 4> LiveRegs;
68 std::vector<SUnit*> LiveRegDefs;
69 std::vector<unsigned> LiveRegCycles;
70
Evan Chengd38c22b2006-05-11 23:55:42 +000071public:
72 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
73 const TargetMachine &tm, bool isbottomup,
74 SchedulingPriorityQueue *availqueue)
75 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
76 AvailableQueue(availqueue) {
77 }
78
79 ~ScheduleDAGRRList() {
80 delete AvailableQueue;
81 }
82
83 void Schedule();
84
85private:
Evan Cheng8e136a92007-09-26 21:36:17 +000086 void ReleasePred(SUnit*, bool, unsigned);
87 void ReleaseSucc(SUnit*, bool isChain, unsigned);
88 void CapturePred(SUnit*, SUnit*, bool);
89 void ScheduleNodeBottomUp(SUnit*, unsigned);
90 void ScheduleNodeTopDown(SUnit*, unsigned);
91 void UnscheduleNodeBottomUp(SUnit*);
92 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
93 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Cheng1ec79b42007-09-27 07:09:03 +000094 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
Evan Cheng8e136a92007-09-26 21:36:17 +000095 const TargetRegisterClass*,
Evan Cheng1ec79b42007-09-27 07:09:03 +000096 const TargetRegisterClass*,
97 SmallVector<SUnit*, 2>&);
98 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Evan Chengd38c22b2006-05-11 23:55:42 +000099 void ListScheduleTopDown();
100 void ListScheduleBottomUp();
Evan Chengafed73e2006-05-12 01:58:24 +0000101 void CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000102};
103} // end anonymous namespace
104
105
106/// Schedule - Schedule the DAG using list scheduling.
107void ScheduleDAGRRList::Schedule() {
Bill Wendling22e978a2006-12-07 20:04:42 +0000108 DOUT << "********** List Scheduling **********\n";
Evan Cheng5924bf72007-09-25 01:54:36 +0000109
110 LiveRegDefs.resize(MRI->getNumRegs(), NULL);
111 LiveRegCycles.resize(MRI->getNumRegs(), 0);
112
Evan Chengd38c22b2006-05-11 23:55:42 +0000113 // Build scheduling units.
114 BuildSchedUnits();
115
Evan Chengd38c22b2006-05-11 23:55:42 +0000116 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Chris Lattnerd86418a2006-08-17 00:09:56 +0000117 SUnits[su].dumpAll(&DAG));
Evan Cheng47fbeda2006-10-14 08:34:06 +0000118 CalculateDepths();
119 CalculateHeights();
Evan Chengd38c22b2006-05-11 23:55:42 +0000120
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000121 AvailableQueue->initNodes(SUnitMap, SUnits);
Dan Gohman54a187e2007-08-20 19:28:38 +0000122
Evan Chengd38c22b2006-05-11 23:55:42 +0000123 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
124 if (isBottomUp)
125 ListScheduleBottomUp();
126 else
127 ListScheduleTopDown();
128
129 AvailableQueue->releaseState();
Dan Gohman54a187e2007-08-20 19:28:38 +0000130
Evan Cheng009f5f52006-05-25 08:37:31 +0000131 CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000132
Bill Wendling22e978a2006-12-07 20:04:42 +0000133 DOUT << "*** Final schedule ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000134 DEBUG(dumpSchedule());
Bill Wendling22e978a2006-12-07 20:04:42 +0000135 DOUT << "\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000136
137 // Emit in scheduled order
138 EmitSchedule();
139}
140
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000141/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
Evan Chengafed73e2006-05-12 01:58:24 +0000142/// it is not the last use of its first operand, add it to the CommuteSet if
143/// possible. It will be commuted when it is translated to a MI.
144void ScheduleDAGRRList::CommuteNodesToReducePressure() {
Evan Chenge3c44192007-06-22 01:35:51 +0000145 SmallPtrSet<SUnit*, 4> OperandSeen;
Evan Chengafed73e2006-05-12 01:58:24 +0000146 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
147 SUnit *SU = Sequence[i];
Evan Cheng8e136a92007-09-26 21:36:17 +0000148 if (!SU || !SU->Node) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000149 if (SU->isCommutable) {
150 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +0000151 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000152 unsigned NumOps = CountOperands(SU->Node);
153 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000154 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000155 continue;
156
157 SDNode *OpN = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000158 SUnit *OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000159 if (OpSU && OperandSeen.count(OpSU) == 1) {
160 // Ok, so SU is not the last use of OpSU, but SU is two-address so
161 // it will clobber OpSU. Try to commute SU if no other source operands
162 // are live below.
163 bool DoCommute = true;
164 for (unsigned k = 0; k < NumOps; ++k) {
165 if (k != j) {
166 OpN = SU->Node->getOperand(k).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000167 OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000168 if (OpSU && OperandSeen.count(OpSU) == 1) {
169 DoCommute = false;
170 break;
171 }
172 }
Evan Chengafed73e2006-05-12 01:58:24 +0000173 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000174 if (DoCommute)
175 CommuteSet.insert(SU->Node);
Evan Chengafed73e2006-05-12 01:58:24 +0000176 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000177
178 // Only look at the first use&def node for now.
179 break;
Evan Chengafed73e2006-05-12 01:58:24 +0000180 }
181 }
182
Chris Lattnerd86418a2006-08-17 00:09:56 +0000183 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
184 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000185 if (!I->isCtrl)
186 OperandSeen.insert(I->Dep);
Evan Chengafed73e2006-05-12 01:58:24 +0000187 }
188 }
189}
Evan Chengd38c22b2006-05-11 23:55:42 +0000190
191//===----------------------------------------------------------------------===//
192// Bottom-Up Scheduling
193//===----------------------------------------------------------------------===//
194
Evan Chengd38c22b2006-05-11 23:55:42 +0000195/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000196/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000197void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
198 unsigned CurCycle) {
199 // FIXME: the distance between two nodes is not always == the predecessor's
200 // latency. For example, the reader can very well read the register written
201 // by the predecessor later than the issue cycle. It also depends on the
202 // interrupt model (drain vs. freeze).
203 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
204
Evan Cheng038dcc52007-09-28 19:24:24 +0000205 --PredSU->NumSuccsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000206
207#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +0000208 if (PredSU->NumSuccsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000209 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000210 PredSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000211 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000212 assert(0);
213 }
214#endif
215
Evan Cheng038dcc52007-09-28 19:24:24 +0000216 if (PredSU->NumSuccsLeft == 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000217 // EntryToken has to go last! Special case it here.
Evan Cheng8e136a92007-09-26 21:36:17 +0000218 if (!PredSU->Node || PredSU->Node->getOpcode() != ISD::EntryToken) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000219 PredSU->isAvailable = true;
220 AvailableQueue->push(PredSU);
221 }
222 }
223}
224
225/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
226/// count of its predecessors. If a predecessor pending count is zero, add it to
227/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000228void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000229 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000230 DEBUG(SU->dump(&DAG));
231 SU->Cycle = CurCycle;
232
233 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000234
235 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000236 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000237 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000238 ReleasePred(I->Dep, I->isCtrl, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000239 if (I->Cost < 0) {
240 // This is a physical register dependency and it's impossible or
241 // expensive to copy the register. Make sure nothing that can
242 // clobber the register is scheduled between the predecessor and
243 // this node.
244 if (LiveRegs.insert(I->Reg)) {
245 LiveRegDefs[I->Reg] = I->Dep;
246 LiveRegCycles[I->Reg] = CurCycle;
247 }
248 }
249 }
250
251 // Release all the implicit physical register defs that are live.
252 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
253 I != E; ++I) {
254 if (I->Cost < 0) {
255 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
256 LiveRegs.erase(I->Reg);
257 assert(LiveRegDefs[I->Reg] == SU &&
258 "Physical register dependency violated?");
259 LiveRegDefs[I->Reg] = NULL;
260 LiveRegCycles[I->Reg] = 0;
261 }
262 }
263 }
264
Evan Chengd38c22b2006-05-11 23:55:42 +0000265 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000266}
267
Evan Cheng5924bf72007-09-25 01:54:36 +0000268/// CapturePred - This does the opposite of ReleasePred. Since SU is being
269/// unscheduled, incrcease the succ left count of its predecessors. Remove
270/// them from AvailableQueue if necessary.
271void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
272 PredSU->CycleBound = 0;
273 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
274 I != E; ++I) {
275 if (I->Dep == SU)
276 continue;
277 PredSU->CycleBound = std::max(PredSU->CycleBound,
278 I->Dep->Cycle + PredSU->Latency);
279 }
280
281 if (PredSU->isAvailable) {
282 PredSU->isAvailable = false;
283 if (!PredSU->isPending)
284 AvailableQueue->remove(PredSU);
285 }
286
Evan Cheng038dcc52007-09-28 19:24:24 +0000287 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000288}
289
290/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
291/// its predecessor states to reflect the change.
292void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
293 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
294 DEBUG(SU->dump(&DAG));
295
296 AvailableQueue->UnscheduledNode(SU);
297
298 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
299 I != E; ++I) {
300 CapturePred(I->Dep, SU, I->isCtrl);
301 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
302 LiveRegs.erase(I->Reg);
303 assert(LiveRegDefs[I->Reg] == I->Dep &&
304 "Physical register dependency violated?");
305 LiveRegDefs[I->Reg] = NULL;
306 LiveRegCycles[I->Reg] = 0;
307 }
308 }
309
310 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
311 I != E; ++I) {
312 if (I->Cost < 0) {
313 if (LiveRegs.insert(I->Reg)) {
314 assert(!LiveRegDefs[I->Reg] &&
315 "Physical register dependency violated?");
316 LiveRegDefs[I->Reg] = SU;
317 }
318 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
319 LiveRegCycles[I->Reg] = I->Dep->Cycle;
320 }
321 }
322
323 SU->Cycle = 0;
324 SU->isScheduled = false;
325 SU->isAvailable = true;
326 AvailableQueue->push(SU);
327}
328
Evan Chengcfd5f822007-09-27 00:25:29 +0000329// FIXME: This is probably too slow!
330static void isReachable(SUnit *SU, SUnit *TargetSU,
331 SmallPtrSet<SUnit*, 32> &Visited, bool &Reached) {
332 if (Reached) return;
333 if (SU == TargetSU) {
334 Reached = true;
335 return;
336 }
337 if (!Visited.insert(SU)) return;
338
339 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
340 ++I)
341 isReachable(I->Dep, TargetSU, Visited, Reached);
342}
343
344static bool isReachable(SUnit *SU, SUnit *TargetSU) {
345 SmallPtrSet<SUnit*, 32> Visited;
346 bool Reached = false;
347 isReachable(SU, TargetSU, Visited, Reached);
348 return Reached;
349}
350
351/// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
352/// create a cycle.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000353static bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
Evan Chengcfd5f822007-09-27 00:25:29 +0000354 if (isReachable(TargetSU, SU))
355 return true;
356 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
357 I != E; ++I)
358 if (I->Cost < 0 && isReachable(TargetSU, I->Dep))
359 return true;
360 return false;
361}
362
Evan Cheng8e136a92007-09-26 21:36:17 +0000363/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Evan Cheng5924bf72007-09-25 01:54:36 +0000364/// BTCycle in order to schedule a specific node. Returns the last unscheduled
365/// SUnit. Also returns if a successor is unscheduled in the process.
Evan Cheng8e136a92007-09-26 21:36:17 +0000366void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
367 unsigned &CurCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000368 SUnit *OldSU = NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000369 while (CurCycle > BtCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000370 OldSU = Sequence.back();
371 Sequence.pop_back();
372 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000373 // Don't try to remove SU from AvailableQueue.
374 SU->isAvailable = false;
Evan Cheng5924bf72007-09-25 01:54:36 +0000375 UnscheduleNodeBottomUp(OldSU);
376 --CurCycle;
377 }
378
379
380 if (SU->isSucc(OldSU)) {
381 assert(false && "Something is wrong!");
382 abort();
383 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000384
385 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000386}
387
388/// isSafeToCopy - True if the SUnit for the given SDNode can safely cloned,
389/// i.e. the node does not produce a flag, it does not read a flag and it does
390/// not have an incoming chain.
391static bool isSafeToCopy(SDNode *N) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000392 if (!N)
393 return true;
394
Evan Cheng5924bf72007-09-25 01:54:36 +0000395 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
396 if (N->getValueType(i) == MVT::Flag)
397 return false;
398 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
399 const SDOperand &Op = N->getOperand(i);
400 MVT::ValueType VT = Op.Val->getValueType(Op.ResNo);
401 if (VT == MVT::Other || VT == MVT::Flag)
402 return false;
403 }
404
405 return true;
406}
407
408/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
409/// successors to the newly created node.
410SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000411 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
412
Evan Cheng5924bf72007-09-25 01:54:36 +0000413 SUnit *NewSU = Clone(SU);
414
415 // New SUnit has the exact same predecessors.
416 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
417 I != E; ++I)
418 if (!I->isSpecial) {
419 NewSU->addPred(I->Dep, I->isCtrl, false, I->Reg, I->Cost);
420 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
421 }
422
423 // Only copy scheduled successors. Cut them from old node's successor
424 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000425 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000426 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
427 I != E; ++I) {
428 if (I->isSpecial)
429 continue;
Evan Cheng5924bf72007-09-25 01:54:36 +0000430 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000431 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
Evan Cheng5924bf72007-09-25 01:54:36 +0000432 I->Dep->addPred(NewSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000433 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng5924bf72007-09-25 01:54:36 +0000434 }
435 }
436 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000437 SUnit *Succ = DelDeps[i].first;
438 bool isCtrl = DelDeps[i].second;
Evan Cheng5924bf72007-09-25 01:54:36 +0000439 Succ->removePred(SU, isCtrl, false);
440 }
441
442 AvailableQueue->updateNode(SU);
443 AvailableQueue->addNode(NewSU);
444
Evan Cheng1ec79b42007-09-27 07:09:03 +0000445 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000446 return NewSU;
447}
448
Evan Cheng1ec79b42007-09-27 07:09:03 +0000449/// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
450/// and move all scheduled successors of the given SUnit to the last copy.
451void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
452 const TargetRegisterClass *DestRC,
453 const TargetRegisterClass *SrcRC,
454 SmallVector<SUnit*, 2> &Copies) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000455 SUnit *CopyFromSU = NewSUnit(NULL);
456 CopyFromSU->CopySrcRC = SrcRC;
457 CopyFromSU->CopyDstRC = DestRC;
458 CopyFromSU->Depth = SU->Depth;
459 CopyFromSU->Height = SU->Height;
460
461 SUnit *CopyToSU = NewSUnit(NULL);
462 CopyToSU->CopySrcRC = DestRC;
463 CopyToSU->CopyDstRC = SrcRC;
464
465 // Only copy scheduled successors. Cut them from old node's successor
466 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000467 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000468 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
469 I != E; ++I) {
470 if (I->isSpecial)
471 continue;
Evan Cheng8e136a92007-09-26 21:36:17 +0000472 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000473 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
Evan Cheng8e136a92007-09-26 21:36:17 +0000474 I->Dep->addPred(CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000475 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng8e136a92007-09-26 21:36:17 +0000476 }
477 }
478 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000479 SUnit *Succ = DelDeps[i].first;
480 bool isCtrl = DelDeps[i].second;
Evan Cheng8e136a92007-09-26 21:36:17 +0000481 Succ->removePred(SU, isCtrl, false);
482 }
483
484 CopyFromSU->addPred(SU, false, false, Reg, -1);
485 CopyToSU->addPred(CopyFromSU, false, false, Reg, 1);
486
487 AvailableQueue->updateNode(SU);
488 AvailableQueue->addNode(CopyFromSU);
489 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000490 Copies.push_back(CopyFromSU);
491 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000492
Evan Cheng1ec79b42007-09-27 07:09:03 +0000493 ++NumCCCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000494}
495
496/// getPhysicalRegisterVT - Returns the ValueType of the physical register
497/// definition of the specified node.
498/// FIXME: Move to SelectionDAG?
499static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
500 const TargetInstrInfo *TII) {
501 const TargetInstrDescriptor &TID = TII->get(N->getTargetOpcode());
502 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
503 unsigned NumRes = TID.numDefs;
504 for (const unsigned *ImpDef = TID.ImplicitDefs; *ImpDef; ++ImpDef) {
505 if (Reg == *ImpDef)
506 break;
507 ++NumRes;
508 }
509 return N->getValueType(NumRes);
510}
511
Evan Cheng5924bf72007-09-25 01:54:36 +0000512/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
513/// scheduling of the given node to satisfy live physical register dependencies.
514/// If the specific node is the last one that's available to schedule, do
515/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000516bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
517 SmallVector<unsigned, 4> &LRegs){
Evan Cheng5924bf72007-09-25 01:54:36 +0000518 if (LiveRegs.empty())
519 return false;
520
Evan Chenge6f92252007-09-27 18:46:06 +0000521 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000522 // If this node would clobber any "live" register, then it's not ready.
Evan Cheng5924bf72007-09-25 01:54:36 +0000523 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
524 I != E; ++I) {
525 if (I->Cost < 0) {
526 unsigned Reg = I->Reg;
Evan Chenge6f92252007-09-27 18:46:06 +0000527 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
528 if (RegAdded.insert(Reg))
529 LRegs.push_back(Reg);
530 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000531 for (const unsigned *Alias = MRI->getAliasSet(Reg);
532 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000533 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
534 if (RegAdded.insert(*Alias))
535 LRegs.push_back(*Alias);
536 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000537 }
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) {
Evan Chenge6f92252007-09-27 18:46:06 +0000548 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
549 if (RegAdded.insert(*Reg))
550 LRegs.push_back(*Reg);
551 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000552 for (const unsigned *Alias = MRI->getAliasSet(*Reg);
553 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000554 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
555 if (RegAdded.insert(*Alias))
556 LRegs.push_back(*Alias);
557 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000558 }
559 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000560 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000561}
562
Evan Cheng1ec79b42007-09-27 07:09:03 +0000563
Evan Chengd38c22b2006-05-11 23:55:42 +0000564/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
565/// schedulers.
566void ScheduleDAGRRList::ListScheduleBottomUp() {
567 unsigned CurCycle = 0;
568 // Add root to Available queue.
Evan Cheng5924bf72007-09-25 01:54:36 +0000569 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
570 RootSU->isAvailable = true;
571 AvailableQueue->push(RootSU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000572
573 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000574 // priority. If it is not ready put it back. Schedule the node.
Evan Cheng5924bf72007-09-25 01:54:36 +0000575 SmallVector<SUnit*, 4> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000576 while (!AvailableQueue->empty()) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000577 bool Delayed = false;
578 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
Evan Cheng5924bf72007-09-25 01:54:36 +0000579 SUnit *CurSU = AvailableQueue->pop();
580 while (CurSU) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000581 if (CurSU->CycleBound <= CurCycle) {
582 SmallVector<unsigned, 4> LRegs;
583 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
Evan Cheng5924bf72007-09-25 01:54:36 +0000584 break;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000585 Delayed = true;
586 LRegsMap.insert(std::make_pair(CurSU, LRegs));
Evan Cheng5924bf72007-09-25 01:54:36 +0000587 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000588
589 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
590 NotReady.push_back(CurSU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000591 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000592 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000593
594 // All candidates are delayed due to live physical reg dependencies.
595 // Try backtracking, code duplication, or inserting cross class copies
596 // to resolve it.
597 if (Delayed && !CurSU) {
598 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
599 SUnit *TrySU = NotReady[i];
600 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
601
602 // Try unscheduling up to the point where it's safe to schedule
603 // this node.
604 unsigned LiveCycle = CurCycle;
605 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
606 unsigned Reg = LRegs[j];
607 unsigned LCycle = LiveRegCycles[Reg];
608 LiveCycle = std::min(LiveCycle, LCycle);
609 }
610 SUnit *OldSU = Sequence[LiveCycle];
611 if (!WillCreateCycle(TrySU, OldSU)) {
612 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
613 // Force the current node to be scheduled before the node that
614 // requires the physical reg dep.
615 if (OldSU->isAvailable) {
616 OldSU->isAvailable = false;
617 AvailableQueue->remove(OldSU);
618 }
619 TrySU->addPred(OldSU, true, true);
620 // If one or more successors has been unscheduled, then the current
621 // node is no longer avaialable. Schedule a successor that's now
622 // available instead.
623 if (!TrySU->isAvailable)
624 CurSU = AvailableQueue->pop();
625 else {
626 CurSU = TrySU;
627 TrySU->isPending = false;
628 NotReady.erase(NotReady.begin()+i);
629 }
630 break;
631 }
632 }
633
634 if (!CurSU) {
635 // Can't backtrace. Try duplicating the nodes that produces these
636 // "expensive to copy" values to break the dependency. In case even
637 // that doesn't work, insert cross class copies.
638 SUnit *TrySU = NotReady[0];
639 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
640 assert(LRegs.size() == 1 && "Can't handle this yet!");
641 unsigned Reg = LRegs[0];
642 SUnit *LRDef = LiveRegDefs[Reg];
643 SUnit *NewDef;
644 if (isSafeToCopy(LRDef->Node))
645 NewDef = CopyAndMoveSuccessors(LRDef);
646 else {
647 // Issue expensive cross register class copies.
648 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
649 const TargetRegisterClass *RC =
650 MRI->getPhysicalRegisterRegClass(VT, Reg);
651 const TargetRegisterClass *DestRC = MRI->getCrossCopyRegClass(RC);
652 if (!DestRC) {
653 assert(false && "Don't know how to copy this physical register!");
654 abort();
655 }
656 SmallVector<SUnit*, 2> Copies;
657 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
658 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
659 << " to SU #" << Copies.front()->NodeNum << "\n";
660 TrySU->addPred(Copies.front(), true, true);
661 NewDef = Copies.back();
662 }
663
664 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
665 << " to SU #" << TrySU->NodeNum << "\n";
666 LiveRegDefs[Reg] = NewDef;
667 NewDef->addPred(TrySU, true, true);
668 TrySU->isAvailable = false;
669 CurSU = NewDef;
670 }
671
672 if (!CurSU) {
673 assert(false && "Unable to resolve live physical register dependencies!");
674 abort();
675 }
676 }
677
Evan Chengd38c22b2006-05-11 23:55:42 +0000678 // Add the nodes that aren't ready back onto the available list.
Evan Cheng5924bf72007-09-25 01:54:36 +0000679 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
680 NotReady[i]->isPending = false;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000681 // May no longer be available due to backtracking.
Evan Cheng5924bf72007-09-25 01:54:36 +0000682 if (NotReady[i]->isAvailable)
683 AvailableQueue->push(NotReady[i]);
684 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000685 NotReady.clear();
686
Evan Cheng5924bf72007-09-25 01:54:36 +0000687 if (!CurSU)
688 Sequence.push_back(0);
689 else {
690 ScheduleNodeBottomUp(CurSU, CurCycle);
691 Sequence.push_back(CurSU);
692 }
693 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000694 }
695
696 // Add entry node last
697 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000698 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000699 Sequence.push_back(Entry);
700 }
701
702 // Reverse the order if it is bottom up.
703 std::reverse(Sequence.begin(), Sequence.end());
704
705
706#ifndef NDEBUG
707 // Verify that all SUnits were scheduled.
708 bool AnyNotSched = false;
709 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Evan Cheng038dcc52007-09-28 19:24:24 +0000710 if (SUnits[i].NumSuccsLeft != 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000711 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000712 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000713 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000714 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000715 AnyNotSched = true;
716 }
717 }
718 assert(!AnyNotSched);
719#endif
720}
721
722//===----------------------------------------------------------------------===//
723// Top-Down Scheduling
724//===----------------------------------------------------------------------===//
725
726/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000727/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000728void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
729 unsigned CurCycle) {
730 // FIXME: the distance between two nodes is not always == the predecessor's
731 // latency. For example, the reader can very well read the register written
732 // by the predecessor later than the issue cycle. It also depends on the
733 // interrupt model (drain vs. freeze).
734 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
735
Evan Cheng038dcc52007-09-28 19:24:24 +0000736 --SuccSU->NumPredsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000737
738#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +0000739 if (SuccSU->NumPredsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000740 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000741 SuccSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000742 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000743 assert(0);
744 }
745#endif
746
Evan Cheng038dcc52007-09-28 19:24:24 +0000747 if (SuccSU->NumPredsLeft == 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000748 SuccSU->isAvailable = true;
749 AvailableQueue->push(SuccSU);
750 }
751}
752
753
754/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
755/// count of its successors. If a successor pending count is zero, add it to
756/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000757void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000758 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000759 DEBUG(SU->dump(&DAG));
760 SU->Cycle = CurCycle;
761
762 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000763
764 // Top down: release successors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000765 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
766 I != E; ++I)
Evan Cheng0effc3a2007-09-19 01:38:40 +0000767 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +0000768 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000769}
770
Dan Gohman54a187e2007-08-20 19:28:38 +0000771/// ListScheduleTopDown - The main loop of list scheduling for top-down
772/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +0000773void ScheduleDAGRRList::ListScheduleTopDown() {
774 unsigned CurCycle = 0;
Evan Cheng5924bf72007-09-25 01:54:36 +0000775 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000776
777 // All leaves to Available queue.
778 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
779 // It is available if it has no predecessors.
780 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
781 AvailableQueue->push(&SUnits[i]);
782 SUnits[i].isAvailable = true;
783 }
784 }
785
786 // Emit the entry node first.
787 ScheduleNodeTopDown(Entry, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000788 Sequence.push_back(Entry);
789 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000790
791 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000792 // priority. If it is not ready put it back. Schedule the node.
Evan Chengd38c22b2006-05-11 23:55:42 +0000793 std::vector<SUnit*> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000794 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000795 SUnit *CurSU = AvailableQueue->pop();
796 while (CurSU && CurSU->CycleBound > CurCycle) {
797 NotReady.push_back(CurSU);
798 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000799 }
800
801 // Add the nodes that aren't ready back onto the available list.
802 AvailableQueue->push_all(NotReady);
803 NotReady.clear();
804
Evan Cheng5924bf72007-09-25 01:54:36 +0000805 if (!CurSU)
806 Sequence.push_back(0);
807 else {
808 ScheduleNodeTopDown(CurSU, CurCycle);
809 Sequence.push_back(CurSU);
810 }
Evan Chengd12c97d2006-05-30 18:05:39 +0000811 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000812 }
813
814
815#ifndef NDEBUG
816 // Verify that all SUnits were scheduled.
817 bool AnyNotSched = false;
818 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
819 if (!SUnits[i].isScheduled) {
820 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000821 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000822 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000823 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000824 AnyNotSched = true;
825 }
826 }
827 assert(!AnyNotSched);
828#endif
829}
830
831
832
833//===----------------------------------------------------------------------===//
834// RegReductionPriorityQueue Implementation
835//===----------------------------------------------------------------------===//
836//
837// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
838// to reduce register pressure.
839//
840namespace {
841 template<class SF>
842 class RegReductionPriorityQueue;
843
844 /// Sorting functions for the Available queue.
845 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
846 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
847 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
848 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
849
850 bool operator()(const SUnit* left, const SUnit* right) const;
851 };
852
853 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
854 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
855 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
856 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
857
858 bool operator()(const SUnit* left, const SUnit* right) const;
859 };
860} // end anonymous namespace
861
Evan Cheng961bbd32007-01-08 23:50:38 +0000862static inline bool isCopyFromLiveIn(const SUnit *SU) {
863 SDNode *N = SU->Node;
Evan Cheng8e136a92007-09-26 21:36:17 +0000864 return N && N->getOpcode() == ISD::CopyFromReg &&
Evan Cheng961bbd32007-01-08 23:50:38 +0000865 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
866}
867
Evan Chengd38c22b2006-05-11 23:55:42 +0000868namespace {
869 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000870 class VISIBILITY_HIDDEN RegReductionPriorityQueue
871 : public SchedulingPriorityQueue {
Evan Chengd38c22b2006-05-11 23:55:42 +0000872 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
873
874 public:
875 RegReductionPriorityQueue() :
876 Queue(SF(this)) {}
877
Evan Cheng5924bf72007-09-25 01:54:36 +0000878 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000879 std::vector<SUnit> &sunits) {}
Evan Cheng5924bf72007-09-25 01:54:36 +0000880
881 virtual void addNode(const SUnit *SU) {}
882
883 virtual void updateNode(const SUnit *SU) {}
884
Evan Chengd38c22b2006-05-11 23:55:42 +0000885 virtual void releaseState() {}
886
Evan Cheng6730f032007-01-08 23:55:53 +0000887 virtual unsigned getNodePriority(const SUnit *SU) const {
Evan Chengd38c22b2006-05-11 23:55:42 +0000888 return 0;
889 }
890
Evan Cheng5924bf72007-09-25 01:54:36 +0000891 unsigned size() const { return Queue.size(); }
892
Evan Chengd38c22b2006-05-11 23:55:42 +0000893 bool empty() const { return Queue.empty(); }
894
895 void push(SUnit *U) {
896 Queue.push(U);
897 }
898 void push_all(const std::vector<SUnit *> &Nodes) {
899 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
900 Queue.push(Nodes[i]);
901 }
902
903 SUnit *pop() {
Evan Chengd12c97d2006-05-30 18:05:39 +0000904 if (empty()) return NULL;
Evan Chengd38c22b2006-05-11 23:55:42 +0000905 SUnit *V = Queue.top();
906 Queue.pop();
907 return V;
908 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000909
Evan Cheng5924bf72007-09-25 01:54:36 +0000910 /// remove - This is a really inefficient way to remove a node from a
911 /// priority queue. We should roll our own heap to make this better or
912 /// something.
913 void remove(SUnit *SU) {
914 std::vector<SUnit*> Temp;
915
916 assert(!Queue.empty() && "Not in queue!");
917 while (Queue.top() != SU) {
918 Temp.push_back(Queue.top());
919 Queue.pop();
920 assert(!Queue.empty() && "Not in queue!");
921 }
922
923 // Remove the node from the PQ.
924 Queue.pop();
925
926 // Add all the other nodes back.
927 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
928 Queue.push(Temp[i]);
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000929 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000930 };
931
932 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000933 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
934 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +0000935 // SUnitMap SDNode to SUnit mapping (n -> n).
936 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000937
Evan Chengd38c22b2006-05-11 23:55:42 +0000938 // SUnits - The SUnits for the current graph.
939 const std::vector<SUnit> *SUnits;
940
941 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +0000942 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +0000943
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000944 const TargetInstrInfo *TII;
Evan Chengd38c22b2006-05-11 23:55:42 +0000945 public:
Dan Gohman54a187e2007-08-20 19:28:38 +0000946 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000947 : TII(tii) {}
Evan Chengd38c22b2006-05-11 23:55:42 +0000948
Evan Cheng5924bf72007-09-25 01:54:36 +0000949 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000950 std::vector<SUnit> &sunits) {
951 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +0000952 SUnits = &sunits;
953 // Add pseudo dependency edges for two-address nodes.
Evan Chengafed73e2006-05-12 01:58:24 +0000954 AddPseudoTwoAddrDeps();
Evan Chengd38c22b2006-05-11 23:55:42 +0000955 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +0000956 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +0000957 }
958
Evan Cheng5924bf72007-09-25 01:54:36 +0000959 void addNode(const SUnit *SU) {
960 SethiUllmanNumbers.resize(SUnits->size(), 0);
961 CalcNodeSethiUllmanNumber(SU);
962 }
963
964 void updateNode(const SUnit *SU) {
965 SethiUllmanNumbers[SU->NodeNum] = 0;
966 CalcNodeSethiUllmanNumber(SU);
967 }
968
Evan Chengd38c22b2006-05-11 23:55:42 +0000969 void releaseState() {
970 SUnits = 0;
971 SethiUllmanNumbers.clear();
972 }
973
Evan Cheng6730f032007-01-08 23:55:53 +0000974 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +0000975 assert(SU->NodeNum < SethiUllmanNumbers.size());
Evan Cheng8e136a92007-09-26 21:36:17 +0000976 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Cheng961bbd32007-01-08 23:50:38 +0000977 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
978 // CopyFromReg should be close to its def because it restricts
979 // allocation choices. But if it is a livein then perhaps we want it
980 // closer to its uses so it can be coalesced.
981 return 0xffff;
982 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
983 // CopyToReg should be close to its uses to facilitate coalescing and
984 // avoid spilling.
985 return 0;
986 else if (SU->NumSuccs == 0)
987 // If SU does not have a use, i.e. it doesn't produce a value that would
988 // be consumed (e.g. store), then it terminates a chain of computation.
989 // Give it a large SethiUllman number so it will be scheduled right
990 // before its predecessors that it doesn't lengthen their live ranges.
991 return 0xffff;
992 else if (SU->NumPreds == 0)
993 // If SU does not have a def, schedule it close to its uses because it
994 // does not lengthen any live ranges.
995 return 0;
996 else
997 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +0000998 }
999
1000 private:
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001001 bool canClobber(SUnit *SU, SUnit *Op);
Evan Chengd38c22b2006-05-11 23:55:42 +00001002 void AddPseudoTwoAddrDeps();
Evan Cheng6730f032007-01-08 23:55:53 +00001003 void CalculateSethiUllmanNumbers();
1004 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001005 };
1006
1007
1008 template<class SF>
Dan Gohman54a187e2007-08-20 19:28:38 +00001009 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1010 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +00001011 // SUnitMap SDNode to SUnit mapping (n -> n).
1012 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001013
Evan Chengd38c22b2006-05-11 23:55:42 +00001014 // SUnits - The SUnits for the current graph.
1015 const std::vector<SUnit> *SUnits;
1016
1017 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001018 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001019
1020 public:
1021 TDRegReductionPriorityQueue() {}
1022
Evan Cheng5924bf72007-09-25 01:54:36 +00001023 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001024 std::vector<SUnit> &sunits) {
1025 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +00001026 SUnits = &sunits;
1027 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001028 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001029 }
1030
Evan Cheng5924bf72007-09-25 01:54:36 +00001031 void addNode(const SUnit *SU) {
1032 SethiUllmanNumbers.resize(SUnits->size(), 0);
1033 CalcNodeSethiUllmanNumber(SU);
1034 }
1035
1036 void updateNode(const SUnit *SU) {
1037 SethiUllmanNumbers[SU->NodeNum] = 0;
1038 CalcNodeSethiUllmanNumber(SU);
1039 }
1040
Evan Chengd38c22b2006-05-11 23:55:42 +00001041 void releaseState() {
1042 SUnits = 0;
1043 SethiUllmanNumbers.clear();
1044 }
1045
Evan Cheng6730f032007-01-08 23:55:53 +00001046 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001047 assert(SU->NodeNum < SethiUllmanNumbers.size());
1048 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001049 }
1050
1051 private:
Evan Cheng6730f032007-01-08 23:55:53 +00001052 void CalculateSethiUllmanNumbers();
1053 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001054 };
1055}
1056
Evan Chengb9e3db62007-03-14 22:43:40 +00001057/// closestSucc - Returns the scheduled cycle of the successor which is
1058/// closet to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001059static unsigned closestSucc(const SUnit *SU) {
1060 unsigned MaxCycle = 0;
1061 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001062 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001063 unsigned Cycle = I->Dep->Cycle;
Evan Chengb9e3db62007-03-14 22:43:40 +00001064 // If there are bunch of CopyToRegs stacked up, they should be considered
1065 // to be at the same position.
Evan Cheng8e136a92007-09-26 21:36:17 +00001066 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
Evan Cheng0effc3a2007-09-19 01:38:40 +00001067 Cycle = closestSucc(I->Dep)+1;
Evan Chengb9e3db62007-03-14 22:43:40 +00001068 if (Cycle > MaxCycle)
1069 MaxCycle = Cycle;
1070 }
Evan Cheng28748552007-03-13 23:25:11 +00001071 return MaxCycle;
1072}
1073
Evan Chengd38c22b2006-05-11 23:55:42 +00001074// Bottom up
1075bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
David Greene4c1e6f32007-06-29 03:42:23 +00001076 // There used to be a special tie breaker here that looked for
David Greene5b6f7552007-06-29 02:48:09 +00001077 // two-address instructions and preferred the instruction with a
1078 // def&use operand. The special case triggered diagnostics when
1079 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1080 // ordering that priority_queue requires. It didn't help much anyway
1081 // because AddPseudoTwoAddrDeps already covers many of the cases
1082 // where it would have applied. In addition, it's counter-intuitive
1083 // that a tie breaker would be the first thing attempted. There's a
1084 // "real" tie breaker below that is the operation of last resort.
1085 // The fact that the "special tie breaker" would trigger when there
1086 // wasn't otherwise a tie is what broke the strict weak ordering
1087 // constraint.
Evan Cheng99f2f792006-05-13 08:22:24 +00001088
Evan Cheng6730f032007-01-08 23:55:53 +00001089 unsigned LPriority = SPQ->getNodePriority(left);
1090 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng961bbd32007-01-08 23:50:38 +00001091 if (LPriority > RPriority)
Evan Chengd38c22b2006-05-11 23:55:42 +00001092 return true;
Evan Cheng28748552007-03-13 23:25:11 +00001093 else if (LPriority == RPriority) {
Dan Gohmane131e3a2007-04-26 19:40:56 +00001094 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
Evan Cheng28748552007-03-13 23:25:11 +00001095 // e.g.
1096 // t1 = op t2, c1
1097 // t3 = op t4, c2
1098 //
1099 // and the following instructions are both ready.
1100 // t2 = op c3
1101 // t4 = op c4
1102 //
1103 // Then schedule t2 = op first.
1104 // i.e.
1105 // t4 = op c4
1106 // t2 = op c3
1107 // t1 = op t2, c1
1108 // t3 = op t4, c2
1109 //
1110 // This creates more short live intervals.
1111 unsigned LDist = closestSucc(left);
1112 unsigned RDist = closestSucc(right);
1113 if (LDist < RDist)
Evan Chengd38c22b2006-05-11 23:55:42 +00001114 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001115 else if (LDist == RDist) {
Evan Chengf72693f2007-09-28 19:37:35 +00001116 if (left->Height > right->Height)
Evan Chengd38c22b2006-05-11 23:55:42 +00001117 return true;
Evan Chengf72693f2007-09-28 19:37:35 +00001118 else if (left->Height == right->Height)
1119 if (left->Depth < right->Depth)
Evan Cheng99f2f792006-05-13 08:22:24 +00001120 return true;
Evan Chengf72693f2007-09-28 19:37:35 +00001121 else if (left->Depth == right->Depth)
1122 if (left->CycleBound > right->CycleBound)
Evan Cheng28748552007-03-13 23:25:11 +00001123 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001124 }
Evan Cheng28748552007-03-13 23:25:11 +00001125 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001126 return false;
1127}
1128
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001129template<class SF>
1130bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
1131 if (SU->isTwoAddress) {
1132 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001133 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001134 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
1135 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001136 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001137 SDNode *DU = SU->Node->getOperand(i).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001138 if (Op == (*SUnitMap)[DU][SU->InstanceNo])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001139 return true;
1140 }
1141 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001142 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001143 return false;
1144}
1145
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001146
Evan Chenga5e595d2007-09-28 22:32:30 +00001147/// hasCopyToRegUse - Return true if SU has a value successor that is a
1148/// CopyToReg node.
1149static bool hasCopyToRegUse(SUnit *SU) {
1150 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1151 I != E; ++I) {
1152 if (I->isCtrl) continue;
1153 SUnit *SuccSU = I->Dep;
1154 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1155 return true;
1156 }
1157 return false;
1158}
1159
Evan Chengd38c22b2006-05-11 23:55:42 +00001160/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1161/// it as a def&use operand. Add a pseudo control edge from it to the other
1162/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00001163/// first (lower in the schedule). If both nodes are two-address, favor the
1164/// one that has a CopyToReg use (more likely to be a loop induction update).
1165/// If both are two-address, but one is commutable while the other is not
1166/// commutable, favor the one that's not commutable.
Evan Chengd38c22b2006-05-11 23:55:42 +00001167template<class SF>
1168void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001169 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1170 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1171 if (!SU->isTwoAddress)
1172 continue;
1173
1174 SDNode *Node = SU->Node;
Evan Chenga5e595d2007-09-28 22:32:30 +00001175 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001176 continue;
1177
1178 unsigned Opc = Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001179 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001180 unsigned NumOps = ScheduleDAG::CountOperands(Node);
1181 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001182 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001183 SDNode *DU = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001184 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
Evan Chengf24d15f2006-11-06 21:33:46 +00001185 if (!DUSU) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001186 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1187 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001188 if (I->isCtrl) continue;
1189 SUnit *SuccSU = I->Dep;
Evan Cheng5924bf72007-09-25 01:54:36 +00001190 // Don't constraint nodes with implicit defs. It can create cycles
1191 // plus it may increase register pressures.
Evan Chenga5e595d2007-09-28 22:32:30 +00001192 if (SuccSU == SU || SuccSU->hasPhysRegDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001193 continue;
1194 // Be conservative. Ignore if nodes aren't at the same depth.
1195 if (SuccSU->Depth != SU->Depth)
1196 continue;
1197 if ((!canClobber(SuccSU, DUSU) ||
Evan Chenga5e595d2007-09-28 22:32:30 +00001198 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
Evan Cheng5924bf72007-09-25 01:54:36 +00001199 (!SU->isCommutable && SuccSU->isCommutable)) &&
1200 !isReachable(SuccSU, SU)) {
1201 DOUT << "Adding an edge from SU # " << SU->NodeNum
1202 << " to SU #" << SuccSU->NodeNum << "\n";
1203 SU->addPred(SuccSU, true, true);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001204 }
1205 }
1206 }
1207 }
1208 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001209}
1210
Evan Cheng6730f032007-01-08 23:55:53 +00001211/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001212/// Smaller number is the higher priority.
1213template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001214unsigned BURegReductionPriorityQueue<SF>::
1215CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001216 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001217 if (SethiUllmanNumber != 0)
1218 return SethiUllmanNumber;
1219
Evan Cheng961bbd32007-01-08 23:50:38 +00001220 unsigned Extra = 0;
1221 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1222 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001223 if (I->isCtrl) continue; // ignore chain preds
1224 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001225 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Cheng961bbd32007-01-08 23:50:38 +00001226 if (PredSethiUllman > SethiUllmanNumber) {
1227 SethiUllmanNumber = PredSethiUllman;
1228 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001229 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001230 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001231 }
Evan Cheng961bbd32007-01-08 23:50:38 +00001232
1233 SethiUllmanNumber += Extra;
1234
1235 if (SethiUllmanNumber == 0)
1236 SethiUllmanNumber = 1;
Evan Chengd38c22b2006-05-11 23:55:42 +00001237
1238 return SethiUllmanNumber;
1239}
1240
Evan Cheng6730f032007-01-08 23:55:53 +00001241/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1242/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001243template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001244void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001245 SethiUllmanNumbers.assign(SUnits->size(), 0);
1246
1247 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001248 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001249}
1250
1251static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1252 unsigned Sum = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001253 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1254 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001255 SUnit *SuccSU = I->Dep;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001256 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1257 EE = SuccSU->Preds.end(); II != EE; ++II) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001258 SUnit *PredSU = II->Dep;
Evan Chengd38c22b2006-05-11 23:55:42 +00001259 if (!PredSU->isScheduled)
Evan Cheng5924bf72007-09-25 01:54:36 +00001260 ++Sum;
Evan Chengd38c22b2006-05-11 23:55:42 +00001261 }
1262 }
1263
1264 return Sum;
1265}
1266
1267
1268// Top down
1269bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00001270 unsigned LPriority = SPQ->getNodePriority(left);
1271 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng8e136a92007-09-26 21:36:17 +00001272 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1273 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00001274 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1275 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1276 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1277 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1278
1279 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1280 return false;
1281 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1282 return true;
1283
1284 // Special tie breaker: if two nodes share a operand, the one that use it
1285 // as a def&use operand is preferred.
1286 if (LIsTarget && RIsTarget) {
1287 if (left->isTwoAddress && !right->isTwoAddress) {
1288 SDNode *DUNode = left->Node->getOperand(0).Val;
1289 if (DUNode->isOperand(right->Node))
1290 RBonus += 2;
1291 }
1292 if (!left->isTwoAddress && right->isTwoAddress) {
1293 SDNode *DUNode = right->Node->getOperand(0).Val;
1294 if (DUNode->isOperand(left->Node))
1295 LBonus += 2;
1296 }
1297 }
1298 if (LIsFloater)
1299 LBonus -= 2;
1300 if (RIsFloater)
1301 RBonus -= 2;
1302 if (left->NumSuccs == 1)
1303 LBonus += 2;
1304 if (right->NumSuccs == 1)
1305 RBonus += 2;
1306
1307 if (LPriority+LBonus < RPriority+RBonus)
1308 return true;
1309 else if (LPriority == RPriority)
1310 if (left->Depth < right->Depth)
1311 return true;
1312 else if (left->Depth == right->Depth)
1313 if (left->NumSuccsLeft > right->NumSuccsLeft)
1314 return true;
1315 else if (left->NumSuccsLeft == right->NumSuccsLeft)
1316 if (left->CycleBound > right->CycleBound)
1317 return true;
1318 return false;
1319}
1320
Evan Cheng6730f032007-01-08 23:55:53 +00001321/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001322/// Smaller number is the higher priority.
1323template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001324unsigned TDRegReductionPriorityQueue<SF>::
1325CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001326 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001327 if (SethiUllmanNumber != 0)
1328 return SethiUllmanNumber;
1329
Evan Cheng8e136a92007-09-26 21:36:17 +00001330 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001331 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Evan Cheng961bbd32007-01-08 23:50:38 +00001332 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001333 else if (SU->NumSuccsLeft == 0)
1334 // If SU does not have a use, i.e. it doesn't produce a value that would
1335 // be consumed (e.g. store), then it terminates a chain of computation.
Chris Lattner296a83c2007-02-01 04:55:59 +00001336 // Give it a small SethiUllman number so it will be scheduled right before
1337 // its predecessors that it doesn't lengthen their live ranges.
Evan Cheng961bbd32007-01-08 23:50:38 +00001338 SethiUllmanNumber = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001339 else if (SU->NumPredsLeft == 0 &&
1340 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
Evan Cheng961bbd32007-01-08 23:50:38 +00001341 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001342 else {
1343 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001344 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1345 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001346 if (I->isCtrl) continue; // ignore chain preds
1347 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001348 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001349 if (PredSethiUllman > SethiUllmanNumber) {
1350 SethiUllmanNumber = PredSethiUllman;
1351 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001352 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001353 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001354 }
1355
1356 SethiUllmanNumber += Extra;
1357 }
1358
1359 return SethiUllmanNumber;
1360}
1361
Evan Cheng6730f032007-01-08 23:55:53 +00001362/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1363/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001364template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001365void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001366 SethiUllmanNumbers.assign(SUnits->size(), 0);
1367
1368 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001369 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001370}
1371
1372//===----------------------------------------------------------------------===//
1373// Public Constructor Functions
1374//===----------------------------------------------------------------------===//
1375
Jim Laskey03593f72006-08-01 18:29:48 +00001376llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1377 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001378 MachineBasicBlock *BB) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001379 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
Jim Laskey95eda5b2006-08-01 14:21:23 +00001380 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001381 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
Evan Chengd38c22b2006-05-11 23:55:42 +00001382}
1383
Jim Laskey03593f72006-08-01 18:29:48 +00001384llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1385 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001386 MachineBasicBlock *BB) {
Jim Laskey95eda5b2006-08-01 14:21:23 +00001387 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
Chris Lattner296a83c2007-02-01 04:55:59 +00001388 new TDRegReductionPriorityQueue<td_ls_rr_sort>());
Evan Chengd38c22b2006-05-11 23:55:42 +00001389}
1390