1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction 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 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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "ScheduleDAGSDNodes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
38 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
39 STATISTIC(NumUnfolds, "Number of nodes unfolded");
40 STATISTIC(NumDups, "Number of duplicated nodes");
41 STATISTIC(NumPRCopies, "Number of physical register copies");
43 static RegisterScheduler
44 burrListDAGScheduler("list-burr",
45 "Bottom-up register reduction list scheduling",
46 createBURRListDAGScheduler);
47 static RegisterScheduler
48 tdrListrDAGScheduler("list-tdrr",
49 "Top-down register reduction list scheduling",
50 createTDRRListDAGScheduler);
51 static RegisterScheduler
52 sourceListDAGScheduler("source",
53 "Similar to list-burr but schedules in source "
54 "order when possible",
55 createSourceListDAGScheduler);
57 static RegisterScheduler
58 hybridListDAGScheduler("list-hybrid",
59 "Bottom-up register pressure aware list scheduling "
60 "which tries to balance latency and register pressure",
61 createHybridListDAGScheduler);
63 static RegisterScheduler
64 ILPListDAGScheduler("list-ilp",
65 "Bottom-up register pressure aware list scheduling "
66 "which tries to balance ILP and register pressure",
67 createILPListDAGScheduler);
69 static cl::opt<bool> EnableSchedCycles(
70 "enable-sched-cycles",
71 cl::desc("Enable cycle-level precision during preRA scheduling"),
72 cl::init(false), cl::Hidden);
75 //===----------------------------------------------------------------------===//
76 /// ScheduleDAGRRList - The actual register reduction list scheduler
77 /// implementation. This supports both top-down and bottom-up scheduling.
79 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
81 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
85 /// NeedLatency - True if the scheduler will make use of latency information.
89 /// AvailableQueue - The priority queue to use for the available SUnits.
90 SchedulingPriorityQueue *AvailableQueue;
92 /// PendingQueue - This contains all of the instructions whose operands have
93 /// been issued, but their results are not ready yet (due to the latency of
94 /// the operation). Once the operands becomes available, the instruction is
95 /// added to the AvailableQueue.
96 std::vector<SUnit*> PendingQueue;
98 /// HazardRec - The hazard recognizer to use.
99 ScheduleHazardRecognizer *HazardRec;
101 /// CurCycle - The current scheduler state corresponds to this cycle.
104 /// MinAvailableCycle - Cycle of the soonest available instruction.
105 unsigned MinAvailableCycle;
107 /// LiveRegDefs - A set of physical registers and their definition
108 /// that are "live". These nodes must be scheduled before any other nodes that
109 /// modifies the registers can be scheduled.
110 unsigned NumLiveRegs;
111 std::vector<SUnit*> LiveRegDefs;
112 std::vector<SUnit*> LiveRegGens;
114 /// Topo - A topological ordering for SUnits which permits fast IsReachable
115 /// and similar queries.
116 ScheduleDAGTopologicalSort Topo;
119 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
120 SchedulingPriorityQueue *availqueue,
121 CodeGenOpt::Level OptLevel)
122 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
123 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
126 const TargetMachine &tm = mf.getTarget();
127 if (EnableSchedCycles && OptLevel != CodeGenOpt::None)
128 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
130 HazardRec = new ScheduleHazardRecognizer();
133 ~ScheduleDAGRRList() {
135 delete AvailableQueue;
140 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
142 /// IsReachable - Checks if SU is reachable from TargetSU.
143 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
144 return Topo.IsReachable(SU, TargetSU);
147 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
149 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
150 return Topo.WillCreateCycle(SU, TargetSU);
153 /// AddPred - adds a predecessor edge to SUnit SU.
154 /// This returns true if this is a new predecessor.
155 /// Updates the topological ordering if required.
156 void AddPred(SUnit *SU, const SDep &D) {
157 Topo.AddPred(SU, D.getSUnit());
161 /// RemovePred - removes a predecessor edge from SUnit SU.
162 /// This returns true if an edge was removed.
163 /// Updates the topological ordering if required.
164 void RemovePred(SUnit *SU, const SDep &D) {
165 Topo.RemovePred(SU, D.getSUnit());
170 bool isReady(SUnit *SU) {
171 return !EnableSchedCycles || !AvailableQueue->hasReadyFilter() ||
172 AvailableQueue->isReady(SU);
175 void ReleasePred(SUnit *SU, const SDep *PredEdge);
176 void ReleasePredecessors(SUnit *SU);
177 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
178 void ReleaseSuccessors(SUnit *SU);
179 void ReleasePending();
180 void AdvanceToCycle(unsigned NextCycle);
181 void AdvancePastStalls(SUnit *SU);
182 void EmitNode(SUnit *SU);
183 void ScheduleNodeBottomUp(SUnit*);
184 void CapturePred(SDep *PredEdge);
185 void UnscheduleNodeBottomUp(SUnit*);
186 void RestoreHazardCheckerBottomUp();
187 void BacktrackBottomUp(SUnit*, SUnit*);
188 SUnit *CopyAndMoveSuccessors(SUnit*);
189 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
190 const TargetRegisterClass*,
191 const TargetRegisterClass*,
192 SmallVector<SUnit*, 2>&);
193 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
195 SUnit *PickNodeToScheduleBottomUp();
196 void ListScheduleBottomUp();
198 void ScheduleNodeTopDown(SUnit*);
199 void ListScheduleTopDown();
202 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
203 /// Updates the topological ordering if required.
204 SUnit *CreateNewSUnit(SDNode *N) {
205 unsigned NumSUnits = SUnits.size();
206 SUnit *NewNode = NewSUnit(N);
207 // Update the topological ordering.
208 if (NewNode->NodeNum >= NumSUnits)
209 Topo.InitDAGTopologicalSorting();
213 /// CreateClone - Creates a new SUnit from an existing one.
214 /// Updates the topological ordering if required.
215 SUnit *CreateClone(SUnit *N) {
216 unsigned NumSUnits = SUnits.size();
217 SUnit *NewNode = Clone(N);
218 // Update the topological ordering.
219 if (NewNode->NodeNum >= NumSUnits)
220 Topo.InitDAGTopologicalSorting();
224 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
225 /// need actual latency information but the hybrid scheduler does.
226 bool ForceUnitLatencies() const {
230 } // end anonymous namespace
233 /// Schedule - Schedule the DAG using list scheduling.
234 void ScheduleDAGRRList::Schedule() {
236 << "********** List Scheduling BB#" << BB->getNumber()
237 << " '" << BB->getName() << "' **********\n");
240 MinAvailableCycle = EnableSchedCycles ? UINT_MAX : 0;
242 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
243 LiveRegGens.resize(TRI->getNumRegs(), NULL);
245 // Build the scheduling graph.
246 BuildSchedGraph(NULL);
248 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
249 SUnits[su].dumpAll(this));
250 Topo.InitDAGTopologicalSorting();
252 AvailableQueue->initNodes(SUnits);
256 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
258 ListScheduleBottomUp();
260 ListScheduleTopDown();
262 AvailableQueue->releaseState();
265 //===----------------------------------------------------------------------===//
266 // Bottom-Up Scheduling
267 //===----------------------------------------------------------------------===//
269 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
270 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
271 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
272 SUnit *PredSU = PredEdge->getSUnit();
275 if (PredSU->NumSuccsLeft == 0) {
276 dbgs() << "*** Scheduling failed! ***\n";
278 dbgs() << " has been released too many times!\n";
282 --PredSU->NumSuccsLeft;
284 if (!ForceUnitLatencies()) {
285 // Updating predecessor's height. This is now the cycle when the
286 // predecessor can be scheduled without causing a pipeline stall.
287 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
290 // If all the node's successors are scheduled, this node is ready
291 // to be scheduled. Ignore the special EntrySU node.
292 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
293 PredSU->isAvailable = true;
295 unsigned Height = PredSU->getHeight();
296 if (Height < MinAvailableCycle)
297 MinAvailableCycle = Height;
300 AvailableQueue->push(PredSU);
302 // CapturePred and others may have left the node in the pending queue, avoid
304 else if (!PredSU->isPending) {
305 PredSU->isPending = true;
306 PendingQueue.push_back(PredSU);
311 /// Call ReleasePred for each predecessor, then update register live def/gen.
312 /// Always update LiveRegDefs for a register dependence even if the current SU
313 /// also defines the register. This effectively create one large live range
314 /// across a sequence of two-address node. This is important because the
315 /// entire chain must be scheduled together. Example:
318 /// flags = (2) addc flags
319 /// flags = (1) addc flags
323 /// LiveRegDefs[flags] = 3
324 /// LiveRegGens[flags] = 1
326 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
327 /// interference on flags.
328 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
329 // Bottom up: release predecessors
330 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
332 ReleasePred(SU, &*I);
333 if (I->isAssignedRegDep()) {
334 // This is a physical register dependency and it's impossible or
335 // expensive to copy the register. Make sure nothing that can
336 // clobber the register is scheduled between the predecessor and
338 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
339 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
340 "interference on register dependence");
341 LiveRegDefs[I->getReg()] = I->getSUnit();
342 if (!LiveRegGens[I->getReg()]) {
344 LiveRegGens[I->getReg()] = SU;
350 /// Check to see if any of the pending instructions are ready to issue. If
351 /// so, add them to the available queue.
352 void ScheduleDAGRRList::ReleasePending() {
353 if (!EnableSchedCycles) {
354 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
358 // If the available queue is empty, it is safe to reset MinAvailableCycle.
359 if (AvailableQueue->empty())
360 MinAvailableCycle = UINT_MAX;
362 // Check to see if any of the pending instructions are ready to issue. If
363 // so, add them to the available queue.
364 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
365 unsigned ReadyCycle =
366 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
367 if (ReadyCycle < MinAvailableCycle)
368 MinAvailableCycle = ReadyCycle;
370 if (PendingQueue[i]->isAvailable) {
371 if (!isReady(PendingQueue[i]))
373 AvailableQueue->push(PendingQueue[i]);
375 PendingQueue[i]->isPending = false;
376 PendingQueue[i] = PendingQueue.back();
377 PendingQueue.pop_back();
382 /// Move the scheduler state forward by the specified number of Cycles.
383 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
384 if (NextCycle <= CurCycle)
387 AvailableQueue->setCurCycle(NextCycle);
388 if (HazardRec->getMaxLookAhead() == 0) {
389 // Bypass lots of virtual calls in case of long latency.
390 CurCycle = NextCycle;
393 for (; CurCycle != NextCycle; ++CurCycle) {
395 HazardRec->RecedeCycle();
397 HazardRec->AdvanceCycle();
400 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
401 // available Q to release pending nodes at least once before popping.
405 /// Move the scheduler state forward until the specified node's dependents are
406 /// ready and can be scheduled with no resource conflicts.
407 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
408 if (!EnableSchedCycles)
411 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
413 // Bump CurCycle to account for latency. We assume the latency of other
414 // available instructions may be hidden by the stall (not a full pipe stall).
415 // This updates the hazard recognizer's cycle before reserving resources for
417 AdvanceToCycle(ReadyCycle);
419 // Calls are scheduled in their preceding cycle, so don't conflict with
420 // hazards from instructions after the call. EmitNode will reset the
421 // scoreboard state before emitting the call.
422 if (isBottomUp && SU->isCall)
425 // FIXME: For resource conflicts in very long non-pipelined stages, we
426 // should probably skip ahead here to avoid useless scoreboard checks.
429 ScheduleHazardRecognizer::HazardType HT =
430 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
432 if (HT == ScheduleHazardRecognizer::NoHazard)
437 AdvanceToCycle(CurCycle + Stalls);
440 /// Record this SUnit in the HazardRecognizer.
441 /// Does not update CurCycle.
442 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
443 if (!EnableSchedCycles || HazardRec->getMaxLookAhead() == 0)
446 // Check for phys reg copy.
450 switch (SU->getNode()->getOpcode()) {
452 assert(SU->getNode()->isMachineOpcode() &&
453 "This target-independent node should not be scheduled.");
455 case ISD::MERGE_VALUES:
456 case ISD::TokenFactor:
458 case ISD::CopyFromReg:
460 // Noops don't affect the scoreboard state. Copies are likely to be
464 // For inline asm, clear the pipeline state.
468 if (isBottomUp && SU->isCall) {
469 // Calls are scheduled with their preceding instructions. For bottom-up
470 // scheduling, clear the pipeline state before emitting.
474 HazardRec->EmitInstruction(SU);
476 if (!isBottomUp && SU->isCall) {
481 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
482 /// count of its predecessors. If a predecessor pending count is zero, add it to
483 /// the Available queue.
484 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
485 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
486 DEBUG(SU->dump(this));
489 if (CurCycle < SU->getHeight())
490 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
493 // FIXME: Do not modify node height. It may interfere with
494 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
495 // node it's ready cycle can aid heuristics, and after scheduling it can
496 // indicate the scheduled cycle.
497 SU->setHeightToAtLeast(CurCycle);
499 // Reserve resources for the scheduled intruction.
502 Sequence.push_back(SU);
504 AvailableQueue->ScheduledNode(SU);
506 // Update liveness of predecessors before successors to avoid treating a
507 // two-address node as a live range def.
508 ReleasePredecessors(SU);
510 // Release all the implicit physical register defs that are live.
511 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
513 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
514 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
515 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
517 LiveRegDefs[I->getReg()] = NULL;
518 LiveRegGens[I->getReg()] = NULL;
522 SU->isScheduled = true;
524 // Conditions under which the scheduler should eagerly advance the cycle:
525 // (1) No available instructions
526 // (2) All pipelines full, so available instructions must have hazards.
528 // If SchedCycles is disabled, count each inst as one cycle.
529 if (!EnableSchedCycles ||
530 AvailableQueue->empty() || HazardRec->atIssueLimit())
531 AdvanceToCycle(CurCycle + 1);
534 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
535 /// unscheduled, incrcease the succ left count of its predecessors. Remove
536 /// them from AvailableQueue if necessary.
537 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
538 SUnit *PredSU = PredEdge->getSUnit();
539 if (PredSU->isAvailable) {
540 PredSU->isAvailable = false;
541 if (!PredSU->isPending)
542 AvailableQueue->remove(PredSU);
545 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
546 ++PredSU->NumSuccsLeft;
549 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
550 /// its predecessor states to reflect the change.
551 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
552 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
553 DEBUG(SU->dump(this));
555 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
558 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
559 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
560 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
561 "Physical register dependency violated?");
563 LiveRegDefs[I->getReg()] = NULL;
564 LiveRegGens[I->getReg()] = NULL;
568 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
570 if (I->isAssignedRegDep()) {
571 // This becomes the nearest def. Note that an earlier def may still be
572 // pending if this is a two-address node.
573 LiveRegDefs[I->getReg()] = SU;
574 if (!LiveRegDefs[I->getReg()]) {
577 if (LiveRegGens[I->getReg()] == NULL ||
578 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
579 LiveRegGens[I->getReg()] = I->getSUnit();
582 if (SU->getHeight() < MinAvailableCycle)
583 MinAvailableCycle = SU->getHeight();
585 SU->setHeightDirty();
586 SU->isScheduled = false;
587 SU->isAvailable = true;
588 if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
589 // Don't make available until backtracking is complete.
590 SU->isPending = true;
591 PendingQueue.push_back(SU);
594 AvailableQueue->push(SU);
596 AvailableQueue->UnscheduledNode(SU);
599 /// After backtracking, the hazard checker needs to be restored to a state
600 /// corresponding the the current cycle.
601 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
604 unsigned LookAhead = std::min((unsigned)Sequence.size(),
605 HazardRec->getMaxLookAhead());
609 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
610 unsigned HazardCycle = (*I)->getHeight();
611 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
613 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
614 HazardRec->RecedeCycle();
620 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
621 /// BTCycle in order to schedule a specific node.
622 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
623 SUnit *OldSU = Sequence.back();
626 if (SU->isSucc(OldSU))
627 // Don't try to remove SU from AvailableQueue.
628 SU->isAvailable = false;
629 // FIXME: use ready cycle instead of height
630 CurCycle = OldSU->getHeight();
631 UnscheduleNodeBottomUp(OldSU);
632 AvailableQueue->setCurCycle(CurCycle);
635 OldSU = Sequence.back();
638 assert(!SU->isSucc(OldSU) && "Something is wrong!");
640 RestoreHazardCheckerBottomUp();
647 static bool isOperandOf(const SUnit *SU, SDNode *N) {
648 for (const SDNode *SUNode = SU->getNode(); SUNode;
649 SUNode = SUNode->getGluedNode()) {
650 if (SUNode->isOperandOf(N))
656 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
657 /// successors to the newly created node.
658 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
659 SDNode *N = SU->getNode();
663 if (SU->getNode()->getGluedNode())
667 bool TryUnfold = false;
668 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
669 EVT VT = N->getValueType(i);
672 else if (VT == MVT::Other)
675 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
676 const SDValue &Op = N->getOperand(i);
677 EVT VT = Op.getNode()->getValueType(Op.getResNo());
683 SmallVector<SDNode*, 2> NewNodes;
684 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
687 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
688 assert(NewNodes.size() == 2 && "Expected a load folding node!");
691 SDNode *LoadNode = NewNodes[0];
692 unsigned NumVals = N->getNumValues();
693 unsigned OldNumVals = SU->getNode()->getNumValues();
694 for (unsigned i = 0; i != NumVals; ++i)
695 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
696 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
697 SDValue(LoadNode, 1));
699 // LoadNode may already exist. This can happen when there is another
700 // load from the same location and producing the same type of value
701 // but it has different alignment or volatileness.
702 bool isNewLoad = true;
704 if (LoadNode->getNodeId() != -1) {
705 LoadSU = &SUnits[LoadNode->getNodeId()];
708 LoadSU = CreateNewSUnit(LoadNode);
709 LoadNode->setNodeId(LoadSU->NodeNum);
710 ComputeLatency(LoadSU);
713 SUnit *NewSU = CreateNewSUnit(N);
714 assert(N->getNodeId() == -1 && "Node already inserted!");
715 N->setNodeId(NewSU->NodeNum);
717 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
718 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
719 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
720 NewSU->isTwoAddress = true;
724 if (TID.isCommutable())
725 NewSU->isCommutable = true;
726 ComputeLatency(NewSU);
728 // Record all the edges to and from the old SU, by category.
729 SmallVector<SDep, 4> ChainPreds;
730 SmallVector<SDep, 4> ChainSuccs;
731 SmallVector<SDep, 4> LoadPreds;
732 SmallVector<SDep, 4> NodePreds;
733 SmallVector<SDep, 4> NodeSuccs;
734 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
737 ChainPreds.push_back(*I);
738 else if (isOperandOf(I->getSUnit(), LoadNode))
739 LoadPreds.push_back(*I);
741 NodePreds.push_back(*I);
743 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
746 ChainSuccs.push_back(*I);
748 NodeSuccs.push_back(*I);
751 // Now assign edges to the newly-created nodes.
752 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
753 const SDep &Pred = ChainPreds[i];
754 RemovePred(SU, Pred);
756 AddPred(LoadSU, Pred);
758 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
759 const SDep &Pred = LoadPreds[i];
760 RemovePred(SU, Pred);
762 AddPred(LoadSU, Pred);
764 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
765 const SDep &Pred = NodePreds[i];
766 RemovePred(SU, Pred);
767 AddPred(NewSU, Pred);
769 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
770 SDep D = NodeSuccs[i];
771 SUnit *SuccDep = D.getSUnit();
773 RemovePred(SuccDep, D);
777 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
778 SDep D = ChainSuccs[i];
779 SUnit *SuccDep = D.getSUnit();
781 RemovePred(SuccDep, D);
788 // Add a data dependency to reflect that NewSU reads the value defined
790 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
793 AvailableQueue->addNode(LoadSU);
794 AvailableQueue->addNode(NewSU);
798 if (NewSU->NumSuccsLeft == 0) {
799 NewSU->isAvailable = true;
805 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
806 NewSU = CreateClone(SU);
808 // New SUnit has the exact same predecessors.
809 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
811 if (!I->isArtificial())
814 // Only copy scheduled successors. Cut them from old node's successor
815 // list and move them over.
816 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
817 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
819 if (I->isArtificial())
821 SUnit *SuccSU = I->getSUnit();
822 if (SuccSU->isScheduled) {
827 DelDeps.push_back(std::make_pair(SuccSU, D));
830 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
831 RemovePred(DelDeps[i].first, DelDeps[i].second);
833 AvailableQueue->updateNode(SU);
834 AvailableQueue->addNode(NewSU);
840 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
841 /// scheduled successors of the given SUnit to the last copy.
842 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
843 const TargetRegisterClass *DestRC,
844 const TargetRegisterClass *SrcRC,
845 SmallVector<SUnit*, 2> &Copies) {
846 SUnit *CopyFromSU = CreateNewSUnit(NULL);
847 CopyFromSU->CopySrcRC = SrcRC;
848 CopyFromSU->CopyDstRC = DestRC;
850 SUnit *CopyToSU = CreateNewSUnit(NULL);
851 CopyToSU->CopySrcRC = DestRC;
852 CopyToSU->CopyDstRC = SrcRC;
854 // Only copy scheduled successors. Cut them from old node's successor
855 // list and move them over.
856 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
857 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
859 if (I->isArtificial())
861 SUnit *SuccSU = I->getSUnit();
862 if (SuccSU->isScheduled) {
864 D.setSUnit(CopyToSU);
866 DelDeps.push_back(std::make_pair(SuccSU, *I));
869 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
870 RemovePred(DelDeps[i].first, DelDeps[i].second);
872 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
873 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
875 AvailableQueue->updateNode(SU);
876 AvailableQueue->addNode(CopyFromSU);
877 AvailableQueue->addNode(CopyToSU);
878 Copies.push_back(CopyFromSU);
879 Copies.push_back(CopyToSU);
884 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
885 /// definition of the specified node.
886 /// FIXME: Move to SelectionDAG?
887 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
888 const TargetInstrInfo *TII) {
889 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
890 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
891 unsigned NumRes = TID.getNumDefs();
892 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
897 return N->getValueType(NumRes);
900 /// CheckForLiveRegDef - Return true and update live register vector if the
901 /// specified register def of the specified SUnit clobbers any "live" registers.
902 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
903 std::vector<SUnit*> &LiveRegDefs,
904 SmallSet<unsigned, 4> &RegAdded,
905 SmallVector<unsigned, 4> &LRegs,
906 const TargetRegisterInfo *TRI) {
907 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
909 // Check if Ref is live.
910 if (!LiveRegDefs[Reg]) continue;
912 // Allow multiple uses of the same def.
913 if (LiveRegDefs[Reg] == SU) continue;
915 // Add Reg to the set of interfering live regs.
916 if (RegAdded.insert(Reg))
917 LRegs.push_back(Reg);
921 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
922 /// scheduling of the given node to satisfy live physical register dependencies.
923 /// If the specific node is the last one that's available to schedule, do
924 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
925 bool ScheduleDAGRRList::
926 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
927 if (NumLiveRegs == 0)
930 SmallSet<unsigned, 4> RegAdded;
931 // If this node would clobber any "live" register, then it's not ready.
933 // If SU is the currently live definition of the same register that it uses,
934 // then we are free to schedule it.
935 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
937 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
938 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
939 RegAdded, LRegs, TRI);
942 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
943 if (Node->getOpcode() == ISD::INLINEASM) {
944 // Inline asm can clobber physical defs.
945 unsigned NumOps = Node->getNumOperands();
946 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
947 --NumOps; // Ignore the glue operand.
949 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
951 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
952 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
954 ++i; // Skip the ID value.
955 if (InlineAsm::isRegDefKind(Flags) ||
956 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
957 // Check for def of register or earlyclobber register.
958 for (; NumVals; --NumVals, ++i) {
959 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
960 if (TargetRegisterInfo::isPhysicalRegister(Reg))
961 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
969 if (!Node->isMachineOpcode())
971 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
972 if (!TID.ImplicitDefs)
974 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
975 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
978 return !LRegs.empty();
981 /// Return a node that can be scheduled in this cycle. Requirements:
982 /// (1) Ready: latency has been satisfied
983 /// (2) No Hazards: resources are available
984 /// (3) No Interferences: may unschedule to break register interferences.
985 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
986 SmallVector<SUnit*, 4> Interferences;
987 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
989 SUnit *CurSU = AvailableQueue->pop();
991 SmallVector<unsigned, 4> LRegs;
992 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
994 LRegsMap.insert(std::make_pair(CurSU, LRegs));
996 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
997 Interferences.push_back(CurSU);
998 CurSU = AvailableQueue->pop();
1001 // Add the nodes that aren't ready back onto the available list.
1002 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1003 Interferences[i]->isPending = false;
1004 assert(Interferences[i]->isAvailable && "must still be available");
1005 AvailableQueue->push(Interferences[i]);
1010 // All candidates are delayed due to live physical reg dependencies.
1011 // Try backtracking, code duplication, or inserting cross class copies
1013 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1014 SUnit *TrySU = Interferences[i];
1015 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1017 // Try unscheduling up to the point where it's safe to schedule
1020 unsigned LiveCycle = UINT_MAX;
1021 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1022 unsigned Reg = LRegs[j];
1023 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1024 BtSU = LiveRegGens[Reg];
1025 LiveCycle = BtSU->getHeight();
1028 if (!WillCreateCycle(TrySU, BtSU)) {
1029 BacktrackBottomUp(TrySU, BtSU);
1031 // Force the current node to be scheduled before the node that
1032 // requires the physical reg dep.
1033 if (BtSU->isAvailable) {
1034 BtSU->isAvailable = false;
1035 if (!BtSU->isPending)
1036 AvailableQueue->remove(BtSU);
1038 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1039 /*Reg=*/0, /*isNormalMemory=*/false,
1040 /*isMustAlias=*/false, /*isArtificial=*/true));
1042 // If one or more successors has been unscheduled, then the current
1043 // node is no longer avaialable. Schedule a successor that's now
1044 // available instead.
1045 if (!TrySU->isAvailable) {
1046 CurSU = AvailableQueue->pop();
1050 TrySU->isPending = false;
1051 Interferences.erase(Interferences.begin()+i);
1058 // Can't backtrack. If it's too expensive to copy the value, then try
1059 // duplicate the nodes that produces these "too expensive to copy"
1060 // values to break the dependency. In case even that doesn't work,
1061 // insert cross class copies.
1062 // If it's not too expensive, i.e. cost != -1, issue copies.
1063 SUnit *TrySU = Interferences[0];
1064 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1065 assert(LRegs.size() == 1 && "Can't handle this yet!");
1066 unsigned Reg = LRegs[0];
1067 SUnit *LRDef = LiveRegDefs[Reg];
1068 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1069 const TargetRegisterClass *RC =
1070 TRI->getMinimalPhysRegClass(Reg, VT);
1071 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1073 // If cross copy register class is null, then it must be possible copy
1074 // the value directly. Do not try duplicate the def.
1077 NewDef = CopyAndMoveSuccessors(LRDef);
1081 // Issue copies, these can be expensive cross register class copies.
1082 SmallVector<SUnit*, 2> Copies;
1083 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1084 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1085 << " to SU #" << Copies.front()->NodeNum << "\n");
1086 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1087 /*Reg=*/0, /*isNormalMemory=*/false,
1088 /*isMustAlias=*/false,
1089 /*isArtificial=*/true));
1090 NewDef = Copies.back();
1093 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1094 << " to SU #" << TrySU->NodeNum << "\n");
1095 LiveRegDefs[Reg] = NewDef;
1096 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1097 /*Reg=*/0, /*isNormalMemory=*/false,
1098 /*isMustAlias=*/false,
1099 /*isArtificial=*/true));
1100 TrySU->isAvailable = false;
1104 assert(CurSU && "Unable to resolve live physical register dependencies!");
1106 // Add the nodes that aren't ready back onto the available list.
1107 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1108 Interferences[i]->isPending = false;
1109 // May no longer be available due to backtracking.
1110 if (Interferences[i]->isAvailable) {
1111 AvailableQueue->push(Interferences[i]);
1117 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1119 void ScheduleDAGRRList::ListScheduleBottomUp() {
1120 // Release any predecessors of the special Exit node.
1121 ReleasePredecessors(&ExitSU);
1123 // Add root to Available queue.
1124 if (!SUnits.empty()) {
1125 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1126 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1127 RootSU->isAvailable = true;
1128 AvailableQueue->push(RootSU);
1131 // While Available queue is not empty, grab the node with the highest
1132 // priority. If it is not ready put it back. Schedule the node.
1133 Sequence.reserve(SUnits.size());
1134 while (!AvailableQueue->empty()) {
1135 DEBUG(dbgs() << "\n*** Examining Available\n";
1136 AvailableQueue->dump(this));
1138 // Pick the best node to schedule taking all constraints into
1140 SUnit *SU = PickNodeToScheduleBottomUp();
1142 AdvancePastStalls(SU);
1144 ScheduleNodeBottomUp(SU);
1146 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1147 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1148 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1149 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1153 // Reverse the order if it is bottom up.
1154 std::reverse(Sequence.begin(), Sequence.end());
1157 VerifySchedule(isBottomUp);
1161 //===----------------------------------------------------------------------===//
1162 // Top-Down Scheduling
1163 //===----------------------------------------------------------------------===//
1165 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1166 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1167 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1168 SUnit *SuccSU = SuccEdge->getSUnit();
1171 if (SuccSU->NumPredsLeft == 0) {
1172 dbgs() << "*** Scheduling failed! ***\n";
1174 dbgs() << " has been released too many times!\n";
1175 llvm_unreachable(0);
1178 --SuccSU->NumPredsLeft;
1180 // If all the node's predecessors are scheduled, this node is ready
1181 // to be scheduled. Ignore the special ExitSU node.
1182 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1183 SuccSU->isAvailable = true;
1184 AvailableQueue->push(SuccSU);
1188 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1189 // Top down: release successors
1190 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1192 assert(!I->isAssignedRegDep() &&
1193 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1195 ReleaseSucc(SU, &*I);
1199 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1200 /// count of its successors. If a successor pending count is zero, add it to
1201 /// the Available queue.
1202 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1203 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1204 DEBUG(SU->dump(this));
1206 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1207 SU->setDepthToAtLeast(CurCycle);
1208 Sequence.push_back(SU);
1210 ReleaseSuccessors(SU);
1211 SU->isScheduled = true;
1212 AvailableQueue->ScheduledNode(SU);
1215 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1217 void ScheduleDAGRRList::ListScheduleTopDown() {
1218 AvailableQueue->setCurCycle(CurCycle);
1220 // Release any successors of the special Entry node.
1221 ReleaseSuccessors(&EntrySU);
1223 // All leaves to Available queue.
1224 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1225 // It is available if it has no predecessors.
1226 if (SUnits[i].Preds.empty()) {
1227 AvailableQueue->push(&SUnits[i]);
1228 SUnits[i].isAvailable = true;
1232 // While Available queue is not empty, grab the node with the highest
1233 // priority. If it is not ready put it back. Schedule the node.
1234 Sequence.reserve(SUnits.size());
1235 while (!AvailableQueue->empty()) {
1236 SUnit *CurSU = AvailableQueue->pop();
1239 ScheduleNodeTopDown(CurSU);
1241 AvailableQueue->setCurCycle(CurCycle);
1245 VerifySchedule(isBottomUp);
1250 //===----------------------------------------------------------------------===//
1251 // RegReductionPriorityQueue Definition
1252 //===----------------------------------------------------------------------===//
1254 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1255 // to reduce register pressure.
1258 class RegReductionPQBase;
1260 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1261 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1264 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1265 // reduction scheduler.
1266 struct bu_ls_rr_sort : public queue_sort {
1269 HasReadyFilter = false
1272 RegReductionPQBase *SPQ;
1273 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1274 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1276 bool operator()(SUnit* left, SUnit* right) const;
1279 // td_ls_rr_sort - Priority function for top down register pressure reduction
1281 struct td_ls_rr_sort : public queue_sort {
1284 HasReadyFilter = false
1287 RegReductionPQBase *SPQ;
1288 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1289 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1291 bool operator()(const SUnit* left, const SUnit* right) const;
1294 // src_ls_rr_sort - Priority function for source order scheduler.
1295 struct src_ls_rr_sort : public queue_sort {
1298 HasReadyFilter = false
1301 RegReductionPQBase *SPQ;
1302 src_ls_rr_sort(RegReductionPQBase *spq)
1304 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1307 bool operator()(SUnit* left, SUnit* right) const;
1310 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1311 struct hybrid_ls_rr_sort : public queue_sort {
1314 HasReadyFilter = true
1317 RegReductionPQBase *SPQ;
1318 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1320 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1323 bool isReady(SUnit *SU, unsigned CurCycle) const;
1325 bool operator()(SUnit* left, SUnit* right) const;
1328 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1330 struct ilp_ls_rr_sort : public queue_sort {
1333 HasReadyFilter = true
1336 RegReductionPQBase *SPQ;
1337 ilp_ls_rr_sort(RegReductionPQBase *spq)
1339 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1342 bool isReady(SUnit *SU, unsigned CurCycle) const;
1344 bool operator()(SUnit* left, SUnit* right) const;
1347 class RegReductionPQBase : public SchedulingPriorityQueue {
1349 std::vector<SUnit*> Queue;
1350 unsigned CurQueueId;
1351 bool TracksRegPressure;
1353 // SUnits - The SUnits for the current graph.
1354 std::vector<SUnit> *SUnits;
1356 MachineFunction &MF;
1357 const TargetInstrInfo *TII;
1358 const TargetRegisterInfo *TRI;
1359 const TargetLowering *TLI;
1360 ScheduleDAGRRList *scheduleDAG;
1362 // SethiUllmanNumbers - The SethiUllman number for each node.
1363 std::vector<unsigned> SethiUllmanNumbers;
1365 /// RegPressure - Tracking current reg pressure per register class.
1367 std::vector<unsigned> RegPressure;
1369 /// RegLimit - Tracking the number of allocatable registers per register
1371 std::vector<unsigned> RegLimit;
1374 RegReductionPQBase(MachineFunction &mf,
1375 bool hasReadyFilter,
1377 const TargetInstrInfo *tii,
1378 const TargetRegisterInfo *tri,
1379 const TargetLowering *tli)
1380 : SchedulingPriorityQueue(hasReadyFilter),
1381 CurQueueId(0), TracksRegPressure(tracksrp),
1382 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1383 if (TracksRegPressure) {
1384 unsigned NumRC = TRI->getNumRegClasses();
1385 RegLimit.resize(NumRC);
1386 RegPressure.resize(NumRC);
1387 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1388 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1389 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1390 E = TRI->regclass_end(); I != E; ++I)
1391 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1395 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1396 scheduleDAG = scheduleDag;
1399 ScheduleHazardRecognizer* getHazardRec() {
1400 return scheduleDAG->getHazardRec();
1403 void initNodes(std::vector<SUnit> &sunits);
1405 void addNode(const SUnit *SU);
1407 void updateNode(const SUnit *SU);
1409 void releaseState() {
1411 SethiUllmanNumbers.clear();
1412 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1415 unsigned getNodePriority(const SUnit *SU) const;
1417 unsigned getNodeOrdering(const SUnit *SU) const {
1418 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1421 bool empty() const { return Queue.empty(); }
1423 void push(SUnit *U) {
1424 assert(!U->NodeQueueId && "Node in the queue already");
1425 U->NodeQueueId = ++CurQueueId;
1429 void remove(SUnit *SU) {
1430 assert(!Queue.empty() && "Queue is empty!");
1431 assert(SU->NodeQueueId != 0 && "Not in queue!");
1432 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1434 if (I != prior(Queue.end()))
1435 std::swap(*I, Queue.back());
1437 SU->NodeQueueId = 0;
1440 void dumpRegPressure() const;
1442 bool HighRegPressure(const SUnit *SU) const;
1444 bool MayReduceRegPressure(SUnit *SU);
1446 void ScheduledNode(SUnit *SU);
1448 void UnscheduledNode(SUnit *SU);
1451 bool canClobber(const SUnit *SU, const SUnit *Op);
1452 void AddPseudoTwoAddrDeps();
1453 void PrescheduleNodesWithMultipleUses();
1454 void CalculateSethiUllmanNumbers();
1458 class RegReductionPriorityQueue : public RegReductionPQBase {
1459 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1460 std::vector<SUnit *>::iterator Best = Q.begin();
1461 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1462 E = Q.end(); I != E; ++I)
1463 if (Picker(*Best, *I))
1466 if (Best != prior(Q.end()))
1467 std::swap(*Best, Q.back());
1475 RegReductionPriorityQueue(MachineFunction &mf,
1477 const TargetInstrInfo *tii,
1478 const TargetRegisterInfo *tri,
1479 const TargetLowering *tli)
1480 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1483 bool isBottomUp() const { return SF::IsBottomUp; }
1485 bool isReady(SUnit *U) const {
1486 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1490 if (Queue.empty()) return NULL;
1492 SUnit *V = popFromQueue(Queue, Picker);
1497 void dump(ScheduleDAG *DAG) const {
1498 // Emulate pop() without clobbering NodeQueueIds.
1499 std::vector<SUnit*> DumpQueue = Queue;
1500 SF DumpPicker = Picker;
1501 while (!DumpQueue.empty()) {
1502 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1504 dbgs() << "Height " << SU->getHeight() << ": ";
1506 dbgs() << "Depth " << SU->getDepth() << ": ";
1512 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1513 BURegReductionPriorityQueue;
1515 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1516 TDRegReductionPriorityQueue;
1518 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1519 SrcRegReductionPriorityQueue;
1521 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1522 HybridBURRPriorityQueue;
1524 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1525 ILPBURRPriorityQueue;
1526 } // end anonymous namespace
1528 //===----------------------------------------------------------------------===//
1529 // Static Node Priority for Register Pressure Reduction
1530 //===----------------------------------------------------------------------===//
1532 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1533 /// Smaller number is the higher priority.
1535 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1536 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1537 if (SethiUllmanNumber != 0)
1538 return SethiUllmanNumber;
1541 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1543 if (I->isCtrl()) continue; // ignore chain preds
1544 SUnit *PredSU = I->getSUnit();
1545 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1546 if (PredSethiUllman > SethiUllmanNumber) {
1547 SethiUllmanNumber = PredSethiUllman;
1549 } else if (PredSethiUllman == SethiUllmanNumber)
1553 SethiUllmanNumber += Extra;
1555 if (SethiUllmanNumber == 0)
1556 SethiUllmanNumber = 1;
1558 return SethiUllmanNumber;
1561 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1562 /// scheduling units.
1563 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1564 SethiUllmanNumbers.assign(SUnits->size(), 0);
1566 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1567 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1570 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1572 // Add pseudo dependency edges for two-address nodes.
1573 AddPseudoTwoAddrDeps();
1574 // Reroute edges to nodes with multiple uses.
1575 PrescheduleNodesWithMultipleUses();
1576 // Calculate node priorities.
1577 CalculateSethiUllmanNumbers();
1580 void RegReductionPQBase::addNode(const SUnit *SU) {
1581 unsigned SUSize = SethiUllmanNumbers.size();
1582 if (SUnits->size() > SUSize)
1583 SethiUllmanNumbers.resize(SUSize*2, 0);
1584 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1587 void RegReductionPQBase::updateNode(const SUnit *SU) {
1588 SethiUllmanNumbers[SU->NodeNum] = 0;
1589 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1592 // Lower priority means schedule further down. For bottom-up scheduling, lower
1593 // priority SUs are scheduled before higher priority SUs.
1594 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1595 assert(SU->NodeNum < SethiUllmanNumbers.size());
1596 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1597 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1598 // CopyToReg should be close to its uses to facilitate coalescing and
1601 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1602 Opc == TargetOpcode::SUBREG_TO_REG ||
1603 Opc == TargetOpcode::INSERT_SUBREG)
1604 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1605 // close to their uses to facilitate coalescing.
1607 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1608 // If SU does not have a register use, i.e. it doesn't produce a value
1609 // that would be consumed (e.g. store), then it terminates a chain of
1610 // computation. Give it a large SethiUllman number so it will be
1611 // scheduled right before its predecessors that it doesn't lengthen
1612 // their live ranges.
1614 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1615 // If SU does not have a register def, schedule it close to its uses
1616 // because it does not lengthen any live ranges.
1618 return SethiUllmanNumbers[SU->NodeNum];
1621 //===----------------------------------------------------------------------===//
1622 // Register Pressure Tracking
1623 //===----------------------------------------------------------------------===//
1625 void RegReductionPQBase::dumpRegPressure() const {
1626 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1627 E = TRI->regclass_end(); I != E; ++I) {
1628 const TargetRegisterClass *RC = *I;
1629 unsigned Id = RC->getID();
1630 unsigned RP = RegPressure[Id];
1632 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1637 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1641 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1645 SUnit *PredSU = I->getSUnit();
1646 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1647 // counts data deps. To be more precise, we could maintain a
1648 // NumDataSuccsLeft count.
1649 if (PredSU->NumSuccsLeft != PredSU->Succs.size()) {
1650 DEBUG(dbgs() << " SU(" << PredSU->NodeNum << ") live across SU("
1651 << SU->NodeNum << ")\n");
1654 const SDNode *PN = PredSU->getNode();
1655 if (!PN->isMachineOpcode()) {
1656 if (PN->getOpcode() == ISD::CopyFromReg) {
1657 EVT VT = PN->getValueType(0);
1658 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1659 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1660 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1665 unsigned POpc = PN->getMachineOpcode();
1666 if (POpc == TargetOpcode::IMPLICIT_DEF)
1668 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1669 EVT VT = PN->getOperand(0).getValueType();
1670 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1671 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1672 // Check if this increases register pressure of the specific register
1673 // class to the point where it would cause spills.
1674 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1677 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1678 POpc == TargetOpcode::SUBREG_TO_REG) {
1679 EVT VT = PN->getValueType(0);
1680 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1681 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1682 // Check if this increases register pressure of the specific register
1683 // class to the point where it would cause spills.
1684 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1688 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1689 for (unsigned i = 0; i != NumDefs; ++i) {
1690 EVT VT = PN->getValueType(i);
1691 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1692 if (RegPressure[RCId] >= RegLimit[RCId])
1693 return true; // Reg pressure already high.
1694 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1695 if (!PN->hasAnyUseOfValue(i))
1697 // Check if this increases register pressure of the specific register
1698 // class to the point where it would cause spills.
1699 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1707 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1708 const SDNode *N = SU->getNode();
1710 if (!N->isMachineOpcode() || !SU->NumSuccs)
1713 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1714 for (unsigned i = 0; i != NumDefs; ++i) {
1715 EVT VT = N->getValueType(i);
1716 if (!N->hasAnyUseOfValue(i))
1718 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1719 if (RegPressure[RCId] >= RegLimit[RCId])
1725 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1726 if (!TracksRegPressure)
1729 const SDNode *N = SU->getNode();
1730 if (!N->isMachineOpcode()) {
1731 if (N->getOpcode() != ISD::CopyToReg)
1734 unsigned Opc = N->getMachineOpcode();
1735 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1736 Opc == TargetOpcode::INSERT_SUBREG ||
1737 Opc == TargetOpcode::SUBREG_TO_REG ||
1738 Opc == TargetOpcode::REG_SEQUENCE ||
1739 Opc == TargetOpcode::IMPLICIT_DEF)
1743 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1747 SUnit *PredSU = I->getSUnit();
1748 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1749 // counts data deps.
1750 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1752 const SDNode *PN = PredSU->getNode();
1753 if (!PN->isMachineOpcode()) {
1754 if (PN->getOpcode() == ISD::CopyFromReg) {
1755 EVT VT = PN->getValueType(0);
1756 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1757 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1761 unsigned POpc = PN->getMachineOpcode();
1762 if (POpc == TargetOpcode::IMPLICIT_DEF)
1764 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1765 EVT VT = PN->getOperand(0).getValueType();
1766 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1767 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1769 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1770 POpc == TargetOpcode::SUBREG_TO_REG) {
1771 EVT VT = PN->getValueType(0);
1772 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1773 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1776 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1777 for (unsigned i = 0; i != NumDefs; ++i) {
1778 EVT VT = PN->getValueType(i);
1779 if (!PN->hasAnyUseOfValue(i))
1781 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1782 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1786 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1787 // may transfer data dependencies to CopyToReg.
1788 if (SU->NumSuccs && N->isMachineOpcode()) {
1789 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1790 for (unsigned i = 0; i != NumDefs; ++i) {
1791 EVT VT = N->getValueType(i);
1792 if (!N->hasAnyUseOfValue(i))
1794 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1795 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1796 // Register pressure tracking is imprecise. This can happen.
1797 RegPressure[RCId] = 0;
1799 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1806 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1807 if (!TracksRegPressure)
1810 const SDNode *N = SU->getNode();
1811 if (!N->isMachineOpcode()) {
1812 if (N->getOpcode() != ISD::CopyToReg)
1815 unsigned Opc = N->getMachineOpcode();
1816 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1817 Opc == TargetOpcode::INSERT_SUBREG ||
1818 Opc == TargetOpcode::SUBREG_TO_REG ||
1819 Opc == TargetOpcode::REG_SEQUENCE ||
1820 Opc == TargetOpcode::IMPLICIT_DEF)
1824 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1828 SUnit *PredSU = I->getSUnit();
1829 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1830 // counts data deps.
1831 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1833 const SDNode *PN = PredSU->getNode();
1834 if (!PN->isMachineOpcode()) {
1835 if (PN->getOpcode() == ISD::CopyFromReg) {
1836 EVT VT = PN->getValueType(0);
1837 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1838 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1842 unsigned POpc = PN->getMachineOpcode();
1843 if (POpc == TargetOpcode::IMPLICIT_DEF)
1845 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1846 EVT VT = PN->getOperand(0).getValueType();
1847 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1848 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1850 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1851 POpc == TargetOpcode::SUBREG_TO_REG) {
1852 EVT VT = PN->getValueType(0);
1853 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1854 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1857 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1858 for (unsigned i = 0; i != NumDefs; ++i) {
1859 EVT VT = PN->getValueType(i);
1860 if (!PN->hasAnyUseOfValue(i))
1862 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1863 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1864 // Register pressure tracking is imprecise. This can happen.
1865 RegPressure[RCId] = 0;
1867 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1871 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1872 // may transfer data dependencies to CopyToReg.
1873 if (SU->NumSuccs && N->isMachineOpcode()) {
1874 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1875 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1876 EVT VT = N->getValueType(i);
1877 if (VT == MVT::Glue || VT == MVT::Other)
1879 if (!N->hasAnyUseOfValue(i))
1881 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1882 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1889 //===----------------------------------------------------------------------===//
1890 // Dynamic Node Priority for Register Pressure Reduction
1891 //===----------------------------------------------------------------------===//
1893 /// closestSucc - Returns the scheduled cycle of the successor which is
1894 /// closest to the current cycle.
1895 static unsigned closestSucc(const SUnit *SU) {
1896 unsigned MaxHeight = 0;
1897 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1899 if (I->isCtrl()) continue; // ignore chain succs
1900 unsigned Height = I->getSUnit()->getHeight();
1901 // If there are bunch of CopyToRegs stacked up, they should be considered
1902 // to be at the same position.
1903 if (I->getSUnit()->getNode() &&
1904 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1905 Height = closestSucc(I->getSUnit())+1;
1906 if (Height > MaxHeight)
1912 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1913 /// for scratch registers, i.e. number of data dependencies.
1914 static unsigned calcMaxScratches(const SUnit *SU) {
1915 unsigned Scratches = 0;
1916 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1918 if (I->isCtrl()) continue; // ignore chain preds
1924 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1925 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1926 /// it has no other use. It should be scheduled closer to the terminator.
1927 static bool hasOnlyLiveOutUses(const SUnit *SU) {
1928 bool RetVal = false;
1929 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1931 if (I->isCtrl()) continue;
1932 const SUnit *SuccSU = I->getSUnit();
1933 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1935 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1936 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1946 /// UnitsSharePred - Return true if the two scheduling units share a common
1947 /// data predecessor.
1948 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1949 SmallSet<const SUnit*, 4> Preds;
1950 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1952 if (I->isCtrl()) continue; // ignore chain preds
1953 Preds.insert(I->getSUnit());
1955 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1957 if (I->isCtrl()) continue; // ignore chain preds
1958 if (Preds.count(I->getSUnit()))
1964 // Check for either a dependence (latency) or resource (hazard) stall.
1966 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1967 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1968 if ((int)SPQ->getCurCycle() < Height) return true;
1969 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1970 != ScheduleHazardRecognizer::NoHazard)
1975 // Return -1 if left has higher priority, 1 if right has higher priority.
1976 // Return 0 if latency-based priority is equivalent.
1977 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1978 RegReductionPQBase *SPQ) {
1979 // If the two nodes share an operand and one of them has a single
1980 // use that is a live out copy, favor the one that is live out. Otherwise
1981 // it will be difficult to eliminate the copy if the instruction is a
1982 // loop induction variable update. e.g.
1989 bool SharePred = UnitsSharePred(left, right);
1990 // FIXME: Only adjust if BB is a loop back edge.
1991 // FIXME: What's the cost of a copy?
1992 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1993 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1994 int LHeight = (int)left->getHeight() - LBonus;
1995 int RHeight = (int)right->getHeight() - RBonus;
1997 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1998 BUHasStall(left, LHeight, SPQ);
1999 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2000 BUHasStall(right, RHeight, SPQ);
2002 // If scheduling one of the node will cause a pipeline stall, delay it.
2003 // If scheduling either one of the node will cause a pipeline stall, sort
2004 // them according to their height.
2008 if (LHeight != RHeight)
2009 return LHeight > RHeight ? 1 : -1;
2013 // If either node is scheduling for latency, sort them by depth
2015 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2016 right->SchedulingPref == Sched::Latency)) {
2017 int LDepth = (int)left->getDepth();
2018 int RDepth = (int)right->getDepth();
2020 if (EnableSchedCycles) {
2021 if (LDepth != RDepth)
2022 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2023 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2024 << ") depth " << RDepth << ")\n");
2025 return LDepth < RDepth ? 1 : -1;
2028 if (LHeight != RHeight)
2029 return LHeight > RHeight ? 1 : -1;
2031 if (left->Latency != right->Latency)
2032 return left->Latency > right->Latency ? 1 : -1;
2037 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2038 unsigned LPriority = SPQ->getNodePriority(left);
2039 unsigned RPriority = SPQ->getNodePriority(right);
2040 if (LPriority != RPriority)
2041 return LPriority > RPriority;
2043 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2048 // and the following instructions are both ready.
2052 // Then schedule t2 = op first.
2059 // This creates more short live intervals.
2060 unsigned LDist = closestSucc(left);
2061 unsigned RDist = closestSucc(right);
2063 return LDist < RDist;
2065 // How many registers becomes live when the node is scheduled.
2066 unsigned LScratch = calcMaxScratches(left);
2067 unsigned RScratch = calcMaxScratches(right);
2068 if (LScratch != RScratch)
2069 return LScratch > RScratch;
2071 if (EnableSchedCycles) {
2072 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2077 if (left->getHeight() != right->getHeight())
2078 return left->getHeight() > right->getHeight();
2080 if (left->getDepth() != right->getDepth())
2081 return left->getDepth() < right->getDepth();
2084 assert(left->NodeQueueId && right->NodeQueueId &&
2085 "NodeQueueId cannot be zero");
2086 return (left->NodeQueueId > right->NodeQueueId);
2090 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2091 return BURRSort(left, right, SPQ);
2094 // Source order, otherwise bottom up.
2095 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2096 unsigned LOrder = SPQ->getNodeOrdering(left);
2097 unsigned ROrder = SPQ->getNodeOrdering(right);
2099 // Prefer an ordering where the lower the non-zero order number, the higher
2101 if ((LOrder || ROrder) && LOrder != ROrder)
2102 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2104 return BURRSort(left, right, SPQ);
2107 // If the time between now and when the instruction will be ready can cover
2108 // the spill code, then avoid adding it to the ready queue. This gives long
2109 // stalls highest priority and allows hoisting across calls. It should also
2110 // speed up processing the available queue.
2111 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2112 static const unsigned ReadyDelay = 3;
2114 if (SPQ->MayReduceRegPressure(SU)) return true;
2116 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2118 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2119 != ScheduleHazardRecognizer::NoHazard)
2125 // Return true if right should be scheduled with higher priority than left.
2126 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2127 if (left->isCall || right->isCall)
2128 // No way to compute latency of calls.
2129 return BURRSort(left, right, SPQ);
2131 bool LHigh = SPQ->HighRegPressure(left);
2132 bool RHigh = SPQ->HighRegPressure(right);
2133 // Avoid causing spills. If register pressure is high, schedule for
2134 // register pressure reduction.
2135 if (LHigh && !RHigh) {
2136 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2137 << right->NodeNum << ")\n");
2140 else if (!LHigh && RHigh) {
2141 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2142 << left->NodeNum << ")\n");
2145 else if (!LHigh && !RHigh) {
2146 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2150 return BURRSort(left, right, SPQ);
2153 // Schedule as many instructions in each cycle as possible. So don't make an
2154 // instruction available unless it is ready in the current cycle.
2155 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2156 if (SU->getHeight() > CurCycle) return false;
2158 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2159 != ScheduleHazardRecognizer::NoHazard)
2162 return SU->getHeight() <= CurCycle;
2165 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2166 if (left->isCall || right->isCall)
2167 // No way to compute latency of calls.
2168 return BURRSort(left, right, SPQ);
2170 bool LHigh = SPQ->HighRegPressure(left);
2171 bool RHigh = SPQ->HighRegPressure(right);
2172 // Avoid causing spills. If register pressure is high, schedule for
2173 // register pressure reduction.
2174 if (LHigh && !RHigh)
2176 else if (!LHigh && RHigh)
2178 else if (!LHigh && !RHigh) {
2179 // Low register pressure situation, schedule to maximize instruction level
2181 if (left->NumPreds > right->NumPreds)
2183 else if (left->NumPreds < right->NumPreds)
2187 return BURRSort(left, right, SPQ);
2190 //===----------------------------------------------------------------------===//
2191 // Preschedule for Register Pressure
2192 //===----------------------------------------------------------------------===//
2194 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2195 if (SU->isTwoAddress) {
2196 unsigned Opc = SU->getNode()->getMachineOpcode();
2197 const TargetInstrDesc &TID = TII->get(Opc);
2198 unsigned NumRes = TID.getNumDefs();
2199 unsigned NumOps = TID.getNumOperands() - NumRes;
2200 for (unsigned i = 0; i != NumOps; ++i) {
2201 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2202 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2203 if (DU->getNodeId() != -1 &&
2204 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2212 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2213 /// physical register defs.
2214 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2215 const TargetInstrInfo *TII,
2216 const TargetRegisterInfo *TRI) {
2217 SDNode *N = SuccSU->getNode();
2218 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2219 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2220 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2221 for (const SDNode *SUNode = SU->getNode(); SUNode;
2222 SUNode = SUNode->getGluedNode()) {
2223 if (!SUNode->isMachineOpcode())
2225 const unsigned *SUImpDefs =
2226 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2229 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2230 EVT VT = N->getValueType(i);
2231 if (VT == MVT::Glue || VT == MVT::Other)
2233 if (!N->hasAnyUseOfValue(i))
2235 unsigned Reg = ImpDefs[i - NumDefs];
2236 for (;*SUImpDefs; ++SUImpDefs) {
2237 unsigned SUReg = *SUImpDefs;
2238 if (TRI->regsOverlap(Reg, SUReg))
2246 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2247 /// are not handled well by the general register pressure reduction
2248 /// heuristics. When presented with code like this:
2257 /// the heuristics tend to push the store up, but since the
2258 /// operand of the store has another use (U), this would increase
2259 /// the length of that other use (the U->N edge).
2261 /// This function transforms code like the above to route U's
2262 /// dependence through the store when possible, like this:
2273 /// This results in the store being scheduled immediately
2274 /// after N, which shortens the U->N live range, reducing
2275 /// register pressure.
2277 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2278 // Visit all the nodes in topological order, working top-down.
2279 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2280 SUnit *SU = &(*SUnits)[i];
2281 // For now, only look at nodes with no data successors, such as stores.
2282 // These are especially important, due to the heuristics in
2283 // getNodePriority for nodes with no data successors.
2284 if (SU->NumSuccs != 0)
2286 // For now, only look at nodes with exactly one data predecessor.
2287 if (SU->NumPreds != 1)
2289 // Avoid prescheduling copies to virtual registers, which don't behave
2290 // like other nodes from the perspective of scheduling heuristics.
2291 if (SDNode *N = SU->getNode())
2292 if (N->getOpcode() == ISD::CopyToReg &&
2293 TargetRegisterInfo::isVirtualRegister
2294 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2297 // Locate the single data predecessor.
2299 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2300 EE = SU->Preds.end(); II != EE; ++II)
2301 if (!II->isCtrl()) {
2302 PredSU = II->getSUnit();
2307 // Don't rewrite edges that carry physregs, because that requires additional
2308 // support infrastructure.
2309 if (PredSU->hasPhysRegDefs)
2311 // Short-circuit the case where SU is PredSU's only data successor.
2312 if (PredSU->NumSuccs == 1)
2314 // Avoid prescheduling to copies from virtual registers, which don't behave
2315 // like other nodes from the perspective of scheduling // heuristics.
2316 if (SDNode *N = SU->getNode())
2317 if (N->getOpcode() == ISD::CopyFromReg &&
2318 TargetRegisterInfo::isVirtualRegister
2319 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2322 // Perform checks on the successors of PredSU.
2323 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2324 EE = PredSU->Succs.end(); II != EE; ++II) {
2325 SUnit *PredSuccSU = II->getSUnit();
2326 if (PredSuccSU == SU) continue;
2327 // If PredSU has another successor with no data successors, for
2328 // now don't attempt to choose either over the other.
2329 if (PredSuccSU->NumSuccs == 0)
2330 goto outer_loop_continue;
2331 // Don't break physical register dependencies.
2332 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2333 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2334 goto outer_loop_continue;
2335 // Don't introduce graph cycles.
2336 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2337 goto outer_loop_continue;
2340 // Ok, the transformation is safe and the heuristics suggest it is
2341 // profitable. Update the graph.
2342 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2343 << " next to PredSU #" << PredSU->NodeNum
2344 << " to guide scheduling in the presence of multiple uses\n");
2345 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2346 SDep Edge = PredSU->Succs[i];
2347 assert(!Edge.isAssignedRegDep());
2348 SUnit *SuccSU = Edge.getSUnit();
2350 Edge.setSUnit(PredSU);
2351 scheduleDAG->RemovePred(SuccSU, Edge);
2352 scheduleDAG->AddPred(SU, Edge);
2354 scheduleDAG->AddPred(SuccSU, Edge);
2358 outer_loop_continue:;
2362 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2363 /// it as a def&use operand. Add a pseudo control edge from it to the other
2364 /// node (if it won't create a cycle) so the two-address one will be scheduled
2365 /// first (lower in the schedule). If both nodes are two-address, favor the
2366 /// one that has a CopyToReg use (more likely to be a loop induction update).
2367 /// If both are two-address, but one is commutable while the other is not
2368 /// commutable, favor the one that's not commutable.
2369 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2370 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2371 SUnit *SU = &(*SUnits)[i];
2372 if (!SU->isTwoAddress)
2375 SDNode *Node = SU->getNode();
2376 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2379 bool isLiveOut = hasOnlyLiveOutUses(SU);
2380 unsigned Opc = Node->getMachineOpcode();
2381 const TargetInstrDesc &TID = TII->get(Opc);
2382 unsigned NumRes = TID.getNumDefs();
2383 unsigned NumOps = TID.getNumOperands() - NumRes;
2384 for (unsigned j = 0; j != NumOps; ++j) {
2385 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2387 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2388 if (DU->getNodeId() == -1)
2390 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2391 if (!DUSU) continue;
2392 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2393 E = DUSU->Succs.end(); I != E; ++I) {
2394 if (I->isCtrl()) continue;
2395 SUnit *SuccSU = I->getSUnit();
2398 // Be conservative. Ignore if nodes aren't at roughly the same
2399 // depth and height.
2400 if (SuccSU->getHeight() < SU->getHeight() &&
2401 (SU->getHeight() - SuccSU->getHeight()) > 1)
2403 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2404 // constrains whatever is using the copy, instead of the copy
2405 // itself. In the case that the copy is coalesced, this
2406 // preserves the intent of the pseudo two-address heurietics.
2407 while (SuccSU->Succs.size() == 1 &&
2408 SuccSU->getNode()->isMachineOpcode() &&
2409 SuccSU->getNode()->getMachineOpcode() ==
2410 TargetOpcode::COPY_TO_REGCLASS)
2411 SuccSU = SuccSU->Succs.front().getSUnit();
2412 // Don't constrain non-instruction nodes.
2413 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2415 // Don't constrain nodes with physical register defs if the
2416 // predecessor can clobber them.
2417 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2418 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2421 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2422 // these may be coalesced away. We want them close to their uses.
2423 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2424 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2425 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2426 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2428 if ((!canClobber(SuccSU, DUSU) ||
2429 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2430 (!SU->isCommutable && SuccSU->isCommutable)) &&
2431 !scheduleDAG->IsReachable(SuccSU, SU)) {
2432 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2433 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2434 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2435 /*Reg=*/0, /*isNormalMemory=*/false,
2436 /*isMustAlias=*/false,
2437 /*isArtificial=*/true));
2444 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2445 /// predecessors of the successors of the SUnit SU. Stop when the provided
2446 /// limit is exceeded.
2447 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2450 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2452 const SUnit *SuccSU = I->getSUnit();
2453 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2454 EE = SuccSU->Preds.end(); II != EE; ++II) {
2455 SUnit *PredSU = II->getSUnit();
2456 if (!PredSU->isScheduled)
2466 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2467 unsigned LPriority = SPQ->getNodePriority(left);
2468 unsigned RPriority = SPQ->getNodePriority(right);
2469 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2470 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2471 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2472 bool RIsFloater = RIsTarget && right->NumPreds == 0;
2473 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2474 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2476 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2478 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2485 if (left->NumSuccs == 1)
2487 if (right->NumSuccs == 1)
2490 if (LPriority+LBonus != RPriority+RBonus)
2491 return LPriority+LBonus < RPriority+RBonus;
2493 if (left->getDepth() != right->getDepth())
2494 return left->getDepth() < right->getDepth();
2496 if (left->NumSuccsLeft != right->NumSuccsLeft)
2497 return left->NumSuccsLeft > right->NumSuccsLeft;
2499 assert(left->NodeQueueId && right->NodeQueueId &&
2500 "NodeQueueId cannot be zero");
2501 return (left->NodeQueueId > right->NodeQueueId);
2504 //===----------------------------------------------------------------------===//
2505 // Public Constructor Functions
2506 //===----------------------------------------------------------------------===//
2508 llvm::ScheduleDAGSDNodes *
2509 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2510 CodeGenOpt::Level OptLevel) {
2511 const TargetMachine &TM = IS->TM;
2512 const TargetInstrInfo *TII = TM.getInstrInfo();
2513 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2515 BURegReductionPriorityQueue *PQ =
2516 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2517 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2518 PQ->setScheduleDAG(SD);
2522 llvm::ScheduleDAGSDNodes *
2523 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2524 CodeGenOpt::Level OptLevel) {
2525 const TargetMachine &TM = IS->TM;
2526 const TargetInstrInfo *TII = TM.getInstrInfo();
2527 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2529 TDRegReductionPriorityQueue *PQ =
2530 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2531 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2532 PQ->setScheduleDAG(SD);
2536 llvm::ScheduleDAGSDNodes *
2537 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2538 CodeGenOpt::Level OptLevel) {
2539 const TargetMachine &TM = IS->TM;
2540 const TargetInstrInfo *TII = TM.getInstrInfo();
2541 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2543 SrcRegReductionPriorityQueue *PQ =
2544 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2545 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2546 PQ->setScheduleDAG(SD);
2550 llvm::ScheduleDAGSDNodes *
2551 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2552 CodeGenOpt::Level OptLevel) {
2553 const TargetMachine &TM = IS->TM;
2554 const TargetInstrInfo *TII = TM.getInstrInfo();
2555 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2556 const TargetLowering *TLI = &IS->getTargetLowering();
2558 HybridBURRPriorityQueue *PQ =
2559 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2561 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2562 PQ->setScheduleDAG(SD);
2566 llvm::ScheduleDAGSDNodes *
2567 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2568 CodeGenOpt::Level OptLevel) {
2569 const TargetMachine &TM = IS->TM;
2570 const TargetInstrInfo *TII = TM.getInstrInfo();
2571 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2572 const TargetLowering *TLI = &IS->getTargetLowering();
2574 ILPBURRPriorityQueue *PQ =
2575 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2576 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2577 PQ->setScheduleDAG(SD);