1 //===----- ScheduleDAGFast.cpp - Fast poor list scheduler -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a fast scheduler.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "pre-RA-sched"
15 #include "llvm/CodeGen/ScheduleDAG.h"
16 #include "llvm/CodeGen/SchedulerRegistry.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/CommandLine.h"
29 STATISTIC(NumUnfolds, "Number of nodes unfolded");
30 STATISTIC(NumDups, "Number of duplicated nodes");
31 STATISTIC(NumCCCopies, "Number of cross class copies");
33 static RegisterScheduler
34 fastDAGScheduler("fast", "Fast suboptimal list scheduling",
35 createFastDAGScheduler);
38 /// FastPriorityQueue - A degenerate priority queue that considers
39 /// all nodes to have the same priority.
41 struct VISIBILITY_HIDDEN FastPriorityQueue {
42 SmallVector<SUnit *, 16> Queue;
44 bool empty() const { return Queue.empty(); }
51 if (empty()) return NULL;
52 SUnit *V = Queue.back();
58 //===----------------------------------------------------------------------===//
59 /// ScheduleDAGFast - The actual "fast" list scheduler implementation.
61 class VISIBILITY_HIDDEN ScheduleDAGFast : public ScheduleDAG {
63 /// AvailableQueue - The priority queue to use for the available SUnits.
64 FastPriorityQueue AvailableQueue;
66 /// LiveRegDefs - A set of physical registers and their definition
67 /// that are "live". These nodes must be scheduled before any other nodes that
68 /// modifies the registers can be scheduled.
70 std::vector<SUnit*> LiveRegDefs;
71 std::vector<unsigned> LiveRegCycles;
74 ScheduleDAGFast(SelectionDAG *dag, MachineBasicBlock *bb,
75 const TargetMachine &tm)
76 : ScheduleDAG(dag, bb, tm) {}
80 /// AddPred - This adds the specified node X as a predecessor of
81 /// the current node Y if not already.
82 /// This returns true if this is a new predecessor.
83 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
84 unsigned PhyReg = 0, int Cost = 1);
86 /// RemovePred - This removes the specified node N from the predecessors of
87 /// the current node M.
88 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
91 void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
92 void ScheduleNodeBottomUp(SUnit*, unsigned);
93 SUnit *CopyAndMoveSuccessors(SUnit*);
94 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
95 const TargetRegisterClass*,
96 const TargetRegisterClass*,
97 SmallVector<SUnit*, 2>&);
98 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
99 void ListScheduleBottomUp();
101 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
102 SUnit *CreateNewSUnit(SDNode *N) {
103 SUnit *NewNode = NewSUnit(N);
107 /// CreateClone - Creates a new SUnit from an existing one.
108 SUnit *CreateClone(SUnit *N) {
109 SUnit *NewNode = Clone(N);
113 } // end anonymous namespace
116 /// Schedule - Schedule the DAG using list scheduling.
117 void ScheduleDAGFast::Schedule() {
118 DOUT << "********** List Scheduling **********\n";
121 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
122 LiveRegCycles.resize(TRI->getNumRegs(), 0);
124 // Build scheduling units.
127 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
128 SUnits[su].dumpAll(this));
130 // Execute the actual scheduling loop.
131 ListScheduleBottomUp();
134 //===----------------------------------------------------------------------===//
135 // Bottom-Up Scheduling
136 //===----------------------------------------------------------------------===//
138 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
139 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
140 void ScheduleDAGFast::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
141 --PredSU->NumSuccsLeft;
144 if (PredSU->NumSuccsLeft < 0) {
145 cerr << "*** Scheduling failed! ***\n";
147 cerr << " has been released too many times!\n";
152 if (PredSU->NumSuccsLeft == 0) {
153 PredSU->isAvailable = true;
154 AvailableQueue.push(PredSU);
158 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
159 /// count of its predecessors. If a predecessor pending count is zero, add it to
160 /// the Available queue.
161 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
162 DOUT << "*** Scheduling [" << CurCycle << "]: ";
163 DEBUG(SU->dump(this));
164 SU->Cycle = CurCycle;
166 // Bottom up: release predecessors
167 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
169 ReleasePred(SU, I->Dep, I->isCtrl);
171 // This is a physical register dependency and it's impossible or
172 // expensive to copy the register. Make sure nothing that can
173 // clobber the register is scheduled between the predecessor and
175 if (!LiveRegDefs[I->Reg]) {
177 LiveRegDefs[I->Reg] = I->Dep;
178 LiveRegCycles[I->Reg] = CurCycle;
183 // Release all the implicit physical register defs that are live.
184 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
187 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
188 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
189 assert(LiveRegDefs[I->Reg] == SU &&
190 "Physical register dependency violated?");
192 LiveRegDefs[I->Reg] = NULL;
193 LiveRegCycles[I->Reg] = 0;
198 SU->isScheduled = true;
201 /// AddPred - adds an edge from SUnit X to SUnit Y.
202 bool ScheduleDAGFast::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
203 unsigned PhyReg, int Cost) {
204 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
207 /// RemovePred - This removes the specified node N from the predecessors of
208 /// the current node M.
209 bool ScheduleDAGFast::RemovePred(SUnit *M, SUnit *N,
210 bool isCtrl, bool isSpecial) {
211 return M->removePred(N, isCtrl, isSpecial);
214 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
215 /// successors to the newly created node.
216 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
217 if (SU->getNode()->getFlaggedNode())
220 SDNode *N = SU->getNode();
225 bool TryUnfold = false;
226 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
227 MVT VT = N->getValueType(i);
230 else if (VT == MVT::Other)
233 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
234 const SDValue &Op = N->getOperand(i);
235 MVT VT = Op.getNode()->getValueType(Op.getResNo());
241 SmallVector<SDNode*, 2> NewNodes;
242 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
245 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
246 assert(NewNodes.size() == 2 && "Expected a load folding node!");
249 SDNode *LoadNode = NewNodes[0];
250 unsigned NumVals = N->getNumValues();
251 unsigned OldNumVals = SU->getNode()->getNumValues();
252 for (unsigned i = 0; i != NumVals; ++i)
253 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
254 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
255 SDValue(LoadNode, 1));
257 SUnit *NewSU = CreateNewSUnit(N);
258 assert(N->getNodeId() == -1 && "Node already inserted!");
259 N->setNodeId(NewSU->NodeNum);
261 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
262 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
263 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
264 NewSU->isTwoAddress = true;
268 if (TID.isCommutable())
269 NewSU->isCommutable = true;
270 // FIXME: Calculate height / depth and propagate the changes?
271 NewSU->Depth = SU->Depth;
272 NewSU->Height = SU->Height;
274 // LoadNode may already exist. This can happen when there is another
275 // load from the same location and producing the same type of value
276 // but it has different alignment or volatileness.
277 bool isNewLoad = true;
279 if (LoadNode->getNodeId() != -1) {
280 LoadSU = &SUnits[LoadNode->getNodeId()];
283 LoadSU = CreateNewSUnit(LoadNode);
284 LoadNode->setNodeId(LoadSU->NodeNum);
286 LoadSU->Depth = SU->Depth;
287 LoadSU->Height = SU->Height;
290 SUnit *ChainPred = NULL;
291 SmallVector<SDep, 4> ChainSuccs;
292 SmallVector<SDep, 4> LoadPreds;
293 SmallVector<SDep, 4> NodePreds;
294 SmallVector<SDep, 4> NodeSuccs;
295 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
299 else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
300 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
302 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
304 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
307 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
308 I->isCtrl, I->isSpecial));
310 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
311 I->isCtrl, I->isSpecial));
315 RemovePred(SU, ChainPred, true, false);
317 AddPred(LoadSU, ChainPred, true, false);
319 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
320 SDep *Pred = &LoadPreds[i];
321 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
323 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
324 Pred->Reg, Pred->Cost);
327 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
328 SDep *Pred = &NodePreds[i];
329 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
330 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
331 Pred->Reg, Pred->Cost);
333 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
334 SDep *Succ = &NodeSuccs[i];
335 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
336 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
337 Succ->Reg, Succ->Cost);
339 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
340 SDep *Succ = &ChainSuccs[i];
341 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
343 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
344 Succ->Reg, Succ->Cost);
348 AddPred(NewSU, LoadSU, false, false);
353 if (NewSU->NumSuccsLeft == 0) {
354 NewSU->isAvailable = true;
360 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
361 NewSU = CreateClone(SU);
363 // New SUnit has the exact same predecessors.
364 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
367 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
368 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
371 // Only copy scheduled successors. Cut them from old node's successor
372 // list and move them over.
373 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
374 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
378 if (I->Dep->isScheduled) {
379 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
380 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
381 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
384 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
385 SUnit *Succ = DelDeps[i].first;
386 bool isCtrl = DelDeps[i].second;
387 RemovePred(Succ, SU, isCtrl, false);
394 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
395 /// and move all scheduled successors of the given SUnit to the last copy.
396 void ScheduleDAGFast::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
397 const TargetRegisterClass *DestRC,
398 const TargetRegisterClass *SrcRC,
399 SmallVector<SUnit*, 2> &Copies) {
400 SUnit *CopyFromSU = CreateNewSUnit(NULL);
401 CopyFromSU->CopySrcRC = SrcRC;
402 CopyFromSU->CopyDstRC = DestRC;
404 SUnit *CopyToSU = CreateNewSUnit(NULL);
405 CopyToSU->CopySrcRC = DestRC;
406 CopyToSU->CopyDstRC = SrcRC;
408 // Only copy scheduled successors. Cut them from old node's successor
409 // list and move them over.
410 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
411 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
415 if (I->Dep->isScheduled) {
416 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
417 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
420 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
421 SUnit *Succ = DelDeps[i].first;
422 bool isCtrl = DelDeps[i].second;
423 RemovePred(Succ, SU, isCtrl, false);
426 AddPred(CopyFromSU, SU, false, false, Reg, -1);
427 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
429 Copies.push_back(CopyFromSU);
430 Copies.push_back(CopyToSU);
435 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
436 /// definition of the specified node.
437 /// FIXME: Move to SelectionDAG?
438 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
439 const TargetInstrInfo *TII) {
440 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
441 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
442 unsigned NumRes = TID.getNumDefs();
443 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
448 return N->getValueType(NumRes);
451 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
452 /// scheduling of the given node to satisfy live physical register dependencies.
453 /// If the specific node is the last one that's available to schedule, do
454 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
455 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
456 SmallVector<unsigned, 4> &LRegs){
457 if (NumLiveRegs == 0)
460 SmallSet<unsigned, 4> RegAdded;
461 // If this node would clobber any "live" register, then it's not ready.
462 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
465 unsigned Reg = I->Reg;
466 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
467 if (RegAdded.insert(Reg))
468 LRegs.push_back(Reg);
470 for (const unsigned *Alias = TRI->getAliasSet(Reg);
472 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
473 if (RegAdded.insert(*Alias))
474 LRegs.push_back(*Alias);
479 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
480 if (!Node->isMachineOpcode())
482 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
483 if (!TID.ImplicitDefs)
485 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
486 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
487 if (RegAdded.insert(*Reg))
488 LRegs.push_back(*Reg);
490 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
492 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
493 if (RegAdded.insert(*Alias))
494 LRegs.push_back(*Alias);
498 return !LRegs.empty();
502 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
504 void ScheduleDAGFast::ListScheduleBottomUp() {
505 unsigned CurCycle = 0;
506 // Add root to Available queue.
507 if (!SUnits.empty()) {
508 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
509 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
510 RootSU->isAvailable = true;
511 AvailableQueue.push(RootSU);
514 // While Available queue is not empty, grab the node with the highest
515 // priority. If it is not ready put it back. Schedule the node.
516 SmallVector<SUnit*, 4> NotReady;
517 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
518 Sequence.reserve(SUnits.size());
519 while (!AvailableQueue.empty()) {
520 bool Delayed = false;
522 SUnit *CurSU = AvailableQueue.pop();
524 SmallVector<unsigned, 4> LRegs;
525 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
528 LRegsMap.insert(std::make_pair(CurSU, LRegs));
530 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
531 NotReady.push_back(CurSU);
532 CurSU = AvailableQueue.pop();
535 // All candidates are delayed due to live physical reg dependencies.
536 // Try code duplication or inserting cross class copies
538 if (Delayed && !CurSU) {
540 // Try duplicating the nodes that produces these
541 // "expensive to copy" values to break the dependency. In case even
542 // that doesn't work, insert cross class copies.
543 SUnit *TrySU = NotReady[0];
544 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
545 assert(LRegs.size() == 1 && "Can't handle this yet!");
546 unsigned Reg = LRegs[0];
547 SUnit *LRDef = LiveRegDefs[Reg];
548 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
550 // Issue expensive cross register class copies.
551 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
552 const TargetRegisterClass *RC =
553 TRI->getPhysicalRegisterRegClass(Reg, VT);
554 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
556 assert(false && "Don't know how to copy this physical register!");
559 SmallVector<SUnit*, 2> Copies;
560 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
561 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
562 << " to SU #" << Copies.front()->NodeNum << "\n";
563 AddPred(TrySU, Copies.front(), true, true);
564 NewDef = Copies.back();
567 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
568 << " to SU #" << TrySU->NodeNum << "\n";
569 LiveRegDefs[Reg] = NewDef;
570 AddPred(NewDef, TrySU, true, true);
571 TrySU->isAvailable = false;
576 assert(false && "Unable to resolve live physical register dependencies!");
581 // Add the nodes that aren't ready back onto the available list.
582 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
583 NotReady[i]->isPending = false;
584 // May no longer be available due to backtracking.
585 if (NotReady[i]->isAvailable)
586 AvailableQueue.push(NotReady[i]);
591 Sequence.push_back(0);
593 ScheduleNodeBottomUp(CurSU, CurCycle);
594 Sequence.push_back(CurSU);
599 // Reverse the order if it is bottom up.
600 std::reverse(Sequence.begin(), Sequence.end());
604 // Verify that all SUnits were scheduled.
605 bool AnyNotSched = false;
606 unsigned DeadNodes = 0;
608 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
609 if (!SUnits[i].isScheduled) {
610 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
615 cerr << "*** List scheduling failed! ***\n";
616 SUnits[i].dump(this);
617 cerr << "has not been scheduled!\n";
620 if (SUnits[i].NumSuccsLeft != 0) {
622 cerr << "*** List scheduling failed! ***\n";
623 SUnits[i].dump(this);
624 cerr << "has successors left!\n";
628 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
631 assert(!AnyNotSched);
632 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
633 "The number of nodes scheduled doesn't match the expected number!");
637 //===----------------------------------------------------------------------===//
638 // Public Constructor Functions
639 //===----------------------------------------------------------------------===//
641 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS,
643 const TargetMachine *TM,
644 MachineBasicBlock *BB, bool) {
645 return new ScheduleDAGFast(DAG, BB, *TM);