blob: 2baf24d7d54b33235406353ac37d57ff2f681021 [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");
Evan Cheng79e97132007-10-05 01:39:18 +000037STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000038STATISTIC(NumDups, "Number of duplicated nodes");
39STATISTIC(NumCCCopies, "Number of cross class copies");
40
Jim Laskey95eda5b2006-08-01 14:21:23 +000041static RegisterScheduler
42 burrListDAGScheduler("list-burr",
43 " Bottom-up register reduction list scheduling",
44 createBURRListDAGScheduler);
45static RegisterScheduler
46 tdrListrDAGScheduler("list-tdrr",
47 " Top-down register reduction list scheduling",
48 createTDRRListDAGScheduler);
49
Evan Chengd38c22b2006-05-11 23:55:42 +000050namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000051//===----------------------------------------------------------------------===//
52/// ScheduleDAGRRList - The actual register reduction list scheduler
53/// implementation. This supports both top-down and bottom-up scheduling.
54///
Chris Lattnere097e6f2006-06-28 22:17:39 +000055class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
Evan Chengd38c22b2006-05-11 23:55:42 +000056private:
57 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
58 /// it is top-down.
59 bool isBottomUp;
60
61 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Cheng5924bf72007-09-25 01:54:36 +000062 ///a
Evan Chengd38c22b2006-05-11 23:55:42 +000063 SchedulingPriorityQueue *AvailableQueue;
64
Evan Cheng5924bf72007-09-25 01:54:36 +000065 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
66 /// that are "live". These nodes must be scheduled before any other nodes that
67 /// modifies the registers can be scheduled.
68 SmallSet<unsigned, 4> LiveRegs;
69 std::vector<SUnit*> LiveRegDefs;
70 std::vector<unsigned> LiveRegCycles;
71
Evan Chengd38c22b2006-05-11 23:55:42 +000072public:
73 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
74 const TargetMachine &tm, bool isbottomup,
75 SchedulingPriorityQueue *availqueue)
76 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
77 AvailableQueue(availqueue) {
78 }
79
80 ~ScheduleDAGRRList() {
81 delete AvailableQueue;
82 }
83
84 void Schedule();
85
86private:
Evan Cheng8e136a92007-09-26 21:36:17 +000087 void ReleasePred(SUnit*, bool, unsigned);
88 void ReleaseSucc(SUnit*, bool isChain, unsigned);
89 void CapturePred(SUnit*, SUnit*, bool);
90 void ScheduleNodeBottomUp(SUnit*, unsigned);
91 void ScheduleNodeTopDown(SUnit*, unsigned);
92 void UnscheduleNodeBottomUp(SUnit*);
93 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
94 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Cheng1ec79b42007-09-27 07:09:03 +000095 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
Evan Cheng8e136a92007-09-26 21:36:17 +000096 const TargetRegisterClass*,
Evan Cheng1ec79b42007-09-27 07:09:03 +000097 const TargetRegisterClass*,
98 SmallVector<SUnit*, 2>&);
99 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Evan Chengd38c22b2006-05-11 23:55:42 +0000100 void ListScheduleTopDown();
101 void ListScheduleBottomUp();
Evan Chengafed73e2006-05-12 01:58:24 +0000102 void CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000103};
104} // end anonymous namespace
105
106
107/// Schedule - Schedule the DAG using list scheduling.
108void ScheduleDAGRRList::Schedule() {
Bill Wendling22e978a2006-12-07 20:04:42 +0000109 DOUT << "********** List Scheduling **********\n";
Evan Cheng5924bf72007-09-25 01:54:36 +0000110
111 LiveRegDefs.resize(MRI->getNumRegs(), NULL);
112 LiveRegCycles.resize(MRI->getNumRegs(), 0);
113
Evan Chengd38c22b2006-05-11 23:55:42 +0000114 // Build scheduling units.
115 BuildSchedUnits();
116
Evan Chengd38c22b2006-05-11 23:55:42 +0000117 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Chris Lattnerd86418a2006-08-17 00:09:56 +0000118 SUnits[su].dumpAll(&DAG));
Evan Cheng47fbeda2006-10-14 08:34:06 +0000119 CalculateDepths();
120 CalculateHeights();
Evan Chengd38c22b2006-05-11 23:55:42 +0000121
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000122 AvailableQueue->initNodes(SUnitMap, SUnits);
Dan Gohman54a187e2007-08-20 19:28:38 +0000123
Evan Chengd38c22b2006-05-11 23:55:42 +0000124 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
125 if (isBottomUp)
126 ListScheduleBottomUp();
127 else
128 ListScheduleTopDown();
129
130 AvailableQueue->releaseState();
Dan Gohman54a187e2007-08-20 19:28:38 +0000131
Evan Cheng009f5f52006-05-25 08:37:31 +0000132 CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000133
Bill Wendling22e978a2006-12-07 20:04:42 +0000134 DOUT << "*** Final schedule ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000135 DEBUG(dumpSchedule());
Bill Wendling22e978a2006-12-07 20:04:42 +0000136 DOUT << "\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000137
138 // Emit in scheduled order
139 EmitSchedule();
140}
141
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000142/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
Evan Chengafed73e2006-05-12 01:58:24 +0000143/// it is not the last use of its first operand, add it to the CommuteSet if
144/// possible. It will be commuted when it is translated to a MI.
145void ScheduleDAGRRList::CommuteNodesToReducePressure() {
Evan Chenge3c44192007-06-22 01:35:51 +0000146 SmallPtrSet<SUnit*, 4> OperandSeen;
Evan Chengafed73e2006-05-12 01:58:24 +0000147 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
148 SUnit *SU = Sequence[i];
Evan Cheng8e136a92007-09-26 21:36:17 +0000149 if (!SU || !SU->Node) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000150 if (SU->isCommutable) {
151 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +0000152 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000153 unsigned NumOps = CountOperands(SU->Node);
154 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000155 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000156 continue;
157
158 SDNode *OpN = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000159 SUnit *OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000160 if (OpSU && OperandSeen.count(OpSU) == 1) {
161 // Ok, so SU is not the last use of OpSU, but SU is two-address so
162 // it will clobber OpSU. Try to commute SU if no other source operands
163 // are live below.
164 bool DoCommute = true;
165 for (unsigned k = 0; k < NumOps; ++k) {
166 if (k != j) {
167 OpN = SU->Node->getOperand(k).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +0000168 OpSU = SUnitMap[OpN][SU->InstanceNo];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000169 if (OpSU && OperandSeen.count(OpSU) == 1) {
170 DoCommute = false;
171 break;
172 }
173 }
Evan Chengafed73e2006-05-12 01:58:24 +0000174 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000175 if (DoCommute)
176 CommuteSet.insert(SU->Node);
Evan Chengafed73e2006-05-12 01:58:24 +0000177 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000178
179 // Only look at the first use&def node for now.
180 break;
Evan Chengafed73e2006-05-12 01:58:24 +0000181 }
182 }
183
Chris Lattnerd86418a2006-08-17 00:09:56 +0000184 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
185 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000186 if (!I->isCtrl)
187 OperandSeen.insert(I->Dep);
Evan Chengafed73e2006-05-12 01:58:24 +0000188 }
189 }
190}
Evan Chengd38c22b2006-05-11 23:55:42 +0000191
192//===----------------------------------------------------------------------===//
193// Bottom-Up Scheduling
194//===----------------------------------------------------------------------===//
195
Evan Chengd38c22b2006-05-11 23:55:42 +0000196/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000197/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000198void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
199 unsigned CurCycle) {
200 // FIXME: the distance between two nodes is not always == the predecessor's
201 // latency. For example, the reader can very well read the register written
202 // by the predecessor later than the issue cycle. It also depends on the
203 // interrupt model (drain vs. freeze).
204 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
205
Evan Cheng038dcc52007-09-28 19:24:24 +0000206 --PredSU->NumSuccsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000207
208#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +0000209 if (PredSU->NumSuccsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000210 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000211 PredSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000212 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000213 assert(0);
214 }
215#endif
216
Evan Cheng038dcc52007-09-28 19:24:24 +0000217 if (PredSU->NumSuccsLeft == 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000218 // EntryToken has to go last! Special case it here.
Evan Cheng8e136a92007-09-26 21:36:17 +0000219 if (!PredSU->Node || PredSU->Node->getOpcode() != ISD::EntryToken) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000220 PredSU->isAvailable = true;
221 AvailableQueue->push(PredSU);
222 }
223 }
224}
225
226/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
227/// count of its predecessors. If a predecessor pending count is zero, add it to
228/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000229void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000230 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000231 DEBUG(SU->dump(&DAG));
232 SU->Cycle = CurCycle;
233
234 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000235
236 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000237 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000238 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000239 ReleasePred(I->Dep, I->isCtrl, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000240 if (I->Cost < 0) {
241 // This is a physical register dependency and it's impossible or
242 // expensive to copy the register. Make sure nothing that can
243 // clobber the register is scheduled between the predecessor and
244 // this node.
245 if (LiveRegs.insert(I->Reg)) {
246 LiveRegDefs[I->Reg] = I->Dep;
247 LiveRegCycles[I->Reg] = CurCycle;
248 }
249 }
250 }
251
252 // Release all the implicit physical register defs that are live.
253 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
254 I != E; ++I) {
255 if (I->Cost < 0) {
256 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
257 LiveRegs.erase(I->Reg);
258 assert(LiveRegDefs[I->Reg] == SU &&
259 "Physical register dependency violated?");
260 LiveRegDefs[I->Reg] = NULL;
261 LiveRegCycles[I->Reg] = 0;
262 }
263 }
264 }
265
Evan Chengd38c22b2006-05-11 23:55:42 +0000266 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000267}
268
Evan Cheng5924bf72007-09-25 01:54:36 +0000269/// CapturePred - This does the opposite of ReleasePred. Since SU is being
270/// unscheduled, incrcease the succ left count of its predecessors. Remove
271/// them from AvailableQueue if necessary.
272void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
273 PredSU->CycleBound = 0;
274 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
275 I != E; ++I) {
276 if (I->Dep == SU)
277 continue;
278 PredSU->CycleBound = std::max(PredSU->CycleBound,
279 I->Dep->Cycle + PredSU->Latency);
280 }
281
282 if (PredSU->isAvailable) {
283 PredSU->isAvailable = false;
284 if (!PredSU->isPending)
285 AvailableQueue->remove(PredSU);
286 }
287
Evan Cheng038dcc52007-09-28 19:24:24 +0000288 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000289}
290
291/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
292/// its predecessor states to reflect the change.
293void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
294 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
295 DEBUG(SU->dump(&DAG));
296
297 AvailableQueue->UnscheduledNode(SU);
298
299 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
300 I != E; ++I) {
301 CapturePred(I->Dep, SU, I->isCtrl);
302 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
303 LiveRegs.erase(I->Reg);
304 assert(LiveRegDefs[I->Reg] == I->Dep &&
305 "Physical register dependency violated?");
306 LiveRegDefs[I->Reg] = NULL;
307 LiveRegCycles[I->Reg] = 0;
308 }
309 }
310
311 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
312 I != E; ++I) {
313 if (I->Cost < 0) {
314 if (LiveRegs.insert(I->Reg)) {
315 assert(!LiveRegDefs[I->Reg] &&
316 "Physical register dependency violated?");
317 LiveRegDefs[I->Reg] = SU;
318 }
319 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
320 LiveRegCycles[I->Reg] = I->Dep->Cycle;
321 }
322 }
323
324 SU->Cycle = 0;
325 SU->isScheduled = false;
326 SU->isAvailable = true;
327 AvailableQueue->push(SU);
328}
329
Evan Chengcfd5f822007-09-27 00:25:29 +0000330// FIXME: This is probably too slow!
331static void isReachable(SUnit *SU, SUnit *TargetSU,
332 SmallPtrSet<SUnit*, 32> &Visited, bool &Reached) {
333 if (Reached) return;
334 if (SU == TargetSU) {
335 Reached = true;
336 return;
337 }
338 if (!Visited.insert(SU)) return;
339
340 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
341 ++I)
342 isReachable(I->Dep, TargetSU, Visited, Reached);
343}
344
345static bool isReachable(SUnit *SU, SUnit *TargetSU) {
346 SmallPtrSet<SUnit*, 32> Visited;
347 bool Reached = false;
348 isReachable(SU, TargetSU, Visited, Reached);
349 return Reached;
350}
351
352/// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
353/// create a cycle.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000354static bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
Evan Chengcfd5f822007-09-27 00:25:29 +0000355 if (isReachable(TargetSU, SU))
356 return true;
357 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
358 I != E; ++I)
359 if (I->Cost < 0 && isReachable(TargetSU, I->Dep))
360 return true;
361 return false;
362}
363
Evan Cheng8e136a92007-09-26 21:36:17 +0000364/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Evan Cheng5924bf72007-09-25 01:54:36 +0000365/// BTCycle in order to schedule a specific node. Returns the last unscheduled
366/// SUnit. Also returns if a successor is unscheduled in the process.
Evan Cheng8e136a92007-09-26 21:36:17 +0000367void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
368 unsigned &CurCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000369 SUnit *OldSU = NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000370 while (CurCycle > BtCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000371 OldSU = Sequence.back();
372 Sequence.pop_back();
373 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000374 // Don't try to remove SU from AvailableQueue.
375 SU->isAvailable = false;
Evan Cheng5924bf72007-09-25 01:54:36 +0000376 UnscheduleNodeBottomUp(OldSU);
377 --CurCycle;
378 }
379
380
381 if (SU->isSucc(OldSU)) {
382 assert(false && "Something is wrong!");
383 abort();
384 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000385
386 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000387}
388
Evan Cheng5924bf72007-09-25 01:54:36 +0000389/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
390/// successors to the newly created node.
391SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Evan Cheng79e97132007-10-05 01:39:18 +0000392 if (SU->FlaggedNodes.size())
393 return NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000394
Evan Cheng79e97132007-10-05 01:39:18 +0000395 SDNode *N = SU->Node;
396 if (!N)
397 return NULL;
398
399 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000400 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000401 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
402 MVT::ValueType VT = N->getValueType(i);
403 if (VT == MVT::Flag)
404 return NULL;
405 else if (VT == MVT::Other)
406 TryUnfold = true;
407 }
Evan Cheng79e97132007-10-05 01:39:18 +0000408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
409 const SDOperand &Op = N->getOperand(i);
410 MVT::ValueType VT = Op.Val->getValueType(Op.ResNo);
411 if (VT == MVT::Flag)
412 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000413 }
414
415 if (TryUnfold) {
416 SmallVector<SDNode*, 4> NewNodes;
417 if (!MRI->unfoldMemoryOperand(DAG, N, NewNodes))
418 return NULL;
419
420 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
421 assert(NewNodes.size() == 2 && "Expected a load folding node!");
422
423 N = NewNodes[1];
424 SDNode *LoadNode = NewNodes[0];
425 std::vector<SDNode*> Deleted;
426 unsigned NumVals = N->getNumValues();
427 unsigned OldNumVals = SU->Node->getNumValues();
428 for (unsigned i = 0; i != NumVals; ++i)
429 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i),
430 SDOperand(N, i), Deleted);
431 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
432 SDOperand(LoadNode, 1), Deleted);
433
434 SUnit *LoadSU = NewSUnit(LoadNode);
435 SUnit *NewSU = NewSUnit(N);
436 SUnitMap[LoadNode].push_back(LoadSU);
437 SUnitMap[N].push_back(NewSU);
438 const TargetInstrDescriptor *TID = &TII->get(LoadNode->getTargetOpcode());
439 for (unsigned i = 0; i != TID->numOperands; ++i) {
440 if (TID->getOperandConstraint(i, TOI::TIED_TO) != -1) {
441 LoadSU->isTwoAddress = true;
442 break;
443 }
444 }
445 if (TID->Flags & M_COMMUTABLE)
446 LoadSU->isCommutable = true;
447
448 TID = &TII->get(N->getTargetOpcode());
449 for (unsigned i = 0; i != TID->numOperands; ++i) {
450 if (TID->getOperandConstraint(i, TOI::TIED_TO) != -1) {
451 NewSU->isTwoAddress = true;
452 break;
453 }
454 }
455 if (TID->Flags & M_COMMUTABLE)
456 NewSU->isCommutable = true;
457
458 // FIXME: Calculate height / depth and propagate the changes?
459 LoadSU->Depth = NewSU->Depth = SU->Depth;
460 LoadSU->Height = NewSU->Height = SU->Height;
461 ComputeLatency(LoadSU);
462 ComputeLatency(NewSU);
463
464 SUnit *ChainPred = NULL;
465 SmallVector<SDep, 4> ChainSuccs;
466 SmallVector<SDep, 4> LoadPreds;
467 SmallVector<SDep, 4> NodePreds;
468 SmallVector<SDep, 4> NodeSuccs;
469 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
470 I != E; ++I) {
471 if (I->isCtrl)
472 ChainPred = I->Dep;
473 else if (I->Dep->Node && I->Dep->Node->isOperand(LoadNode))
474 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
475 else
476 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
477 }
478 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
479 I != E; ++I) {
480 if (I->isCtrl)
481 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
482 I->isCtrl, I->isSpecial));
483 else
484 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
485 I->isCtrl, I->isSpecial));
486 }
487
488 SU->removePred(ChainPred, true, false);
489 LoadSU->addPred(ChainPred, true, false);
490 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
491 SDep *Pred = &LoadPreds[i];
492 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
493 LoadSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
494 Pred->Reg, Pred->Cost);
495 }
496 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
497 SDep *Pred = &NodePreds[i];
498 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
499 NewSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
500 Pred->Reg, Pred->Cost);
501 }
502 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
503 SDep *Succ = &NodeSuccs[i];
504 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
505 Succ->Dep->addPred(NewSU, Succ->isCtrl, Succ->isSpecial,
506 Succ->Reg, Succ->Cost);
507 }
508 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
509 SDep *Succ = &ChainSuccs[i];
510 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
511 Succ->Dep->addPred(LoadSU, Succ->isCtrl, Succ->isSpecial,
512 Succ->Reg, Succ->Cost);
513 }
514 NewSU->addPred(LoadSU, false, false);
515
516 AvailableQueue->addNode(LoadSU);
517 AvailableQueue->addNode(NewSU);
518
519 ++NumUnfolds;
520
521 if (NewSU->NumSuccsLeft == 0) {
522 NewSU->isAvailable = true;
523 return NewSU;
524 } else
525 SU = NewSU;
526 }
527
528 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
529 NewSU = Clone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000530
531 // New SUnit has the exact same predecessors.
532 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
533 I != E; ++I)
534 if (!I->isSpecial) {
535 NewSU->addPred(I->Dep, I->isCtrl, false, I->Reg, I->Cost);
536 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
537 }
538
539 // Only copy scheduled successors. Cut them from old node's successor
540 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000541 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000542 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
543 I != E; ++I) {
544 if (I->isSpecial)
545 continue;
Evan Cheng5924bf72007-09-25 01:54:36 +0000546 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000547 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
Evan Cheng5924bf72007-09-25 01:54:36 +0000548 I->Dep->addPred(NewSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000549 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng5924bf72007-09-25 01:54:36 +0000550 }
551 }
552 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000553 SUnit *Succ = DelDeps[i].first;
554 bool isCtrl = DelDeps[i].second;
Evan Cheng5924bf72007-09-25 01:54:36 +0000555 Succ->removePred(SU, isCtrl, false);
556 }
557
558 AvailableQueue->updateNode(SU);
559 AvailableQueue->addNode(NewSU);
560
Evan Cheng1ec79b42007-09-27 07:09:03 +0000561 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000562 return NewSU;
563}
564
Evan Cheng1ec79b42007-09-27 07:09:03 +0000565/// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
566/// and move all scheduled successors of the given SUnit to the last copy.
567void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
568 const TargetRegisterClass *DestRC,
569 const TargetRegisterClass *SrcRC,
570 SmallVector<SUnit*, 2> &Copies) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000571 SUnit *CopyFromSU = NewSUnit(NULL);
572 CopyFromSU->CopySrcRC = SrcRC;
573 CopyFromSU->CopyDstRC = DestRC;
574 CopyFromSU->Depth = SU->Depth;
575 CopyFromSU->Height = SU->Height;
576
577 SUnit *CopyToSU = NewSUnit(NULL);
578 CopyToSU->CopySrcRC = DestRC;
579 CopyToSU->CopyDstRC = SrcRC;
580
581 // Only copy scheduled successors. Cut them from old node's successor
582 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000583 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000584 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
585 I != E; ++I) {
586 if (I->isSpecial)
587 continue;
Evan Cheng8e136a92007-09-26 21:36:17 +0000588 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000589 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
Evan Cheng8e136a92007-09-26 21:36:17 +0000590 I->Dep->addPred(CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000591 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng8e136a92007-09-26 21:36:17 +0000592 }
593 }
594 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000595 SUnit *Succ = DelDeps[i].first;
596 bool isCtrl = DelDeps[i].second;
Evan Cheng8e136a92007-09-26 21:36:17 +0000597 Succ->removePred(SU, isCtrl, false);
598 }
599
600 CopyFromSU->addPred(SU, false, false, Reg, -1);
601 CopyToSU->addPred(CopyFromSU, false, false, Reg, 1);
602
603 AvailableQueue->updateNode(SU);
604 AvailableQueue->addNode(CopyFromSU);
605 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000606 Copies.push_back(CopyFromSU);
607 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000608
Evan Cheng1ec79b42007-09-27 07:09:03 +0000609 ++NumCCCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000610}
611
612/// getPhysicalRegisterVT - Returns the ValueType of the physical register
613/// definition of the specified node.
614/// FIXME: Move to SelectionDAG?
615static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
616 const TargetInstrInfo *TII) {
617 const TargetInstrDescriptor &TID = TII->get(N->getTargetOpcode());
618 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
619 unsigned NumRes = TID.numDefs;
620 for (const unsigned *ImpDef = TID.ImplicitDefs; *ImpDef; ++ImpDef) {
621 if (Reg == *ImpDef)
622 break;
623 ++NumRes;
624 }
625 return N->getValueType(NumRes);
626}
627
Evan Cheng5924bf72007-09-25 01:54:36 +0000628/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
629/// scheduling of the given node to satisfy live physical register dependencies.
630/// If the specific node is the last one that's available to schedule, do
631/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000632bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
633 SmallVector<unsigned, 4> &LRegs){
Evan Cheng5924bf72007-09-25 01:54:36 +0000634 if (LiveRegs.empty())
635 return false;
636
Evan Chenge6f92252007-09-27 18:46:06 +0000637 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000638 // If this node would clobber any "live" register, then it's not ready.
Evan Cheng5924bf72007-09-25 01:54:36 +0000639 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
640 I != E; ++I) {
641 if (I->Cost < 0) {
642 unsigned Reg = I->Reg;
Evan Chenge6f92252007-09-27 18:46:06 +0000643 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
644 if (RegAdded.insert(Reg))
645 LRegs.push_back(Reg);
646 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000647 for (const unsigned *Alias = MRI->getAliasSet(Reg);
648 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000649 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
650 if (RegAdded.insert(*Alias))
651 LRegs.push_back(*Alias);
652 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000653 }
654 }
655
656 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
657 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
Evan Cheng8e136a92007-09-26 21:36:17 +0000658 if (!Node || !Node->isTargetOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000659 continue;
660 const TargetInstrDescriptor &TID = TII->get(Node->getTargetOpcode());
661 if (!TID.ImplicitDefs)
662 continue;
663 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
Evan Chenge6f92252007-09-27 18:46:06 +0000664 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
665 if (RegAdded.insert(*Reg))
666 LRegs.push_back(*Reg);
667 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000668 for (const unsigned *Alias = MRI->getAliasSet(*Reg);
669 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000670 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
671 if (RegAdded.insert(*Alias))
672 LRegs.push_back(*Alias);
673 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000674 }
675 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000676 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000677}
678
Evan Cheng1ec79b42007-09-27 07:09:03 +0000679
Evan Chengd38c22b2006-05-11 23:55:42 +0000680/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
681/// schedulers.
682void ScheduleDAGRRList::ListScheduleBottomUp() {
683 unsigned CurCycle = 0;
684 // Add root to Available queue.
Evan Cheng5924bf72007-09-25 01:54:36 +0000685 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
686 RootSU->isAvailable = true;
687 AvailableQueue->push(RootSU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000688
689 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000690 // priority. If it is not ready put it back. Schedule the node.
Evan Cheng5924bf72007-09-25 01:54:36 +0000691 SmallVector<SUnit*, 4> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000692 while (!AvailableQueue->empty()) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000693 bool Delayed = false;
694 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
Evan Cheng5924bf72007-09-25 01:54:36 +0000695 SUnit *CurSU = AvailableQueue->pop();
696 while (CurSU) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000697 if (CurSU->CycleBound <= CurCycle) {
698 SmallVector<unsigned, 4> LRegs;
699 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
Evan Cheng5924bf72007-09-25 01:54:36 +0000700 break;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000701 Delayed = true;
702 LRegsMap.insert(std::make_pair(CurSU, LRegs));
Evan Cheng5924bf72007-09-25 01:54:36 +0000703 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000704
705 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
706 NotReady.push_back(CurSU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000707 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000708 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000709
710 // All candidates are delayed due to live physical reg dependencies.
711 // Try backtracking, code duplication, or inserting cross class copies
712 // to resolve it.
713 if (Delayed && !CurSU) {
714 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
715 SUnit *TrySU = NotReady[i];
716 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
717
718 // Try unscheduling up to the point where it's safe to schedule
719 // this node.
720 unsigned LiveCycle = CurCycle;
721 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
722 unsigned Reg = LRegs[j];
723 unsigned LCycle = LiveRegCycles[Reg];
724 LiveCycle = std::min(LiveCycle, LCycle);
725 }
726 SUnit *OldSU = Sequence[LiveCycle];
727 if (!WillCreateCycle(TrySU, OldSU)) {
728 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
729 // Force the current node to be scheduled before the node that
730 // requires the physical reg dep.
731 if (OldSU->isAvailable) {
732 OldSU->isAvailable = false;
733 AvailableQueue->remove(OldSU);
734 }
735 TrySU->addPred(OldSU, true, true);
736 // If one or more successors has been unscheduled, then the current
737 // node is no longer avaialable. Schedule a successor that's now
738 // available instead.
739 if (!TrySU->isAvailable)
740 CurSU = AvailableQueue->pop();
741 else {
742 CurSU = TrySU;
743 TrySU->isPending = false;
744 NotReady.erase(NotReady.begin()+i);
745 }
746 break;
747 }
748 }
749
750 if (!CurSU) {
751 // Can't backtrace. Try duplicating the nodes that produces these
752 // "expensive to copy" values to break the dependency. In case even
753 // that doesn't work, insert cross class copies.
754 SUnit *TrySU = NotReady[0];
755 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
756 assert(LRegs.size() == 1 && "Can't handle this yet!");
757 unsigned Reg = LRegs[0];
758 SUnit *LRDef = LiveRegDefs[Reg];
Evan Cheng79e97132007-10-05 01:39:18 +0000759 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
760 if (!NewDef) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000761 // Issue expensive cross register class copies.
762 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
763 const TargetRegisterClass *RC =
764 MRI->getPhysicalRegisterRegClass(VT, Reg);
765 const TargetRegisterClass *DestRC = MRI->getCrossCopyRegClass(RC);
766 if (!DestRC) {
767 assert(false && "Don't know how to copy this physical register!");
768 abort();
769 }
770 SmallVector<SUnit*, 2> Copies;
771 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
772 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
773 << " to SU #" << Copies.front()->NodeNum << "\n";
774 TrySU->addPred(Copies.front(), true, true);
775 NewDef = Copies.back();
776 }
777
778 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
779 << " to SU #" << TrySU->NodeNum << "\n";
780 LiveRegDefs[Reg] = NewDef;
781 NewDef->addPred(TrySU, true, true);
782 TrySU->isAvailable = false;
783 CurSU = NewDef;
784 }
785
786 if (!CurSU) {
787 assert(false && "Unable to resolve live physical register dependencies!");
788 abort();
789 }
790 }
791
Evan Chengd38c22b2006-05-11 23:55:42 +0000792 // Add the nodes that aren't ready back onto the available list.
Evan Cheng5924bf72007-09-25 01:54:36 +0000793 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
794 NotReady[i]->isPending = false;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000795 // May no longer be available due to backtracking.
Evan Cheng5924bf72007-09-25 01:54:36 +0000796 if (NotReady[i]->isAvailable)
797 AvailableQueue->push(NotReady[i]);
798 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000799 NotReady.clear();
800
Evan Cheng5924bf72007-09-25 01:54:36 +0000801 if (!CurSU)
802 Sequence.push_back(0);
803 else {
804 ScheduleNodeBottomUp(CurSU, CurCycle);
805 Sequence.push_back(CurSU);
806 }
807 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000808 }
809
810 // Add entry node last
811 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000812 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000813 Sequence.push_back(Entry);
814 }
815
816 // Reverse the order if it is bottom up.
817 std::reverse(Sequence.begin(), Sequence.end());
818
819
820#ifndef NDEBUG
821 // Verify that all SUnits were scheduled.
822 bool AnyNotSched = false;
823 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Evan Cheng038dcc52007-09-28 19:24:24 +0000824 if (SUnits[i].NumSuccsLeft != 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000825 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000826 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000827 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000828 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000829 AnyNotSched = true;
830 }
831 }
832 assert(!AnyNotSched);
833#endif
834}
835
836//===----------------------------------------------------------------------===//
837// Top-Down Scheduling
838//===----------------------------------------------------------------------===//
839
840/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000841/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000842void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
843 unsigned CurCycle) {
844 // FIXME: the distance between two nodes is not always == the predecessor's
845 // latency. For example, the reader can very well read the register written
846 // by the predecessor later than the issue cycle. It also depends on the
847 // interrupt model (drain vs. freeze).
848 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
849
Evan Cheng038dcc52007-09-28 19:24:24 +0000850 --SuccSU->NumPredsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000851
852#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +0000853 if (SuccSU->NumPredsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000854 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000855 SuccSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000856 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000857 assert(0);
858 }
859#endif
860
Evan Cheng038dcc52007-09-28 19:24:24 +0000861 if (SuccSU->NumPredsLeft == 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000862 SuccSU->isAvailable = true;
863 AvailableQueue->push(SuccSU);
864 }
865}
866
867
868/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
869/// count of its successors. If a successor pending count is zero, add it to
870/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000871void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000872 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000873 DEBUG(SU->dump(&DAG));
874 SU->Cycle = CurCycle;
875
876 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000877
878 // Top down: release successors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000879 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
880 I != E; ++I)
Evan Cheng0effc3a2007-09-19 01:38:40 +0000881 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +0000882 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000883}
884
Dan Gohman54a187e2007-08-20 19:28:38 +0000885/// ListScheduleTopDown - The main loop of list scheduling for top-down
886/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +0000887void ScheduleDAGRRList::ListScheduleTopDown() {
888 unsigned CurCycle = 0;
Evan Cheng5924bf72007-09-25 01:54:36 +0000889 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
Evan Chengd38c22b2006-05-11 23:55:42 +0000890
891 // All leaves to Available queue.
892 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
893 // It is available if it has no predecessors.
894 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
895 AvailableQueue->push(&SUnits[i]);
896 SUnits[i].isAvailable = true;
897 }
898 }
899
900 // Emit the entry node first.
901 ScheduleNodeTopDown(Entry, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000902 Sequence.push_back(Entry);
903 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +0000904
905 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000906 // priority. If it is not ready put it back. Schedule the node.
Evan Chengd38c22b2006-05-11 23:55:42 +0000907 std::vector<SUnit*> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000908 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000909 SUnit *CurSU = AvailableQueue->pop();
910 while (CurSU && CurSU->CycleBound > CurCycle) {
911 NotReady.push_back(CurSU);
912 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000913 }
914
915 // Add the nodes that aren't ready back onto the available list.
916 AvailableQueue->push_all(NotReady);
917 NotReady.clear();
918
Evan Cheng5924bf72007-09-25 01:54:36 +0000919 if (!CurSU)
920 Sequence.push_back(0);
921 else {
922 ScheduleNodeTopDown(CurSU, CurCycle);
923 Sequence.push_back(CurSU);
924 }
Evan Chengd12c97d2006-05-30 18:05:39 +0000925 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000926 }
927
928
929#ifndef NDEBUG
930 // Verify that all SUnits were scheduled.
931 bool AnyNotSched = false;
932 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
933 if (!SUnits[i].isScheduled) {
934 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000935 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000936 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000937 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000938 AnyNotSched = true;
939 }
940 }
941 assert(!AnyNotSched);
942#endif
943}
944
945
946
947//===----------------------------------------------------------------------===//
948// RegReductionPriorityQueue Implementation
949//===----------------------------------------------------------------------===//
950//
951// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
952// to reduce register pressure.
953//
954namespace {
955 template<class SF>
956 class RegReductionPriorityQueue;
957
958 /// Sorting functions for the Available queue.
959 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
960 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
961 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
962 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
963
964 bool operator()(const SUnit* left, const SUnit* right) const;
965 };
966
967 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
968 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
969 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
970 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
971
972 bool operator()(const SUnit* left, const SUnit* right) const;
973 };
974} // end anonymous namespace
975
Evan Cheng961bbd32007-01-08 23:50:38 +0000976static inline bool isCopyFromLiveIn(const SUnit *SU) {
977 SDNode *N = SU->Node;
Evan Cheng8e136a92007-09-26 21:36:17 +0000978 return N && N->getOpcode() == ISD::CopyFromReg &&
Evan Cheng961bbd32007-01-08 23:50:38 +0000979 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
980}
981
Evan Chengd38c22b2006-05-11 23:55:42 +0000982namespace {
983 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000984 class VISIBILITY_HIDDEN RegReductionPriorityQueue
985 : public SchedulingPriorityQueue {
Evan Chengd38c22b2006-05-11 23:55:42 +0000986 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
987
988 public:
989 RegReductionPriorityQueue() :
990 Queue(SF(this)) {}
991
Evan Cheng5924bf72007-09-25 01:54:36 +0000992 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000993 std::vector<SUnit> &sunits) {}
Evan Cheng5924bf72007-09-25 01:54:36 +0000994
995 virtual void addNode(const SUnit *SU) {}
996
997 virtual void updateNode(const SUnit *SU) {}
998
Evan Chengd38c22b2006-05-11 23:55:42 +0000999 virtual void releaseState() {}
1000
Evan Cheng6730f032007-01-08 23:55:53 +00001001 virtual unsigned getNodePriority(const SUnit *SU) const {
Evan Chengd38c22b2006-05-11 23:55:42 +00001002 return 0;
1003 }
1004
Evan Cheng5924bf72007-09-25 01:54:36 +00001005 unsigned size() const { return Queue.size(); }
1006
Evan Chengd38c22b2006-05-11 23:55:42 +00001007 bool empty() const { return Queue.empty(); }
1008
1009 void push(SUnit *U) {
1010 Queue.push(U);
1011 }
1012 void push_all(const std::vector<SUnit *> &Nodes) {
1013 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1014 Queue.push(Nodes[i]);
1015 }
1016
1017 SUnit *pop() {
Evan Chengd12c97d2006-05-30 18:05:39 +00001018 if (empty()) return NULL;
Evan Chengd38c22b2006-05-11 23:55:42 +00001019 SUnit *V = Queue.top();
1020 Queue.pop();
1021 return V;
1022 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001023
Evan Cheng5924bf72007-09-25 01:54:36 +00001024 /// remove - This is a really inefficient way to remove a node from a
1025 /// priority queue. We should roll our own heap to make this better or
1026 /// something.
1027 void remove(SUnit *SU) {
1028 std::vector<SUnit*> Temp;
1029
1030 assert(!Queue.empty() && "Not in queue!");
1031 while (Queue.top() != SU) {
1032 Temp.push_back(Queue.top());
1033 Queue.pop();
1034 assert(!Queue.empty() && "Not in queue!");
1035 }
1036
1037 // Remove the node from the PQ.
1038 Queue.pop();
1039
1040 // Add all the other nodes back.
1041 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
1042 Queue.push(Temp[i]);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001043 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001044 };
1045
1046 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +00001047 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1048 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +00001049 // SUnitMap SDNode to SUnit mapping (n -> n).
1050 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001051
Evan Chengd38c22b2006-05-11 23:55:42 +00001052 // SUnits - The SUnits for the current graph.
1053 const std::vector<SUnit> *SUnits;
1054
1055 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001056 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001057
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001058 const TargetInstrInfo *TII;
Evan Chengd38c22b2006-05-11 23:55:42 +00001059 public:
Dan Gohman54a187e2007-08-20 19:28:38 +00001060 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001061 : TII(tii) {}
Evan Chengd38c22b2006-05-11 23:55:42 +00001062
Evan Cheng5924bf72007-09-25 01:54:36 +00001063 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001064 std::vector<SUnit> &sunits) {
1065 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +00001066 SUnits = &sunits;
1067 // Add pseudo dependency edges for two-address nodes.
Evan Chengafed73e2006-05-12 01:58:24 +00001068 AddPseudoTwoAddrDeps();
Evan Chengd38c22b2006-05-11 23:55:42 +00001069 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001070 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001071 }
1072
Evan Cheng5924bf72007-09-25 01:54:36 +00001073 void addNode(const SUnit *SU) {
1074 SethiUllmanNumbers.resize(SUnits->size(), 0);
1075 CalcNodeSethiUllmanNumber(SU);
1076 }
1077
1078 void updateNode(const SUnit *SU) {
1079 SethiUllmanNumbers[SU->NodeNum] = 0;
1080 CalcNodeSethiUllmanNumber(SU);
1081 }
1082
Evan Chengd38c22b2006-05-11 23:55:42 +00001083 void releaseState() {
1084 SUnits = 0;
1085 SethiUllmanNumbers.clear();
1086 }
1087
Evan Cheng6730f032007-01-08 23:55:53 +00001088 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001089 assert(SU->NodeNum < SethiUllmanNumbers.size());
Evan Cheng8e136a92007-09-26 21:36:17 +00001090 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Cheng961bbd32007-01-08 23:50:38 +00001091 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1092 // CopyFromReg should be close to its def because it restricts
1093 // allocation choices. But if it is a livein then perhaps we want it
1094 // closer to its uses so it can be coalesced.
1095 return 0xffff;
1096 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1097 // CopyToReg should be close to its uses to facilitate coalescing and
1098 // avoid spilling.
1099 return 0;
Evan Chengaa2d6ef2007-10-12 08:50:34 +00001100 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1101 Opc == TargetInstrInfo::INSERT_SUBREG)
1102 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1103 // facilitate coalescing.
1104 return 0;
Evan Cheng961bbd32007-01-08 23:50:38 +00001105 else if (SU->NumSuccs == 0)
1106 // If SU does not have a use, i.e. it doesn't produce a value that would
1107 // be consumed (e.g. store), then it terminates a chain of computation.
1108 // Give it a large SethiUllman number so it will be scheduled right
1109 // before its predecessors that it doesn't lengthen their live ranges.
1110 return 0xffff;
1111 else if (SU->NumPreds == 0)
1112 // If SU does not have a def, schedule it close to its uses because it
1113 // does not lengthen any live ranges.
1114 return 0;
1115 else
1116 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001117 }
1118
1119 private:
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001120 bool canClobber(SUnit *SU, SUnit *Op);
Evan Chengd38c22b2006-05-11 23:55:42 +00001121 void AddPseudoTwoAddrDeps();
Evan Cheng6730f032007-01-08 23:55:53 +00001122 void CalculateSethiUllmanNumbers();
1123 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001124 };
1125
1126
1127 template<class SF>
Dan Gohman54a187e2007-08-20 19:28:38 +00001128 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1129 : public RegReductionPriorityQueue<SF> {
Evan Cheng5924bf72007-09-25 01:54:36 +00001130 // SUnitMap SDNode to SUnit mapping (n -> n).
1131 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001132
Evan Chengd38c22b2006-05-11 23:55:42 +00001133 // SUnits - The SUnits for the current graph.
1134 const std::vector<SUnit> *SUnits;
1135
1136 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001137 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001138
1139 public:
1140 TDRegReductionPriorityQueue() {}
1141
Evan Cheng5924bf72007-09-25 01:54:36 +00001142 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001143 std::vector<SUnit> &sunits) {
1144 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +00001145 SUnits = &sunits;
1146 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001147 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001148 }
1149
Evan Cheng5924bf72007-09-25 01:54:36 +00001150 void addNode(const SUnit *SU) {
1151 SethiUllmanNumbers.resize(SUnits->size(), 0);
1152 CalcNodeSethiUllmanNumber(SU);
1153 }
1154
1155 void updateNode(const SUnit *SU) {
1156 SethiUllmanNumbers[SU->NodeNum] = 0;
1157 CalcNodeSethiUllmanNumber(SU);
1158 }
1159
Evan Chengd38c22b2006-05-11 23:55:42 +00001160 void releaseState() {
1161 SUnits = 0;
1162 SethiUllmanNumbers.clear();
1163 }
1164
Evan Cheng6730f032007-01-08 23:55:53 +00001165 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001166 assert(SU->NodeNum < SethiUllmanNumbers.size());
1167 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001168 }
1169
1170 private:
Evan Cheng6730f032007-01-08 23:55:53 +00001171 void CalculateSethiUllmanNumbers();
1172 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001173 };
1174}
1175
Evan Chengb9e3db62007-03-14 22:43:40 +00001176/// closestSucc - Returns the scheduled cycle of the successor which is
1177/// closet to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001178static unsigned closestSucc(const SUnit *SU) {
1179 unsigned MaxCycle = 0;
1180 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001181 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001182 unsigned Cycle = I->Dep->Cycle;
Evan Chengb9e3db62007-03-14 22:43:40 +00001183 // If there are bunch of CopyToRegs stacked up, they should be considered
1184 // to be at the same position.
Evan Cheng8e136a92007-09-26 21:36:17 +00001185 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
Evan Cheng0effc3a2007-09-19 01:38:40 +00001186 Cycle = closestSucc(I->Dep)+1;
Evan Chengb9e3db62007-03-14 22:43:40 +00001187 if (Cycle > MaxCycle)
1188 MaxCycle = Cycle;
1189 }
Evan Cheng28748552007-03-13 23:25:11 +00001190 return MaxCycle;
1191}
1192
Evan Chengd38c22b2006-05-11 23:55:42 +00001193// Bottom up
1194bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
David Greene4c1e6f32007-06-29 03:42:23 +00001195 // There used to be a special tie breaker here that looked for
David Greene5b6f7552007-06-29 02:48:09 +00001196 // two-address instructions and preferred the instruction with a
1197 // def&use operand. The special case triggered diagnostics when
1198 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1199 // ordering that priority_queue requires. It didn't help much anyway
1200 // because AddPseudoTwoAddrDeps already covers many of the cases
1201 // where it would have applied. In addition, it's counter-intuitive
1202 // that a tie breaker would be the first thing attempted. There's a
1203 // "real" tie breaker below that is the operation of last resort.
1204 // The fact that the "special tie breaker" would trigger when there
1205 // wasn't otherwise a tie is what broke the strict weak ordering
1206 // constraint.
Evan Cheng99f2f792006-05-13 08:22:24 +00001207
Evan Cheng6730f032007-01-08 23:55:53 +00001208 unsigned LPriority = SPQ->getNodePriority(left);
1209 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng961bbd32007-01-08 23:50:38 +00001210 if (LPriority > RPriority)
Evan Chengd38c22b2006-05-11 23:55:42 +00001211 return true;
Evan Cheng28748552007-03-13 23:25:11 +00001212 else if (LPriority == RPriority) {
Dan Gohmane131e3a2007-04-26 19:40:56 +00001213 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
Evan Cheng28748552007-03-13 23:25:11 +00001214 // e.g.
1215 // t1 = op t2, c1
1216 // t3 = op t4, c2
1217 //
1218 // and the following instructions are both ready.
1219 // t2 = op c3
1220 // t4 = op c4
1221 //
1222 // Then schedule t2 = op first.
1223 // i.e.
1224 // t4 = op c4
1225 // t2 = op c3
1226 // t1 = op t2, c1
1227 // t3 = op t4, c2
1228 //
1229 // This creates more short live intervals.
1230 unsigned LDist = closestSucc(left);
1231 unsigned RDist = closestSucc(right);
1232 if (LDist < RDist)
Evan Chengd38c22b2006-05-11 23:55:42 +00001233 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001234 else if (LDist == RDist) {
Evan Chengf72693f2007-09-28 19:37:35 +00001235 if (left->Height > right->Height)
Evan Chengd38c22b2006-05-11 23:55:42 +00001236 return true;
Evan Chengf72693f2007-09-28 19:37:35 +00001237 else if (left->Height == right->Height)
1238 if (left->Depth < right->Depth)
Evan Cheng99f2f792006-05-13 08:22:24 +00001239 return true;
Evan Chengf72693f2007-09-28 19:37:35 +00001240 else if (left->Depth == right->Depth)
1241 if (left->CycleBound > right->CycleBound)
Evan Cheng28748552007-03-13 23:25:11 +00001242 return true;
Evan Chengb9e3db62007-03-14 22:43:40 +00001243 }
Evan Cheng28748552007-03-13 23:25:11 +00001244 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001245 return false;
1246}
1247
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001248template<class SF>
1249bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
1250 if (SU->isTwoAddress) {
1251 unsigned Opc = SU->Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001252 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001253 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
1254 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001255 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001256 SDNode *DU = SU->Node->getOperand(i).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001257 if (Op == (*SUnitMap)[DU][SU->InstanceNo])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001258 return true;
1259 }
1260 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001261 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001262 return false;
1263}
1264
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001265
Evan Chenga5e595d2007-09-28 22:32:30 +00001266/// hasCopyToRegUse - Return true if SU has a value successor that is a
1267/// CopyToReg node.
1268static bool hasCopyToRegUse(SUnit *SU) {
1269 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1270 I != E; ++I) {
1271 if (I->isCtrl) continue;
1272 SUnit *SuccSU = I->Dep;
1273 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1274 return true;
1275 }
1276 return false;
1277}
1278
Evan Chengd38c22b2006-05-11 23:55:42 +00001279/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1280/// it as a def&use operand. Add a pseudo control edge from it to the other
1281/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00001282/// first (lower in the schedule). If both nodes are two-address, favor the
1283/// one that has a CopyToReg use (more likely to be a loop induction update).
1284/// If both are two-address, but one is commutable while the other is not
1285/// commutable, favor the one that's not commutable.
Evan Chengd38c22b2006-05-11 23:55:42 +00001286template<class SF>
1287void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001288 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1289 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1290 if (!SU->isTwoAddress)
1291 continue;
1292
1293 SDNode *Node = SU->Node;
Evan Chenga5e595d2007-09-28 22:32:30 +00001294 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001295 continue;
1296
1297 unsigned Opc = Node->getTargetOpcode();
Evan Cheng100c8d62007-09-13 00:06:00 +00001298 unsigned NumRes = TII->getNumDefs(Opc);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001299 unsigned NumOps = ScheduleDAG::CountOperands(Node);
1300 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +00001301 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001302 SDNode *DU = SU->Node->getOperand(j).Val;
Evan Cheng5924bf72007-09-25 01:54:36 +00001303 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
Evan Chengf24d15f2006-11-06 21:33:46 +00001304 if (!DUSU) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001305 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1306 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001307 if (I->isCtrl) continue;
1308 SUnit *SuccSU = I->Dep;
Dan Gohman2682bb62007-10-05 14:11:58 +00001309 // Don't constrain nodes with implicit defs. It can create cycles
Evan Cheng5924bf72007-09-25 01:54:36 +00001310 // plus it may increase register pressures.
Evan Chenga5e595d2007-09-28 22:32:30 +00001311 if (SuccSU == SU || SuccSU->hasPhysRegDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001312 continue;
1313 // Be conservative. Ignore if nodes aren't at the same depth.
1314 if (SuccSU->Depth != SU->Depth)
1315 continue;
Evan Chengaa2d6ef2007-10-12 08:50:34 +00001316 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1317 continue;
1318 // Don't constraint extract_subreg / insert_subreg these may be
1319 // coalesced away. We don't them close to their uses.
1320 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1321 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1322 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1323 continue;
Evan Cheng5924bf72007-09-25 01:54:36 +00001324 if ((!canClobber(SuccSU, DUSU) ||
Evan Chenga5e595d2007-09-28 22:32:30 +00001325 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
Evan Cheng5924bf72007-09-25 01:54:36 +00001326 (!SU->isCommutable && SuccSU->isCommutable)) &&
1327 !isReachable(SuccSU, SU)) {
1328 DOUT << "Adding an edge from SU # " << SU->NodeNum
1329 << " to SU #" << SuccSU->NodeNum << "\n";
1330 SU->addPred(SuccSU, true, true);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001331 }
1332 }
1333 }
1334 }
1335 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001336}
1337
Evan Cheng6730f032007-01-08 23:55:53 +00001338/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001339/// Smaller number is the higher priority.
1340template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001341unsigned BURegReductionPriorityQueue<SF>::
1342CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001343 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001344 if (SethiUllmanNumber != 0)
1345 return SethiUllmanNumber;
1346
Evan Cheng961bbd32007-01-08 23:50:38 +00001347 unsigned Extra = 0;
1348 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1349 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001350 if (I->isCtrl) continue; // ignore chain preds
1351 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001352 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Cheng961bbd32007-01-08 23:50:38 +00001353 if (PredSethiUllman > SethiUllmanNumber) {
1354 SethiUllmanNumber = PredSethiUllman;
1355 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001356 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001357 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001358 }
Evan Cheng961bbd32007-01-08 23:50:38 +00001359
1360 SethiUllmanNumber += Extra;
1361
1362 if (SethiUllmanNumber == 0)
1363 SethiUllmanNumber = 1;
Evan Chengd38c22b2006-05-11 23:55:42 +00001364
1365 return SethiUllmanNumber;
1366}
1367
Evan Cheng6730f032007-01-08 23:55:53 +00001368/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1369/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001370template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001371void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001372 SethiUllmanNumbers.assign(SUnits->size(), 0);
1373
1374 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001375 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001376}
1377
1378static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1379 unsigned Sum = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001380 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1381 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001382 SUnit *SuccSU = I->Dep;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001383 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1384 EE = SuccSU->Preds.end(); II != EE; ++II) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001385 SUnit *PredSU = II->Dep;
Evan Chengd38c22b2006-05-11 23:55:42 +00001386 if (!PredSU->isScheduled)
Evan Cheng5924bf72007-09-25 01:54:36 +00001387 ++Sum;
Evan Chengd38c22b2006-05-11 23:55:42 +00001388 }
1389 }
1390
1391 return Sum;
1392}
1393
1394
1395// Top down
1396bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00001397 unsigned LPriority = SPQ->getNodePriority(left);
1398 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng8e136a92007-09-26 21:36:17 +00001399 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1400 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00001401 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1402 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1403 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1404 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1405
1406 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1407 return false;
1408 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1409 return true;
1410
1411 // Special tie breaker: if two nodes share a operand, the one that use it
1412 // as a def&use operand is preferred.
1413 if (LIsTarget && RIsTarget) {
1414 if (left->isTwoAddress && !right->isTwoAddress) {
1415 SDNode *DUNode = left->Node->getOperand(0).Val;
1416 if (DUNode->isOperand(right->Node))
1417 RBonus += 2;
1418 }
1419 if (!left->isTwoAddress && right->isTwoAddress) {
1420 SDNode *DUNode = right->Node->getOperand(0).Val;
1421 if (DUNode->isOperand(left->Node))
1422 LBonus += 2;
1423 }
1424 }
1425 if (LIsFloater)
1426 LBonus -= 2;
1427 if (RIsFloater)
1428 RBonus -= 2;
1429 if (left->NumSuccs == 1)
1430 LBonus += 2;
1431 if (right->NumSuccs == 1)
1432 RBonus += 2;
1433
1434 if (LPriority+LBonus < RPriority+RBonus)
1435 return true;
1436 else if (LPriority == RPriority)
1437 if (left->Depth < right->Depth)
1438 return true;
1439 else if (left->Depth == right->Depth)
1440 if (left->NumSuccsLeft > right->NumSuccsLeft)
1441 return true;
1442 else if (left->NumSuccsLeft == right->NumSuccsLeft)
1443 if (left->CycleBound > right->CycleBound)
1444 return true;
1445 return false;
1446}
1447
Evan Cheng6730f032007-01-08 23:55:53 +00001448/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001449/// Smaller number is the higher priority.
1450template<class SF>
Chris Lattner296a83c2007-02-01 04:55:59 +00001451unsigned TDRegReductionPriorityQueue<SF>::
1452CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001453 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001454 if (SethiUllmanNumber != 0)
1455 return SethiUllmanNumber;
1456
Evan Cheng8e136a92007-09-26 21:36:17 +00001457 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001458 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Evan Cheng961bbd32007-01-08 23:50:38 +00001459 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001460 else if (SU->NumSuccsLeft == 0)
1461 // If SU does not have a use, i.e. it doesn't produce a value that would
1462 // be consumed (e.g. store), then it terminates a chain of computation.
Chris Lattner296a83c2007-02-01 04:55:59 +00001463 // Give it a small SethiUllman number so it will be scheduled right before
1464 // its predecessors that it doesn't lengthen their live ranges.
Evan Cheng961bbd32007-01-08 23:50:38 +00001465 SethiUllmanNumber = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001466 else if (SU->NumPredsLeft == 0 &&
1467 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
Evan Cheng961bbd32007-01-08 23:50:38 +00001468 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001469 else {
1470 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001471 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1472 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001473 if (I->isCtrl) continue; // ignore chain preds
1474 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001475 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001476 if (PredSethiUllman > SethiUllmanNumber) {
1477 SethiUllmanNumber = PredSethiUllman;
1478 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001479 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001480 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001481 }
1482
1483 SethiUllmanNumber += Extra;
1484 }
1485
1486 return SethiUllmanNumber;
1487}
1488
Evan Cheng6730f032007-01-08 23:55:53 +00001489/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1490/// scheduling units.
Evan Chengd38c22b2006-05-11 23:55:42 +00001491template<class SF>
Evan Cheng6730f032007-01-08 23:55:53 +00001492void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001493 SethiUllmanNumbers.assign(SUnits->size(), 0);
1494
1495 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001496 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001497}
1498
1499//===----------------------------------------------------------------------===//
1500// Public Constructor Functions
1501//===----------------------------------------------------------------------===//
1502
Jim Laskey03593f72006-08-01 18:29:48 +00001503llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1504 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001505 MachineBasicBlock *BB) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001506 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
Jim Laskey95eda5b2006-08-01 14:21:23 +00001507 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001508 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
Evan Chengd38c22b2006-05-11 23:55:42 +00001509}
1510
Jim Laskey03593f72006-08-01 18:29:48 +00001511llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1512 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001513 MachineBasicBlock *BB) {
Jim Laskey95eda5b2006-08-01 14:21:23 +00001514 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
Chris Lattner296a83c2007-02-01 04:55:59 +00001515 new TDRegReductionPriorityQueue<td_ls_rr_sort>());
Evan Chengd38c22b2006-05-11 23:55:42 +00001516}
1517