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> DisableSchedCycles(
70 "disable-sched-cycles", cl::Hidden, cl::init(false),
71 cl::desc("Disable cycle-level precision during preRA scheduling"));
73 // Temporary sched=list-ilp flags until the heuristics are robust.
74 static cl::opt<bool> DisableSchedRegPressure(
75 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
76 cl::desc("Disable regpressure priority in sched=list-ilp"));
77 static cl::opt<bool> DisableSchedLiveUses(
78 "disable-sched-live-uses", cl::Hidden, cl::init(true),
79 cl::desc("Disable live use priority in sched=list-ilp"));
80 static cl::opt<bool> DisableSchedVRegCycle(
81 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
82 cl::desc("Disable virtual register cycle interference checks"));
83 static cl::opt<bool> DisableSchedStalls(
84 "disable-sched-stalls", cl::Hidden, cl::init(true),
85 cl::desc("Disable no-stall priority in sched=list-ilp"));
86 static cl::opt<bool> DisableSchedCriticalPath(
87 "disable-sched-critical-path", cl::Hidden, cl::init(false),
88 cl::desc("Disable critical path priority in sched=list-ilp"));
89 static cl::opt<bool> DisableSchedHeight(
90 "disable-sched-height", cl::Hidden, cl::init(false),
91 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
93 static cl::opt<int> MaxReorderWindow(
94 "max-sched-reorder", cl::Hidden, cl::init(6),
95 cl::desc("Number of instructions to allow ahead of the critical path "
96 "in sched=list-ilp"));
98 static cl::opt<unsigned> AvgIPC(
99 "sched-avg-ipc", cl::Hidden, cl::init(1),
100 cl::desc("Average inst/cycle whan no target itinerary exists."));
104 // For sched=list-ilp, Count the number of times each factor comes into play.
105 enum { FactPressureDiff, FactRegUses, FactHeight, FactDepth, FactStatic,
106 FactOther, NumFactors };
108 static const char *FactorName[NumFactors] =
109 {"PressureDiff", "RegUses", "Height", "Depth","Static", "Other"};
110 static int FactorCount[NumFactors];
114 //===----------------------------------------------------------------------===//
115 /// ScheduleDAGRRList - The actual register reduction list scheduler
116 /// implementation. This supports both top-down and bottom-up scheduling.
118 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
120 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
124 /// NeedLatency - True if the scheduler will make use of latency information.
128 /// AvailableQueue - The priority queue to use for the available SUnits.
129 SchedulingPriorityQueue *AvailableQueue;
131 /// PendingQueue - This contains all of the instructions whose operands have
132 /// been issued, but their results are not ready yet (due to the latency of
133 /// the operation). Once the operands becomes available, the instruction is
134 /// added to the AvailableQueue.
135 std::vector<SUnit*> PendingQueue;
137 /// HazardRec - The hazard recognizer to use.
138 ScheduleHazardRecognizer *HazardRec;
140 /// CurCycle - The current scheduler state corresponds to this cycle.
143 /// MinAvailableCycle - Cycle of the soonest available instruction.
144 unsigned MinAvailableCycle;
146 /// IssueCount - Count instructions issued in this cycle
147 /// Currently valid only for bottom-up scheduling.
150 /// LiveRegDefs - A set of physical registers and their definition
151 /// that are "live". These nodes must be scheduled before any other nodes that
152 /// modifies the registers can be scheduled.
153 unsigned NumLiveRegs;
154 std::vector<SUnit*> LiveRegDefs;
155 std::vector<SUnit*> LiveRegGens;
157 /// Topo - A topological ordering for SUnits which permits fast IsReachable
158 /// and similar queries.
159 ScheduleDAGTopologicalSort Topo;
162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
163 SchedulingPriorityQueue *availqueue,
164 CodeGenOpt::Level OptLevel)
165 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
169 const TargetMachine &tm = mf.getTarget();
170 if (DisableSchedCycles || !NeedLatency)
171 HazardRec = new ScheduleHazardRecognizer();
173 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
176 ~ScheduleDAGRRList() {
178 delete AvailableQueue;
183 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
185 /// IsReachable - Checks if SU is reachable from TargetSU.
186 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
187 return Topo.IsReachable(SU, TargetSU);
190 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
192 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
193 return Topo.WillCreateCycle(SU, TargetSU);
196 /// AddPred - adds a predecessor edge to SUnit SU.
197 /// This returns true if this is a new predecessor.
198 /// Updates the topological ordering if required.
199 void AddPred(SUnit *SU, const SDep &D) {
200 Topo.AddPred(SU, D.getSUnit());
204 /// RemovePred - removes a predecessor edge from SUnit SU.
205 /// This returns true if an edge was removed.
206 /// Updates the topological ordering if required.
207 void RemovePred(SUnit *SU, const SDep &D) {
208 Topo.RemovePred(SU, D.getSUnit());
213 bool isReady(SUnit *SU) {
214 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
215 AvailableQueue->isReady(SU);
218 void ReleasePred(SUnit *SU, const SDep *PredEdge);
219 void ReleasePredecessors(SUnit *SU);
220 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
221 void ReleaseSuccessors(SUnit *SU);
222 void ReleasePending();
223 void AdvanceToCycle(unsigned NextCycle);
224 void AdvancePastStalls(SUnit *SU);
225 void EmitNode(SUnit *SU);
226 void ScheduleNodeBottomUp(SUnit*);
227 void CapturePred(SDep *PredEdge);
228 void UnscheduleNodeBottomUp(SUnit*);
229 void RestoreHazardCheckerBottomUp();
230 void BacktrackBottomUp(SUnit*, SUnit*);
231 SUnit *CopyAndMoveSuccessors(SUnit*);
232 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
233 const TargetRegisterClass*,
234 const TargetRegisterClass*,
235 SmallVector<SUnit*, 2>&);
236 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
238 SUnit *PickNodeToScheduleBottomUp();
239 void ListScheduleBottomUp();
241 void ScheduleNodeTopDown(SUnit*);
242 void ListScheduleTopDown();
245 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
246 /// Updates the topological ordering if required.
247 SUnit *CreateNewSUnit(SDNode *N) {
248 unsigned NumSUnits = SUnits.size();
249 SUnit *NewNode = NewSUnit(N);
250 // Update the topological ordering.
251 if (NewNode->NodeNum >= NumSUnits)
252 Topo.InitDAGTopologicalSorting();
256 /// CreateClone - Creates a new SUnit from an existing one.
257 /// Updates the topological ordering if required.
258 SUnit *CreateClone(SUnit *N) {
259 unsigned NumSUnits = SUnits.size();
260 SUnit *NewNode = Clone(N);
261 // Update the topological ordering.
262 if (NewNode->NodeNum >= NumSUnits)
263 Topo.InitDAGTopologicalSorting();
267 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
268 /// need actual latency information but the hybrid scheduler does.
269 bool ForceUnitLatencies() const {
273 } // end anonymous namespace
276 /// Schedule - Schedule the DAG using list scheduling.
277 void ScheduleDAGRRList::Schedule() {
279 << "********** List Scheduling BB#" << BB->getNumber()
280 << " '" << BB->getName() << "' **********\n");
282 for (int i = 0; i < NumFactors; ++i) {
289 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
291 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
292 LiveRegGens.resize(TRI->getNumRegs(), NULL);
294 // Build the scheduling graph.
295 BuildSchedGraph(NULL);
297 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
298 SUnits[su].dumpAll(this));
299 Topo.InitDAGTopologicalSorting();
301 AvailableQueue->initNodes(SUnits);
305 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
307 ListScheduleBottomUp();
309 ListScheduleTopDown();
312 for (int i = 0; i < NumFactors; ++i) {
313 DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
316 AvailableQueue->releaseState();
319 //===----------------------------------------------------------------------===//
320 // Bottom-Up Scheduling
321 //===----------------------------------------------------------------------===//
323 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
324 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
325 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
326 SUnit *PredSU = PredEdge->getSUnit();
329 if (PredSU->NumSuccsLeft == 0) {
330 dbgs() << "*** Scheduling failed! ***\n";
332 dbgs() << " has been released too many times!\n";
336 --PredSU->NumSuccsLeft;
338 if (!ForceUnitLatencies()) {
339 // Updating predecessor's height. This is now the cycle when the
340 // predecessor can be scheduled without causing a pipeline stall.
341 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
344 // If all the node's successors are scheduled, this node is ready
345 // to be scheduled. Ignore the special EntrySU node.
346 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
347 PredSU->isAvailable = true;
349 unsigned Height = PredSU->getHeight();
350 if (Height < MinAvailableCycle)
351 MinAvailableCycle = Height;
353 if (isReady(PredSU)) {
354 AvailableQueue->push(PredSU);
356 // CapturePred and others may have left the node in the pending queue, avoid
358 else if (!PredSU->isPending) {
359 PredSU->isPending = true;
360 PendingQueue.push_back(PredSU);
365 /// Call ReleasePred for each predecessor, then update register live def/gen.
366 /// Always update LiveRegDefs for a register dependence even if the current SU
367 /// also defines the register. This effectively create one large live range
368 /// across a sequence of two-address node. This is important because the
369 /// entire chain must be scheduled together. Example:
372 /// flags = (2) addc flags
373 /// flags = (1) addc flags
377 /// LiveRegDefs[flags] = 3
378 /// LiveRegGens[flags] = 1
380 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
381 /// interference on flags.
382 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
383 // Bottom up: release predecessors
384 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
386 ReleasePred(SU, &*I);
387 if (I->isAssignedRegDep()) {
388 // This is a physical register dependency and it's impossible or
389 // expensive to copy the register. Make sure nothing that can
390 // clobber the register is scheduled between the predecessor and
392 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
393 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
394 "interference on register dependence");
395 LiveRegDefs[I->getReg()] = I->getSUnit();
396 if (!LiveRegGens[I->getReg()]) {
398 LiveRegGens[I->getReg()] = SU;
404 /// Check to see if any of the pending instructions are ready to issue. If
405 /// so, add them to the available queue.
406 void ScheduleDAGRRList::ReleasePending() {
407 if (DisableSchedCycles) {
408 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
412 // If the available queue is empty, it is safe to reset MinAvailableCycle.
413 if (AvailableQueue->empty())
414 MinAvailableCycle = UINT_MAX;
416 // Check to see if any of the pending instructions are ready to issue. If
417 // so, add them to the available queue.
418 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
419 unsigned ReadyCycle =
420 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
421 if (ReadyCycle < MinAvailableCycle)
422 MinAvailableCycle = ReadyCycle;
424 if (PendingQueue[i]->isAvailable) {
425 if (!isReady(PendingQueue[i]))
427 AvailableQueue->push(PendingQueue[i]);
429 PendingQueue[i]->isPending = false;
430 PendingQueue[i] = PendingQueue.back();
431 PendingQueue.pop_back();
436 /// Move the scheduler state forward by the specified number of Cycles.
437 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
438 if (NextCycle <= CurCycle)
442 AvailableQueue->setCurCycle(NextCycle);
443 if (!HazardRec->isEnabled()) {
444 // Bypass lots of virtual calls in case of long latency.
445 CurCycle = NextCycle;
448 for (; CurCycle != NextCycle; ++CurCycle) {
450 HazardRec->RecedeCycle();
452 HazardRec->AdvanceCycle();
455 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
456 // available Q to release pending nodes at least once before popping.
460 /// Move the scheduler state forward until the specified node's dependents are
461 /// ready and can be scheduled with no resource conflicts.
462 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
463 if (DisableSchedCycles)
466 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
468 // Bump CurCycle to account for latency. We assume the latency of other
469 // available instructions may be hidden by the stall (not a full pipe stall).
470 // This updates the hazard recognizer's cycle before reserving resources for
472 AdvanceToCycle(ReadyCycle);
474 // Calls are scheduled in their preceding cycle, so don't conflict with
475 // hazards from instructions after the call. EmitNode will reset the
476 // scoreboard state before emitting the call.
477 if (isBottomUp && SU->isCall)
480 // FIXME: For resource conflicts in very long non-pipelined stages, we
481 // should probably skip ahead here to avoid useless scoreboard checks.
484 ScheduleHazardRecognizer::HazardType HT =
485 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
487 if (HT == ScheduleHazardRecognizer::NoHazard)
492 AdvanceToCycle(CurCycle + Stalls);
495 /// Record this SUnit in the HazardRecognizer.
496 /// Does not update CurCycle.
497 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
498 if (!HazardRec->isEnabled())
501 // Check for phys reg copy.
505 switch (SU->getNode()->getOpcode()) {
507 assert(SU->getNode()->isMachineOpcode() &&
508 "This target-independent node should not be scheduled.");
510 case ISD::MERGE_VALUES:
511 case ISD::TokenFactor:
513 case ISD::CopyFromReg:
515 // Noops don't affect the scoreboard state. Copies are likely to be
519 // For inline asm, clear the pipeline state.
523 if (isBottomUp && SU->isCall) {
524 // Calls are scheduled with their preceding instructions. For bottom-up
525 // scheduling, clear the pipeline state before emitting.
529 HazardRec->EmitInstruction(SU);
531 if (!isBottomUp && SU->isCall) {
536 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
537 /// count of its predecessors. If a predecessor pending count is zero, add it to
538 /// the Available queue.
539 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
540 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
541 DEBUG(SU->dump(this));
544 if (CurCycle < SU->getHeight())
545 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
548 // FIXME: Do not modify node height. It may interfere with
549 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
550 // node its ready cycle can aid heuristics, and after scheduling it can
551 // indicate the scheduled cycle.
552 SU->setHeightToAtLeast(CurCycle);
554 // Reserve resources for the scheduled intruction.
557 Sequence.push_back(SU);
559 AvailableQueue->ScheduledNode(SU);
561 // If HazardRec is disabled, and each inst counts as one cycle, then
562 // advance CurCycle before ReleasePredecessors to avoid useles pushed to
563 // PendingQueue for schedulers that implement HasReadyFilter.
564 if (!HazardRec->isEnabled() && AvgIPC < 2)
565 AdvanceToCycle(CurCycle + 1);
567 // Update liveness of predecessors before successors to avoid treating a
568 // two-address node as a live range def.
569 ReleasePredecessors(SU);
571 // Release all the implicit physical register defs that are live.
572 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
574 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
575 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
576 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
578 LiveRegDefs[I->getReg()] = NULL;
579 LiveRegGens[I->getReg()] = NULL;
583 SU->isScheduled = true;
585 // Conditions under which the scheduler should eagerly advance the cycle:
586 // (1) No available instructions
587 // (2) All pipelines full, so available instructions must have hazards.
589 // If HazardRec is disabled, the cycle was advanced earlier.
591 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
593 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
594 || (!HazardRec->isEnabled() && AvgIPC > 1 && IssueCount == AvgIPC)
595 || AvailableQueue->empty())
596 AdvanceToCycle(CurCycle + 1);
599 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
600 /// unscheduled, incrcease the succ left count of its predecessors. Remove
601 /// them from AvailableQueue if necessary.
602 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
603 SUnit *PredSU = PredEdge->getSUnit();
604 if (PredSU->isAvailable) {
605 PredSU->isAvailable = false;
606 if (!PredSU->isPending)
607 AvailableQueue->remove(PredSU);
610 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
611 ++PredSU->NumSuccsLeft;
614 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
615 /// its predecessor states to reflect the change.
616 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
617 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
618 DEBUG(SU->dump(this));
620 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
623 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
624 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
625 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
626 "Physical register dependency violated?");
628 LiveRegDefs[I->getReg()] = NULL;
629 LiveRegGens[I->getReg()] = NULL;
633 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
635 if (I->isAssignedRegDep()) {
636 // This becomes the nearest def. Note that an earlier def may still be
637 // pending if this is a two-address node.
638 LiveRegDefs[I->getReg()] = SU;
639 if (!LiveRegDefs[I->getReg()]) {
642 if (LiveRegGens[I->getReg()] == NULL ||
643 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
644 LiveRegGens[I->getReg()] = I->getSUnit();
647 if (SU->getHeight() < MinAvailableCycle)
648 MinAvailableCycle = SU->getHeight();
650 SU->setHeightDirty();
651 SU->isScheduled = false;
652 SU->isAvailable = true;
653 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
654 // Don't make available until backtracking is complete.
655 SU->isPending = true;
656 PendingQueue.push_back(SU);
659 AvailableQueue->push(SU);
661 AvailableQueue->UnscheduledNode(SU);
664 /// After backtracking, the hazard checker needs to be restored to a state
665 /// corresponding the the current cycle.
666 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
669 unsigned LookAhead = std::min((unsigned)Sequence.size(),
670 HazardRec->getMaxLookAhead());
674 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
675 unsigned HazardCycle = (*I)->getHeight();
676 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
678 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
679 HazardRec->RecedeCycle();
685 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
686 /// BTCycle in order to schedule a specific node.
687 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
688 SUnit *OldSU = Sequence.back();
691 if (SU->isSucc(OldSU))
692 // Don't try to remove SU from AvailableQueue.
693 SU->isAvailable = false;
694 // FIXME: use ready cycle instead of height
695 CurCycle = OldSU->getHeight();
696 UnscheduleNodeBottomUp(OldSU);
697 AvailableQueue->setCurCycle(CurCycle);
700 OldSU = Sequence.back();
703 assert(!SU->isSucc(OldSU) && "Something is wrong!");
705 RestoreHazardCheckerBottomUp();
712 static bool isOperandOf(const SUnit *SU, SDNode *N) {
713 for (const SDNode *SUNode = SU->getNode(); SUNode;
714 SUNode = SUNode->getGluedNode()) {
715 if (SUNode->isOperandOf(N))
721 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
722 /// successors to the newly created node.
723 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
724 SDNode *N = SU->getNode();
728 if (SU->getNode()->getGluedNode())
732 bool TryUnfold = false;
733 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
734 EVT VT = N->getValueType(i);
737 else if (VT == MVT::Other)
740 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
741 const SDValue &Op = N->getOperand(i);
742 EVT VT = Op.getNode()->getValueType(Op.getResNo());
748 SmallVector<SDNode*, 2> NewNodes;
749 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
752 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
753 assert(NewNodes.size() == 2 && "Expected a load folding node!");
756 SDNode *LoadNode = NewNodes[0];
757 unsigned NumVals = N->getNumValues();
758 unsigned OldNumVals = SU->getNode()->getNumValues();
759 for (unsigned i = 0; i != NumVals; ++i)
760 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
761 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
762 SDValue(LoadNode, 1));
764 // LoadNode may already exist. This can happen when there is another
765 // load from the same location and producing the same type of value
766 // but it has different alignment or volatileness.
767 bool isNewLoad = true;
769 if (LoadNode->getNodeId() != -1) {
770 LoadSU = &SUnits[LoadNode->getNodeId()];
773 LoadSU = CreateNewSUnit(LoadNode);
774 LoadNode->setNodeId(LoadSU->NodeNum);
776 InitNumRegDefsLeft(LoadSU);
777 ComputeLatency(LoadSU);
780 SUnit *NewSU = CreateNewSUnit(N);
781 assert(N->getNodeId() == -1 && "Node already inserted!");
782 N->setNodeId(NewSU->NodeNum);
784 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
785 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
786 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
787 NewSU->isTwoAddress = true;
791 if (TID.isCommutable())
792 NewSU->isCommutable = true;
794 InitNumRegDefsLeft(NewSU);
795 ComputeLatency(NewSU);
797 // Record all the edges to and from the old SU, by category.
798 SmallVector<SDep, 4> ChainPreds;
799 SmallVector<SDep, 4> ChainSuccs;
800 SmallVector<SDep, 4> LoadPreds;
801 SmallVector<SDep, 4> NodePreds;
802 SmallVector<SDep, 4> NodeSuccs;
803 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
806 ChainPreds.push_back(*I);
807 else if (isOperandOf(I->getSUnit(), LoadNode))
808 LoadPreds.push_back(*I);
810 NodePreds.push_back(*I);
812 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
815 ChainSuccs.push_back(*I);
817 NodeSuccs.push_back(*I);
820 // Now assign edges to the newly-created nodes.
821 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
822 const SDep &Pred = ChainPreds[i];
823 RemovePred(SU, Pred);
825 AddPred(LoadSU, Pred);
827 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
828 const SDep &Pred = LoadPreds[i];
829 RemovePred(SU, Pred);
831 AddPred(LoadSU, Pred);
833 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
834 const SDep &Pred = NodePreds[i];
835 RemovePred(SU, Pred);
836 AddPred(NewSU, Pred);
838 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
839 SDep D = NodeSuccs[i];
840 SUnit *SuccDep = D.getSUnit();
842 RemovePred(SuccDep, D);
845 // Balance register pressure.
846 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
847 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
848 --NewSU->NumRegDefsLeft;
850 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
851 SDep D = ChainSuccs[i];
852 SUnit *SuccDep = D.getSUnit();
854 RemovePred(SuccDep, D);
861 // Add a data dependency to reflect that NewSU reads the value defined
863 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
866 AvailableQueue->addNode(LoadSU);
867 AvailableQueue->addNode(NewSU);
871 if (NewSU->NumSuccsLeft == 0) {
872 NewSU->isAvailable = true;
878 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
879 NewSU = CreateClone(SU);
881 // New SUnit has the exact same predecessors.
882 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
884 if (!I->isArtificial())
887 // Only copy scheduled successors. Cut them from old node's successor
888 // list and move them over.
889 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
890 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
892 if (I->isArtificial())
894 SUnit *SuccSU = I->getSUnit();
895 if (SuccSU->isScheduled) {
900 DelDeps.push_back(std::make_pair(SuccSU, D));
903 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
904 RemovePred(DelDeps[i].first, DelDeps[i].second);
906 AvailableQueue->updateNode(SU);
907 AvailableQueue->addNode(NewSU);
913 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
914 /// scheduled successors of the given SUnit to the last copy.
915 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
916 const TargetRegisterClass *DestRC,
917 const TargetRegisterClass *SrcRC,
918 SmallVector<SUnit*, 2> &Copies) {
919 SUnit *CopyFromSU = CreateNewSUnit(NULL);
920 CopyFromSU->CopySrcRC = SrcRC;
921 CopyFromSU->CopyDstRC = DestRC;
923 SUnit *CopyToSU = CreateNewSUnit(NULL);
924 CopyToSU->CopySrcRC = DestRC;
925 CopyToSU->CopyDstRC = SrcRC;
927 // Only copy scheduled successors. Cut them from old node's successor
928 // list and move them over.
929 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
930 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
932 if (I->isArtificial())
934 SUnit *SuccSU = I->getSUnit();
935 if (SuccSU->isScheduled) {
937 D.setSUnit(CopyToSU);
939 DelDeps.push_back(std::make_pair(SuccSU, *I));
942 // Avoid scheduling the def-side copy before other successors. Otherwise
943 // we could introduce another physreg interference on the copy and
944 // continue inserting copies indefinitely.
945 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
946 /*Reg=*/0, /*isNormalMemory=*/false,
947 /*isMustAlias=*/false, /*isArtificial=*/true);
951 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
952 RemovePred(DelDeps[i].first, DelDeps[i].second);
954 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
955 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
957 AvailableQueue->updateNode(SU);
958 AvailableQueue->addNode(CopyFromSU);
959 AvailableQueue->addNode(CopyToSU);
960 Copies.push_back(CopyFromSU);
961 Copies.push_back(CopyToSU);
966 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
967 /// definition of the specified node.
968 /// FIXME: Move to SelectionDAG?
969 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
970 const TargetInstrInfo *TII) {
971 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
972 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
973 unsigned NumRes = TID.getNumDefs();
974 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
979 return N->getValueType(NumRes);
982 /// CheckForLiveRegDef - Return true and update live register vector if the
983 /// specified register def of the specified SUnit clobbers any "live" registers.
984 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
985 std::vector<SUnit*> &LiveRegDefs,
986 SmallSet<unsigned, 4> &RegAdded,
987 SmallVector<unsigned, 4> &LRegs,
988 const TargetRegisterInfo *TRI) {
989 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
991 // Check if Ref is live.
992 if (!LiveRegDefs[Reg]) continue;
994 // Allow multiple uses of the same def.
995 if (LiveRegDefs[Reg] == SU) continue;
997 // Add Reg to the set of interfering live regs.
998 if (RegAdded.insert(Reg))
999 LRegs.push_back(Reg);
1003 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1004 /// scheduling of the given node to satisfy live physical register dependencies.
1005 /// If the specific node is the last one that's available to schedule, do
1006 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1007 bool ScheduleDAGRRList::
1008 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
1009 if (NumLiveRegs == 0)
1012 SmallSet<unsigned, 4> RegAdded;
1013 // If this node would clobber any "live" register, then it's not ready.
1015 // If SU is the currently live definition of the same register that it uses,
1016 // then we are free to schedule it.
1017 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1019 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1020 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1021 RegAdded, LRegs, TRI);
1024 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1025 if (Node->getOpcode() == ISD::INLINEASM) {
1026 // Inline asm can clobber physical defs.
1027 unsigned NumOps = Node->getNumOperands();
1028 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1029 --NumOps; // Ignore the glue operand.
1031 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1033 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1034 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1036 ++i; // Skip the ID value.
1037 if (InlineAsm::isRegDefKind(Flags) ||
1038 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
1039 // Check for def of register or earlyclobber register.
1040 for (; NumVals; --NumVals, ++i) {
1041 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1042 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1043 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1051 if (!Node->isMachineOpcode())
1053 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
1054 if (!TID.ImplicitDefs)
1056 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1057 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1060 return !LRegs.empty();
1063 /// Return a node that can be scheduled in this cycle. Requirements:
1064 /// (1) Ready: latency has been satisfied
1065 /// (2) No Hazards: resources are available
1066 /// (3) No Interferences: may unschedule to break register interferences.
1067 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1068 SmallVector<SUnit*, 4> Interferences;
1069 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1071 SUnit *CurSU = AvailableQueue->pop();
1073 SmallVector<unsigned, 4> LRegs;
1074 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1076 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1078 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1079 Interferences.push_back(CurSU);
1080 CurSU = AvailableQueue->pop();
1083 // Add the nodes that aren't ready back onto the available list.
1084 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1085 Interferences[i]->isPending = false;
1086 assert(Interferences[i]->isAvailable && "must still be available");
1087 AvailableQueue->push(Interferences[i]);
1092 // All candidates are delayed due to live physical reg dependencies.
1093 // Try backtracking, code duplication, or inserting cross class copies
1095 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1096 SUnit *TrySU = Interferences[i];
1097 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1099 // Try unscheduling up to the point where it's safe to schedule
1102 unsigned LiveCycle = UINT_MAX;
1103 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1104 unsigned Reg = LRegs[j];
1105 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1106 BtSU = LiveRegGens[Reg];
1107 LiveCycle = BtSU->getHeight();
1110 if (!WillCreateCycle(TrySU, BtSU)) {
1111 BacktrackBottomUp(TrySU, BtSU);
1113 // Force the current node to be scheduled before the node that
1114 // requires the physical reg dep.
1115 if (BtSU->isAvailable) {
1116 BtSU->isAvailable = false;
1117 if (!BtSU->isPending)
1118 AvailableQueue->remove(BtSU);
1120 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1121 /*Reg=*/0, /*isNormalMemory=*/false,
1122 /*isMustAlias=*/false, /*isArtificial=*/true));
1124 // If one or more successors has been unscheduled, then the current
1125 // node is no longer avaialable. Schedule a successor that's now
1126 // available instead.
1127 if (!TrySU->isAvailable) {
1128 CurSU = AvailableQueue->pop();
1132 TrySU->isPending = false;
1133 Interferences.erase(Interferences.begin()+i);
1140 // Can't backtrack. If it's too expensive to copy the value, then try
1141 // duplicate the nodes that produces these "too expensive to copy"
1142 // values to break the dependency. In case even that doesn't work,
1143 // insert cross class copies.
1144 // If it's not too expensive, i.e. cost != -1, issue copies.
1145 SUnit *TrySU = Interferences[0];
1146 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1147 assert(LRegs.size() == 1 && "Can't handle this yet!");
1148 unsigned Reg = LRegs[0];
1149 SUnit *LRDef = LiveRegDefs[Reg];
1150 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1151 const TargetRegisterClass *RC =
1152 TRI->getMinimalPhysRegClass(Reg, VT);
1153 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1155 // If cross copy register class is the same as RC, then it must be possible
1156 // copy the value directly. Do not try duplicate the def.
1157 // If cross copy register class is not the same as RC, then it's possible to
1158 // copy the value but it require cross register class copies and it is
1160 // If cross copy register class is null, then it's not possible to copy
1161 // the value at all.
1164 NewDef = CopyAndMoveSuccessors(LRDef);
1165 if (!DestRC && !NewDef)
1166 report_fatal_error("Can't handle live physical register dependency!");
1169 // Issue copies, these can be expensive cross register class copies.
1170 SmallVector<SUnit*, 2> Copies;
1171 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1172 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1173 << " to SU #" << Copies.front()->NodeNum << "\n");
1174 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1175 /*Reg=*/0, /*isNormalMemory=*/false,
1176 /*isMustAlias=*/false,
1177 /*isArtificial=*/true));
1178 NewDef = Copies.back();
1181 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1182 << " to SU #" << TrySU->NodeNum << "\n");
1183 LiveRegDefs[Reg] = NewDef;
1184 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1185 /*Reg=*/0, /*isNormalMemory=*/false,
1186 /*isMustAlias=*/false,
1187 /*isArtificial=*/true));
1188 TrySU->isAvailable = false;
1192 assert(CurSU && "Unable to resolve live physical register dependencies!");
1194 // Add the nodes that aren't ready back onto the available list.
1195 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1196 Interferences[i]->isPending = false;
1197 // May no longer be available due to backtracking.
1198 if (Interferences[i]->isAvailable) {
1199 AvailableQueue->push(Interferences[i]);
1205 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1207 void ScheduleDAGRRList::ListScheduleBottomUp() {
1208 // Release any predecessors of the special Exit node.
1209 ReleasePredecessors(&ExitSU);
1211 // Add root to Available queue.
1212 if (!SUnits.empty()) {
1213 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1214 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1215 RootSU->isAvailable = true;
1216 AvailableQueue->push(RootSU);
1219 // While Available queue is not empty, grab the node with the highest
1220 // priority. If it is not ready put it back. Schedule the node.
1221 Sequence.reserve(SUnits.size());
1222 while (!AvailableQueue->empty()) {
1223 DEBUG(dbgs() << "\n*** Examining Available\n";
1224 AvailableQueue->dump(this));
1226 // Pick the best node to schedule taking all constraints into
1228 SUnit *SU = PickNodeToScheduleBottomUp();
1230 AdvancePastStalls(SU);
1232 ScheduleNodeBottomUp(SU);
1234 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1235 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1236 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1237 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1241 // Reverse the order if it is bottom up.
1242 std::reverse(Sequence.begin(), Sequence.end());
1245 VerifySchedule(isBottomUp);
1249 //===----------------------------------------------------------------------===//
1250 // Top-Down Scheduling
1251 //===----------------------------------------------------------------------===//
1253 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1254 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1255 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1256 SUnit *SuccSU = SuccEdge->getSUnit();
1259 if (SuccSU->NumPredsLeft == 0) {
1260 dbgs() << "*** Scheduling failed! ***\n";
1262 dbgs() << " has been released too many times!\n";
1263 llvm_unreachable(0);
1266 --SuccSU->NumPredsLeft;
1268 // If all the node's predecessors are scheduled, this node is ready
1269 // to be scheduled. Ignore the special ExitSU node.
1270 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1271 SuccSU->isAvailable = true;
1272 AvailableQueue->push(SuccSU);
1276 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1277 // Top down: release successors
1278 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1280 assert(!I->isAssignedRegDep() &&
1281 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1283 ReleaseSucc(SU, &*I);
1287 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1288 /// count of its successors. If a successor pending count is zero, add it to
1289 /// the Available queue.
1290 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1291 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1292 DEBUG(SU->dump(this));
1294 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1295 SU->setDepthToAtLeast(CurCycle);
1296 Sequence.push_back(SU);
1298 ReleaseSuccessors(SU);
1299 SU->isScheduled = true;
1300 AvailableQueue->ScheduledNode(SU);
1303 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1305 void ScheduleDAGRRList::ListScheduleTopDown() {
1306 AvailableQueue->setCurCycle(CurCycle);
1308 // Release any successors of the special Entry node.
1309 ReleaseSuccessors(&EntrySU);
1311 // All leaves to Available queue.
1312 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1313 // It is available if it has no predecessors.
1314 if (SUnits[i].Preds.empty()) {
1315 AvailableQueue->push(&SUnits[i]);
1316 SUnits[i].isAvailable = true;
1320 // While Available queue is not empty, grab the node with the highest
1321 // priority. If it is not ready put it back. Schedule the node.
1322 Sequence.reserve(SUnits.size());
1323 while (!AvailableQueue->empty()) {
1324 SUnit *CurSU = AvailableQueue->pop();
1327 ScheduleNodeTopDown(CurSU);
1329 AvailableQueue->setCurCycle(CurCycle);
1333 VerifySchedule(isBottomUp);
1338 //===----------------------------------------------------------------------===//
1339 // RegReductionPriorityQueue Definition
1340 //===----------------------------------------------------------------------===//
1342 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1343 // to reduce register pressure.
1346 class RegReductionPQBase;
1348 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1349 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1352 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1353 // reduction scheduler.
1354 struct bu_ls_rr_sort : public queue_sort {
1357 HasReadyFilter = false
1360 RegReductionPQBase *SPQ;
1361 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1362 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1364 bool operator()(SUnit* left, SUnit* right) const;
1367 // td_ls_rr_sort - Priority function for top down register pressure reduction
1369 struct td_ls_rr_sort : public queue_sort {
1372 HasReadyFilter = false
1375 RegReductionPQBase *SPQ;
1376 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1377 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1379 bool operator()(const SUnit* left, const SUnit* right) const;
1382 // src_ls_rr_sort - Priority function for source order scheduler.
1383 struct src_ls_rr_sort : public queue_sort {
1386 HasReadyFilter = false
1389 RegReductionPQBase *SPQ;
1390 src_ls_rr_sort(RegReductionPQBase *spq)
1392 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1395 bool operator()(SUnit* left, SUnit* right) const;
1398 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1399 struct hybrid_ls_rr_sort : public queue_sort {
1402 HasReadyFilter = false
1405 RegReductionPQBase *SPQ;
1406 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1408 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1411 bool isReady(SUnit *SU, unsigned CurCycle) const;
1413 bool operator()(SUnit* left, SUnit* right) const;
1416 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1418 struct ilp_ls_rr_sort : public queue_sort {
1421 HasReadyFilter = false
1424 RegReductionPQBase *SPQ;
1425 ilp_ls_rr_sort(RegReductionPQBase *spq)
1427 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1430 bool isReady(SUnit *SU, unsigned CurCycle) const;
1432 bool operator()(SUnit* left, SUnit* right) const;
1435 class RegReductionPQBase : public SchedulingPriorityQueue {
1437 std::vector<SUnit*> Queue;
1438 unsigned CurQueueId;
1439 bool TracksRegPressure;
1441 // SUnits - The SUnits for the current graph.
1442 std::vector<SUnit> *SUnits;
1444 MachineFunction &MF;
1445 const TargetInstrInfo *TII;
1446 const TargetRegisterInfo *TRI;
1447 const TargetLowering *TLI;
1448 ScheduleDAGRRList *scheduleDAG;
1450 // SethiUllmanNumbers - The SethiUllman number for each node.
1451 std::vector<unsigned> SethiUllmanNumbers;
1453 /// RegPressure - Tracking current reg pressure per register class.
1455 std::vector<unsigned> RegPressure;
1457 /// RegLimit - Tracking the number of allocatable registers per register
1459 std::vector<unsigned> RegLimit;
1462 RegReductionPQBase(MachineFunction &mf,
1463 bool hasReadyFilter,
1465 const TargetInstrInfo *tii,
1466 const TargetRegisterInfo *tri,
1467 const TargetLowering *tli)
1468 : SchedulingPriorityQueue(hasReadyFilter),
1469 CurQueueId(0), TracksRegPressure(tracksrp),
1470 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1471 if (TracksRegPressure) {
1472 unsigned NumRC = TRI->getNumRegClasses();
1473 RegLimit.resize(NumRC);
1474 RegPressure.resize(NumRC);
1475 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1476 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1477 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1478 E = TRI->regclass_end(); I != E; ++I)
1479 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1483 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1484 scheduleDAG = scheduleDag;
1487 ScheduleHazardRecognizer* getHazardRec() {
1488 return scheduleDAG->getHazardRec();
1491 void initNodes(std::vector<SUnit> &sunits);
1493 void addNode(const SUnit *SU);
1495 void updateNode(const SUnit *SU);
1497 void releaseState() {
1499 SethiUllmanNumbers.clear();
1500 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1503 unsigned getNodePriority(const SUnit *SU) const;
1505 unsigned getNodeOrdering(const SUnit *SU) const {
1506 if (!SU->getNode()) return 0;
1508 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1511 bool empty() const { return Queue.empty(); }
1513 void push(SUnit *U) {
1514 assert(!U->NodeQueueId && "Node in the queue already");
1515 U->NodeQueueId = ++CurQueueId;
1519 void remove(SUnit *SU) {
1520 assert(!Queue.empty() && "Queue is empty!");
1521 assert(SU->NodeQueueId != 0 && "Not in queue!");
1522 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1524 if (I != prior(Queue.end()))
1525 std::swap(*I, Queue.back());
1527 SU->NodeQueueId = 0;
1530 bool tracksRegPressure() const { return TracksRegPressure; }
1532 void dumpRegPressure() const;
1534 bool HighRegPressure(const SUnit *SU) const;
1536 bool MayReduceRegPressure(SUnit *SU) const;
1538 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1540 void ScheduledNode(SUnit *SU);
1542 void UnscheduledNode(SUnit *SU);
1545 bool canClobber(const SUnit *SU, const SUnit *Op);
1546 void AddPseudoTwoAddrDeps();
1547 void PrescheduleNodesWithMultipleUses();
1548 void CalculateSethiUllmanNumbers();
1552 class RegReductionPriorityQueue : public RegReductionPQBase {
1553 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1554 std::vector<SUnit *>::iterator Best = Q.begin();
1555 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1556 E = Q.end(); I != E; ++I)
1557 if (Picker(*Best, *I))
1560 if (Best != prior(Q.end()))
1561 std::swap(*Best, Q.back());
1569 RegReductionPriorityQueue(MachineFunction &mf,
1571 const TargetInstrInfo *tii,
1572 const TargetRegisterInfo *tri,
1573 const TargetLowering *tli)
1574 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1577 bool isBottomUp() const { return SF::IsBottomUp; }
1579 bool isReady(SUnit *U) const {
1580 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1584 if (Queue.empty()) return NULL;
1586 SUnit *V = popFromQueue(Queue, Picker);
1591 void dump(ScheduleDAG *DAG) const {
1592 // Emulate pop() without clobbering NodeQueueIds.
1593 std::vector<SUnit*> DumpQueue = Queue;
1594 SF DumpPicker = Picker;
1595 while (!DumpQueue.empty()) {
1596 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1598 dbgs() << "Height " << SU->getHeight() << ": ";
1600 dbgs() << "Depth " << SU->getDepth() << ": ";
1606 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1607 BURegReductionPriorityQueue;
1609 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1610 TDRegReductionPriorityQueue;
1612 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1613 SrcRegReductionPriorityQueue;
1615 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1616 HybridBURRPriorityQueue;
1618 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1619 ILPBURRPriorityQueue;
1620 } // end anonymous namespace
1622 //===----------------------------------------------------------------------===//
1623 // Static Node Priority for Register Pressure Reduction
1624 //===----------------------------------------------------------------------===//
1626 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1627 /// Smaller number is the higher priority.
1629 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1630 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1631 if (SethiUllmanNumber != 0)
1632 return SethiUllmanNumber;
1635 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1637 if (I->isCtrl()) continue; // ignore chain preds
1638 SUnit *PredSU = I->getSUnit();
1639 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1640 if (PredSethiUllman > SethiUllmanNumber) {
1641 SethiUllmanNumber = PredSethiUllman;
1643 } else if (PredSethiUllman == SethiUllmanNumber)
1647 SethiUllmanNumber += Extra;
1649 if (SethiUllmanNumber == 0)
1650 SethiUllmanNumber = 1;
1652 return SethiUllmanNumber;
1655 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1656 /// scheduling units.
1657 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1658 SethiUllmanNumbers.assign(SUnits->size(), 0);
1660 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1661 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1664 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1666 // Add pseudo dependency edges for two-address nodes.
1667 AddPseudoTwoAddrDeps();
1668 // Reroute edges to nodes with multiple uses.
1669 if (!TracksRegPressure)
1670 PrescheduleNodesWithMultipleUses();
1671 // Calculate node priorities.
1672 CalculateSethiUllmanNumbers();
1675 void RegReductionPQBase::addNode(const SUnit *SU) {
1676 unsigned SUSize = SethiUllmanNumbers.size();
1677 if (SUnits->size() > SUSize)
1678 SethiUllmanNumbers.resize(SUSize*2, 0);
1679 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1682 void RegReductionPQBase::updateNode(const SUnit *SU) {
1683 SethiUllmanNumbers[SU->NodeNum] = 0;
1684 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1687 // Lower priority means schedule further down. For bottom-up scheduling, lower
1688 // priority SUs are scheduled before higher priority SUs.
1689 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1690 assert(SU->NodeNum < SethiUllmanNumbers.size());
1691 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1692 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1693 // CopyToReg should be close to its uses to facilitate coalescing and
1696 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1697 Opc == TargetOpcode::SUBREG_TO_REG ||
1698 Opc == TargetOpcode::INSERT_SUBREG)
1699 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1700 // close to their uses to facilitate coalescing.
1702 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1703 // If SU does not have a register use, i.e. it doesn't produce a value
1704 // that would be consumed (e.g. store), then it terminates a chain of
1705 // computation. Give it a large SethiUllman number so it will be
1706 // scheduled right before its predecessors that it doesn't lengthen
1707 // their live ranges.
1709 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1710 // If SU does not have a register def, schedule it close to its uses
1711 // because it does not lengthen any live ranges.
1713 return SethiUllmanNumbers[SU->NodeNum];
1716 //===----------------------------------------------------------------------===//
1717 // Register Pressure Tracking
1718 //===----------------------------------------------------------------------===//
1720 void RegReductionPQBase::dumpRegPressure() const {
1721 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1722 E = TRI->regclass_end(); I != E; ++I) {
1723 const TargetRegisterClass *RC = *I;
1724 unsigned Id = RC->getID();
1725 unsigned RP = RegPressure[Id];
1727 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1732 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1736 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1740 SUnit *PredSU = I->getSUnit();
1741 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1742 // to cover the number of registers defined (they are all live).
1743 if (PredSU->NumRegDefsLeft == 0) {
1746 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1747 RegDefPos.IsValid(); RegDefPos.Advance()) {
1748 EVT VT = RegDefPos.GetValue();
1749 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1750 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1751 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1758 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1759 const SDNode *N = SU->getNode();
1761 if (!N->isMachineOpcode() || !SU->NumSuccs)
1764 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1765 for (unsigned i = 0; i != NumDefs; ++i) {
1766 EVT VT = N->getValueType(i);
1767 if (!N->hasAnyUseOfValue(i))
1769 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1770 if (RegPressure[RCId] >= RegLimit[RCId])
1776 // Compute the register pressure contribution by this instruction by count up
1777 // for uses that are not live and down for defs. Only count register classes
1778 // that are already under high pressure. As a side effect, compute the number of
1779 // uses of registers that are already live.
1781 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1782 // so could probably be factored.
1783 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1786 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1790 SUnit *PredSU = I->getSUnit();
1791 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1792 // to cover the number of registers defined (they are all live).
1793 if (PredSU->NumRegDefsLeft == 0) {
1794 if (PredSU->getNode()->isMachineOpcode())
1798 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1799 RegDefPos.IsValid(); RegDefPos.Advance()) {
1800 EVT VT = RegDefPos.GetValue();
1801 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1802 if (RegPressure[RCId] >= RegLimit[RCId])
1806 const SDNode *N = SU->getNode();
1808 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1811 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1812 for (unsigned i = 0; i != NumDefs; ++i) {
1813 EVT VT = N->getValueType(i);
1814 if (!N->hasAnyUseOfValue(i))
1816 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1817 if (RegPressure[RCId] >= RegLimit[RCId])
1823 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1824 if (!TracksRegPressure)
1830 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1834 SUnit *PredSU = I->getSUnit();
1835 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1836 // to cover the number of registers defined (they are all live).
1837 if (PredSU->NumRegDefsLeft == 0) {
1840 // FIXME: The ScheduleDAG currently loses information about which of a
1841 // node's values is consumed by each dependence. Consequently, if the node
1842 // defines multiple register classes, we don't know which to pressurize
1843 // here. Instead the following loop consumes the register defs in an
1844 // arbitrary order. At least it handles the common case of clustered loads
1845 // to the same class. For precise liveness, each SDep needs to indicate the
1846 // result number. But that tightly couples the ScheduleDAG with the
1847 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1848 // value type or register class to SDep.
1850 // The most important aspect of register tracking is balancing the increase
1851 // here with the reduction further below. Note that this SU may use multiple
1852 // defs in PredSU. The can't be determined here, but we've already
1853 // compensated by reducing NumRegDefsLeft in PredSU during
1854 // ScheduleDAGSDNodes::AddSchedEdges.
1855 --PredSU->NumRegDefsLeft;
1856 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1857 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1858 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1861 EVT VT = RegDefPos.GetValue();
1862 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1863 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1868 // We should have this assert, but there may be dead SDNodes that never
1869 // materialize as SUnits, so they don't appear to generate liveness.
1870 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1871 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1872 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1873 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1874 if (SkipRegDefs > 0)
1876 EVT VT = RegDefPos.GetValue();
1877 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1878 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1879 // Register pressure tracking is imprecise. This can happen. But we try
1880 // hard not to let it happen because it likely results in poor scheduling.
1881 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1882 RegPressure[RCId] = 0;
1885 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1891 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1892 if (!TracksRegPressure)
1895 const SDNode *N = SU->getNode();
1898 if (!N->isMachineOpcode()) {
1899 if (N->getOpcode() != ISD::CopyToReg)
1902 unsigned Opc = N->getMachineOpcode();
1903 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1904 Opc == TargetOpcode::INSERT_SUBREG ||
1905 Opc == TargetOpcode::SUBREG_TO_REG ||
1906 Opc == TargetOpcode::REG_SEQUENCE ||
1907 Opc == TargetOpcode::IMPLICIT_DEF)
1911 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1915 SUnit *PredSU = I->getSUnit();
1916 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1917 // counts data deps.
1918 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1920 const SDNode *PN = PredSU->getNode();
1921 if (!PN->isMachineOpcode()) {
1922 if (PN->getOpcode() == ISD::CopyFromReg) {
1923 EVT VT = PN->getValueType(0);
1924 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1925 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1929 unsigned POpc = PN->getMachineOpcode();
1930 if (POpc == TargetOpcode::IMPLICIT_DEF)
1932 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1933 EVT VT = PN->getOperand(0).getValueType();
1934 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1935 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1937 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1938 POpc == TargetOpcode::SUBREG_TO_REG) {
1939 EVT VT = PN->getValueType(0);
1940 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1941 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1944 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1945 for (unsigned i = 0; i != NumDefs; ++i) {
1946 EVT VT = PN->getValueType(i);
1947 if (!PN->hasAnyUseOfValue(i))
1949 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1950 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1951 // Register pressure tracking is imprecise. This can happen.
1952 RegPressure[RCId] = 0;
1954 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1958 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1959 // may transfer data dependencies to CopyToReg.
1960 if (SU->NumSuccs && N->isMachineOpcode()) {
1961 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1962 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1963 EVT VT = N->getValueType(i);
1964 if (VT == MVT::Glue || VT == MVT::Other)
1966 if (!N->hasAnyUseOfValue(i))
1968 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1969 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1976 //===----------------------------------------------------------------------===//
1977 // Dynamic Node Priority for Register Pressure Reduction
1978 //===----------------------------------------------------------------------===//
1980 /// closestSucc - Returns the scheduled cycle of the successor which is
1981 /// closest to the current cycle.
1982 static unsigned closestSucc(const SUnit *SU) {
1983 unsigned MaxHeight = 0;
1984 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1986 if (I->isCtrl()) continue; // ignore chain succs
1987 unsigned Height = I->getSUnit()->getHeight();
1988 // If there are bunch of CopyToRegs stacked up, they should be considered
1989 // to be at the same position.
1990 if (I->getSUnit()->getNode() &&
1991 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1992 Height = closestSucc(I->getSUnit())+1;
1993 if (Height > MaxHeight)
1999 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2000 /// for scratch registers, i.e. number of data dependencies.
2001 static unsigned calcMaxScratches(const SUnit *SU) {
2002 unsigned Scratches = 0;
2003 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2005 if (I->isCtrl()) continue; // ignore chain preds
2011 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
2012 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2013 /// it has no other use. It should be scheduled closer to the terminator.
2014 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2015 bool RetVal = false;
2016 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2018 if (I->isCtrl()) continue;
2019 const SUnit *SuccSU = I->getSUnit();
2020 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2022 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2023 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2033 /// UnitsSharePred - Return true if the two scheduling units share a common
2034 /// data predecessor.
2035 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
2036 SmallSet<const SUnit*, 4> Preds;
2037 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
2039 if (I->isCtrl()) continue; // ignore chain preds
2040 Preds.insert(I->getSUnit());
2042 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
2044 if (I->isCtrl()) continue; // ignore chain preds
2045 if (Preds.count(I->getSUnit()))
2051 // Return true if the virtual register defined by VRCycleSU may interfere with
2054 // Note: We may consider two SU's that use the same value live into a loop as
2055 // interferng even though the value is not an induction variable. This is an
2056 // unfortunate consequence of scheduling on the selection DAG.
2057 static bool checkVRegCycleInterference(const SUnit *VRCycleSU,
2058 const SUnit *VRUseSU) {
2059 for (SUnit::const_pred_iterator I = VRCycleSU->Preds.begin(),
2060 E = VRCycleSU->Preds.end(); I != E; ++I) {
2061 if (I->isCtrl()) continue; // ignore chain preds
2062 SDNode *InNode = I->getSUnit()->getNode();
2063 if (!InNode || InNode->getOpcode() != ISD::CopyFromReg)
2065 for (SUnit::const_pred_iterator II = VRUseSU->Preds.begin(),
2066 EE = VRUseSU->Preds.end(); II != EE; ++II) {
2067 if (II->getSUnit() == I->getSUnit())
2074 // Compare the VRegCycle properties of the nodes.
2075 // Return -1 if left has higher priority, 1 if right has higher priority.
2076 // Return 0 if priority is equivalent.
2077 static int BUCompareVRegCycle(const SUnit *left, const SUnit *right) {
2078 if (left->isVRegCycle && !right->isVRegCycle) {
2079 if (checkVRegCycleInterference(left, right))
2082 else if (!left->isVRegCycle && right->isVRegCycle) {
2083 if (checkVRegCycleInterference(right, left))
2089 // Check for either a dependence (latency) or resource (hazard) stall.
2091 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2092 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2093 if ((int)SPQ->getCurCycle() < Height) return true;
2094 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2095 != ScheduleHazardRecognizer::NoHazard)
2100 // Return -1 if left has higher priority, 1 if right has higher priority.
2101 // Return 0 if latency-based priority is equivalent.
2102 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2103 RegReductionPQBase *SPQ) {
2104 // If the two nodes share an operand and one of them has a single
2105 // use that is a live out copy, favor the one that is live out. Otherwise
2106 // it will be difficult to eliminate the copy if the instruction is a
2107 // loop induction variable update. e.g.
2114 bool SharePred = UnitsSharePred(left, right);
2115 // FIXME: Only adjust if BB is a loop back edge.
2116 // FIXME: What's the cost of a copy?
2117 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
2118 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
2119 int LHeight = (int)left->getHeight() - LBonus;
2120 int RHeight = (int)right->getHeight() - RBonus;
2122 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2123 BUHasStall(left, LHeight, SPQ);
2124 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2125 BUHasStall(right, RHeight, SPQ);
2127 // If scheduling one of the node will cause a pipeline stall, delay it.
2128 // If scheduling either one of the node will cause a pipeline stall, sort
2129 // them according to their height.
2133 if (LHeight != RHeight)
2134 return LHeight > RHeight ? 1 : -1;
2138 // If either node is scheduling for latency, sort them by height/depth
2140 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2141 right->SchedulingPref == Sched::Latency)) {
2142 if (DisableSchedCycles) {
2143 if (LHeight != RHeight)
2144 return LHeight > RHeight ? 1 : -1;
2147 // If neither instruction stalls (!LStall && !RStall) then
2148 // its height is already covered so only its depth matters. We also reach
2149 // this if both stall but have the same height.
2150 unsigned LDepth = left->getDepth();
2151 unsigned RDepth = right->getDepth();
2152 if (LDepth != RDepth) {
2153 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2154 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2155 << ") depth " << RDepth << "\n");
2156 return LDepth < RDepth ? 1 : -1;
2159 if (left->Latency != right->Latency)
2160 return left->Latency > right->Latency ? 1 : -1;
2165 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2166 unsigned LPriority = SPQ->getNodePriority(left);
2167 unsigned RPriority = SPQ->getNodePriority(right);
2168 if (LPriority != RPriority) {
2169 DEBUG(++FactorCount[FactStatic]);
2170 return LPriority > RPriority;
2172 DEBUG(++FactorCount[FactOther]);
2174 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2179 // and the following instructions are both ready.
2183 // Then schedule t2 = op first.
2190 // This creates more short live intervals.
2191 unsigned LDist = closestSucc(left);
2192 unsigned RDist = closestSucc(right);
2194 return LDist < RDist;
2196 // How many registers becomes live when the node is scheduled.
2197 unsigned LScratch = calcMaxScratches(left);
2198 unsigned RScratch = calcMaxScratches(right);
2199 if (LScratch != RScratch)
2200 return LScratch > RScratch;
2202 if (!DisableSchedCycles) {
2203 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2208 if (left->getHeight() != right->getHeight())
2209 return left->getHeight() > right->getHeight();
2211 if (left->getDepth() != right->getDepth())
2212 return left->getDepth() < right->getDepth();
2215 assert(left->NodeQueueId && right->NodeQueueId &&
2216 "NodeQueueId cannot be zero");
2217 return (left->NodeQueueId > right->NodeQueueId);
2221 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2222 return BURRSort(left, right, SPQ);
2225 // Source order, otherwise bottom up.
2226 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2227 unsigned LOrder = SPQ->getNodeOrdering(left);
2228 unsigned ROrder = SPQ->getNodeOrdering(right);
2230 // Prefer an ordering where the lower the non-zero order number, the higher
2232 if ((LOrder || ROrder) && LOrder != ROrder)
2233 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2235 return BURRSort(left, right, SPQ);
2238 // If the time between now and when the instruction will be ready can cover
2239 // the spill code, then avoid adding it to the ready queue. This gives long
2240 // stalls highest priority and allows hoisting across calls. It should also
2241 // speed up processing the available queue.
2242 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2243 static const unsigned ReadyDelay = 3;
2245 if (SPQ->MayReduceRegPressure(SU)) return true;
2247 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2249 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2250 != ScheduleHazardRecognizer::NoHazard)
2256 // Return true if right should be scheduled with higher priority than left.
2257 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2258 if (left->isCall || right->isCall)
2259 // No way to compute latency of calls.
2260 return BURRSort(left, right, SPQ);
2262 bool LHigh = SPQ->HighRegPressure(left);
2263 bool RHigh = SPQ->HighRegPressure(right);
2264 // Avoid causing spills. If register pressure is high, schedule for
2265 // register pressure reduction.
2266 if (LHigh && !RHigh) {
2267 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2268 << right->NodeNum << ")\n");
2271 else if (!LHigh && RHigh) {
2272 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2273 << left->NodeNum << ")\n");
2277 if (!DisableSchedVRegCycle) {
2278 result = BUCompareVRegCycle(left, right);
2280 if (result == 0 && !LHigh && !RHigh) {
2281 result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2285 return BURRSort(left, right, SPQ);
2288 // Schedule as many instructions in each cycle as possible. So don't make an
2289 // instruction available unless it is ready in the current cycle.
2290 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2291 if (SU->getHeight() > CurCycle) return false;
2293 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2294 != ScheduleHazardRecognizer::NoHazard)
2300 static bool canEnableCoalescing(SUnit *SU) {
2301 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2302 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2303 // CopyToReg should be close to its uses to facilitate coalescing and
2307 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2308 Opc == TargetOpcode::SUBREG_TO_REG ||
2309 Opc == TargetOpcode::INSERT_SUBREG)
2310 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2311 // close to their uses to facilitate coalescing.
2314 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2315 // If SU does not have a register def, schedule it close to its uses
2316 // because it does not lengthen any live ranges.
2322 // list-ilp is currently an experimental scheduler that allows various
2323 // heuristics to be enabled prior to the normal register reduction logic.
2324 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2325 if (left->isCall || right->isCall)
2326 // No way to compute latency of calls.
2327 return BURRSort(left, right, SPQ);
2329 unsigned LLiveUses = 0, RLiveUses = 0;
2330 int LPDiff = 0, RPDiff = 0;
2331 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2332 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2333 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2335 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2336 DEBUG(++FactorCount[FactPressureDiff]);
2337 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2338 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2339 return LPDiff > RPDiff;
2342 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2343 bool LReduce = canEnableCoalescing(left);
2344 bool RReduce = canEnableCoalescing(right);
2345 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2346 if (LReduce && !RReduce) return false;
2347 if (RReduce && !LReduce) return true;
2350 if (!DisableSchedVRegCycle) {
2351 int result = BUCompareVRegCycle(left, right);
2356 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2357 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2358 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2359 DEBUG(++FactorCount[FactRegUses]);
2360 return LLiveUses < RLiveUses;
2363 if (!DisableSchedStalls) {
2364 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2365 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2366 if (LStall != RStall) {
2367 DEBUG(++FactorCount[FactHeight]);
2368 return left->getHeight() > right->getHeight();
2372 if (!DisableSchedCriticalPath) {
2373 int spread = (int)left->getDepth() - (int)right->getDepth();
2374 if (std::abs(spread) > MaxReorderWindow) {
2375 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2376 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2377 << right->getDepth() << "\n");
2378 DEBUG(++FactorCount[FactDepth]);
2379 return left->getDepth() < right->getDepth();
2383 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2384 int spread = (int)left->getHeight() - (int)right->getHeight();
2385 if (std::abs(spread) > MaxReorderWindow) {
2386 DEBUG(++FactorCount[FactHeight]);
2387 return left->getHeight() > right->getHeight();
2391 return BURRSort(left, right, SPQ);
2394 //===----------------------------------------------------------------------===//
2395 // Preschedule for Register Pressure
2396 //===----------------------------------------------------------------------===//
2398 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2399 if (SU->isTwoAddress) {
2400 unsigned Opc = SU->getNode()->getMachineOpcode();
2401 const TargetInstrDesc &TID = TII->get(Opc);
2402 unsigned NumRes = TID.getNumDefs();
2403 unsigned NumOps = TID.getNumOperands() - NumRes;
2404 for (unsigned i = 0; i != NumOps; ++i) {
2405 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2406 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2407 if (DU->getNodeId() != -1 &&
2408 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2416 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2417 /// physical register defs.
2418 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2419 const TargetInstrInfo *TII,
2420 const TargetRegisterInfo *TRI) {
2421 SDNode *N = SuccSU->getNode();
2422 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2423 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2424 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2425 for (const SDNode *SUNode = SU->getNode(); SUNode;
2426 SUNode = SUNode->getGluedNode()) {
2427 if (!SUNode->isMachineOpcode())
2429 const unsigned *SUImpDefs =
2430 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2433 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2434 EVT VT = N->getValueType(i);
2435 if (VT == MVT::Glue || VT == MVT::Other)
2437 if (!N->hasAnyUseOfValue(i))
2439 unsigned Reg = ImpDefs[i - NumDefs];
2440 for (;*SUImpDefs; ++SUImpDefs) {
2441 unsigned SUReg = *SUImpDefs;
2442 if (TRI->regsOverlap(Reg, SUReg))
2450 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2451 /// are not handled well by the general register pressure reduction
2452 /// heuristics. When presented with code like this:
2461 /// the heuristics tend to push the store up, but since the
2462 /// operand of the store has another use (U), this would increase
2463 /// the length of that other use (the U->N edge).
2465 /// This function transforms code like the above to route U's
2466 /// dependence through the store when possible, like this:
2477 /// This results in the store being scheduled immediately
2478 /// after N, which shortens the U->N live range, reducing
2479 /// register pressure.
2481 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2482 // Visit all the nodes in topological order, working top-down.
2483 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2484 SUnit *SU = &(*SUnits)[i];
2485 // For now, only look at nodes with no data successors, such as stores.
2486 // These are especially important, due to the heuristics in
2487 // getNodePriority for nodes with no data successors.
2488 if (SU->NumSuccs != 0)
2490 // For now, only look at nodes with exactly one data predecessor.
2491 if (SU->NumPreds != 1)
2493 // Avoid prescheduling copies to virtual registers, which don't behave
2494 // like other nodes from the perspective of scheduling heuristics.
2495 if (SDNode *N = SU->getNode())
2496 if (N->getOpcode() == ISD::CopyToReg &&
2497 TargetRegisterInfo::isVirtualRegister
2498 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2501 // Locate the single data predecessor.
2503 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2504 EE = SU->Preds.end(); II != EE; ++II)
2505 if (!II->isCtrl()) {
2506 PredSU = II->getSUnit();
2511 // Don't rewrite edges that carry physregs, because that requires additional
2512 // support infrastructure.
2513 if (PredSU->hasPhysRegDefs)
2515 // Short-circuit the case where SU is PredSU's only data successor.
2516 if (PredSU->NumSuccs == 1)
2518 // Avoid prescheduling to copies from virtual registers, which don't behave
2519 // like other nodes from the perspective of scheduling heuristics.
2520 if (SDNode *N = SU->getNode())
2521 if (N->getOpcode() == ISD::CopyFromReg &&
2522 TargetRegisterInfo::isVirtualRegister
2523 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2526 // Perform checks on the successors of PredSU.
2527 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2528 EE = PredSU->Succs.end(); II != EE; ++II) {
2529 SUnit *PredSuccSU = II->getSUnit();
2530 if (PredSuccSU == SU) continue;
2531 // If PredSU has another successor with no data successors, for
2532 // now don't attempt to choose either over the other.
2533 if (PredSuccSU->NumSuccs == 0)
2534 goto outer_loop_continue;
2535 // Don't break physical register dependencies.
2536 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2537 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2538 goto outer_loop_continue;
2539 // Don't introduce graph cycles.
2540 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2541 goto outer_loop_continue;
2544 // Ok, the transformation is safe and the heuristics suggest it is
2545 // profitable. Update the graph.
2546 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2547 << " next to PredSU #" << PredSU->NodeNum
2548 << " to guide scheduling in the presence of multiple uses\n");
2549 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2550 SDep Edge = PredSU->Succs[i];
2551 assert(!Edge.isAssignedRegDep());
2552 SUnit *SuccSU = Edge.getSUnit();
2554 Edge.setSUnit(PredSU);
2555 scheduleDAG->RemovePred(SuccSU, Edge);
2556 scheduleDAG->AddPred(SU, Edge);
2558 scheduleDAG->AddPred(SuccSU, Edge);
2562 outer_loop_continue:;
2566 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2567 /// it as a def&use operand. Add a pseudo control edge from it to the other
2568 /// node (if it won't create a cycle) so the two-address one will be scheduled
2569 /// first (lower in the schedule). If both nodes are two-address, favor the
2570 /// one that has a CopyToReg use (more likely to be a loop induction update).
2571 /// If both are two-address, but one is commutable while the other is not
2572 /// commutable, favor the one that's not commutable.
2573 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2574 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2575 SUnit *SU = &(*SUnits)[i];
2576 if (!SU->isTwoAddress)
2579 SDNode *Node = SU->getNode();
2580 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2583 bool isLiveOut = hasOnlyLiveOutUses(SU);
2584 unsigned Opc = Node->getMachineOpcode();
2585 const TargetInstrDesc &TID = TII->get(Opc);
2586 unsigned NumRes = TID.getNumDefs();
2587 unsigned NumOps = TID.getNumOperands() - NumRes;
2588 for (unsigned j = 0; j != NumOps; ++j) {
2589 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2591 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2592 if (DU->getNodeId() == -1)
2594 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2595 if (!DUSU) continue;
2596 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2597 E = DUSU->Succs.end(); I != E; ++I) {
2598 if (I->isCtrl()) continue;
2599 SUnit *SuccSU = I->getSUnit();
2602 // Be conservative. Ignore if nodes aren't at roughly the same
2603 // depth and height.
2604 if (SuccSU->getHeight() < SU->getHeight() &&
2605 (SU->getHeight() - SuccSU->getHeight()) > 1)
2607 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2608 // constrains whatever is using the copy, instead of the copy
2609 // itself. In the case that the copy is coalesced, this
2610 // preserves the intent of the pseudo two-address heurietics.
2611 while (SuccSU->Succs.size() == 1 &&
2612 SuccSU->getNode()->isMachineOpcode() &&
2613 SuccSU->getNode()->getMachineOpcode() ==
2614 TargetOpcode::COPY_TO_REGCLASS)
2615 SuccSU = SuccSU->Succs.front().getSUnit();
2616 // Don't constrain non-instruction nodes.
2617 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2619 // Don't constrain nodes with physical register defs if the
2620 // predecessor can clobber them.
2621 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2622 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2625 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2626 // these may be coalesced away. We want them close to their uses.
2627 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2628 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2629 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2630 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2632 if ((!canClobber(SuccSU, DUSU) ||
2633 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2634 (!SU->isCommutable && SuccSU->isCommutable)) &&
2635 !scheduleDAG->IsReachable(SuccSU, SU)) {
2636 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2637 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2638 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2639 /*Reg=*/0, /*isNormalMemory=*/false,
2640 /*isMustAlias=*/false,
2641 /*isArtificial=*/true));
2648 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2649 /// predecessors of the successors of the SUnit SU. Stop when the provided
2650 /// limit is exceeded.
2651 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2654 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2656 const SUnit *SuccSU = I->getSUnit();
2657 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2658 EE = SuccSU->Preds.end(); II != EE; ++II) {
2659 SUnit *PredSU = II->getSUnit();
2660 if (!PredSU->isScheduled)
2670 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2671 unsigned LPriority = SPQ->getNodePriority(left);
2672 unsigned RPriority = SPQ->getNodePriority(right);
2673 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2674 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2675 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2676 bool RIsFloater = RIsTarget && right->NumPreds == 0;
2677 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2678 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2680 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2682 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2689 if (left->NumSuccs == 1)
2691 if (right->NumSuccs == 1)
2694 if (LPriority+LBonus != RPriority+RBonus)
2695 return LPriority+LBonus < RPriority+RBonus;
2697 if (left->getDepth() != right->getDepth())
2698 return left->getDepth() < right->getDepth();
2700 if (left->NumSuccsLeft != right->NumSuccsLeft)
2701 return left->NumSuccsLeft > right->NumSuccsLeft;
2703 assert(left->NodeQueueId && right->NodeQueueId &&
2704 "NodeQueueId cannot be zero");
2705 return (left->NodeQueueId > right->NodeQueueId);
2708 //===----------------------------------------------------------------------===//
2709 // Public Constructor Functions
2710 //===----------------------------------------------------------------------===//
2712 llvm::ScheduleDAGSDNodes *
2713 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2714 CodeGenOpt::Level OptLevel) {
2715 const TargetMachine &TM = IS->TM;
2716 const TargetInstrInfo *TII = TM.getInstrInfo();
2717 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2719 BURegReductionPriorityQueue *PQ =
2720 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2721 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2722 PQ->setScheduleDAG(SD);
2726 llvm::ScheduleDAGSDNodes *
2727 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2728 CodeGenOpt::Level OptLevel) {
2729 const TargetMachine &TM = IS->TM;
2730 const TargetInstrInfo *TII = TM.getInstrInfo();
2731 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2733 TDRegReductionPriorityQueue *PQ =
2734 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2735 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2736 PQ->setScheduleDAG(SD);
2740 llvm::ScheduleDAGSDNodes *
2741 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2742 CodeGenOpt::Level OptLevel) {
2743 const TargetMachine &TM = IS->TM;
2744 const TargetInstrInfo *TII = TM.getInstrInfo();
2745 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2747 SrcRegReductionPriorityQueue *PQ =
2748 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2749 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2750 PQ->setScheduleDAG(SD);
2754 llvm::ScheduleDAGSDNodes *
2755 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2756 CodeGenOpt::Level OptLevel) {
2757 const TargetMachine &TM = IS->TM;
2758 const TargetInstrInfo *TII = TM.getInstrInfo();
2759 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2760 const TargetLowering *TLI = &IS->getTargetLowering();
2762 HybridBURRPriorityQueue *PQ =
2763 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2765 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2766 PQ->setScheduleDAG(SD);
2770 llvm::ScheduleDAGSDNodes *
2771 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2772 CodeGenOpt::Level OptLevel) {
2773 const TargetMachine &TM = IS->TM;
2774 const TargetInstrInfo *TII = TM.getInstrInfo();
2775 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2776 const TargetLowering *TLI = &IS->getTargetLowering();
2778 ILPBURRPriorityQueue *PQ =
2779 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2780 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2781 PQ->setScheduleDAG(SD);