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"));
74 //===----------------------------------------------------------------------===//
75 /// ScheduleDAGRRList - The actual register reduction list scheduler
76 /// implementation. This supports both top-down and bottom-up scheduling.
78 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
80 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
84 /// NeedLatency - True if the scheduler will make use of latency information.
88 /// AvailableQueue - The priority queue to use for the available SUnits.
89 SchedulingPriorityQueue *AvailableQueue;
91 /// PendingQueue - This contains all of the instructions whose operands have
92 /// been issued, but their results are not ready yet (due to the latency of
93 /// the operation). Once the operands becomes available, the instruction is
94 /// added to the AvailableQueue.
95 std::vector<SUnit*> PendingQueue;
97 /// HazardRec - The hazard recognizer to use.
98 ScheduleHazardRecognizer *HazardRec;
100 /// CurCycle - The current scheduler state corresponds to this cycle.
103 /// MinAvailableCycle - Cycle of the soonest available instruction.
104 unsigned MinAvailableCycle;
106 /// LiveRegDefs - A set of physical registers and their definition
107 /// that are "live". These nodes must be scheduled before any other nodes that
108 /// modifies the registers can be scheduled.
109 unsigned NumLiveRegs;
110 std::vector<SUnit*> LiveRegDefs;
111 std::vector<SUnit*> LiveRegGens;
113 /// Topo - A topological ordering for SUnits which permits fast IsReachable
114 /// and similar queries.
115 ScheduleDAGTopologicalSort Topo;
118 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
119 SchedulingPriorityQueue *availqueue,
120 CodeGenOpt::Level OptLevel)
121 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
122 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
125 const TargetMachine &tm = mf.getTarget();
126 if (DisableSchedCycles || !NeedLatency)
127 HazardRec = new ScheduleHazardRecognizer();
129 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
132 ~ScheduleDAGRRList() {
134 delete AvailableQueue;
139 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
141 /// IsReachable - Checks if SU is reachable from TargetSU.
142 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
143 return Topo.IsReachable(SU, TargetSU);
146 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
148 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
149 return Topo.WillCreateCycle(SU, TargetSU);
152 /// AddPred - adds a predecessor edge to SUnit SU.
153 /// This returns true if this is a new predecessor.
154 /// Updates the topological ordering if required.
155 void AddPred(SUnit *SU, const SDep &D) {
156 Topo.AddPred(SU, D.getSUnit());
160 /// RemovePred - removes a predecessor edge from SUnit SU.
161 /// This returns true if an edge was removed.
162 /// Updates the topological ordering if required.
163 void RemovePred(SUnit *SU, const SDep &D) {
164 Topo.RemovePred(SU, D.getSUnit());
169 bool isReady(SUnit *SU) {
170 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
171 AvailableQueue->isReady(SU);
174 void ReleasePred(SUnit *SU, const SDep *PredEdge);
175 void ReleasePredecessors(SUnit *SU);
176 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
177 void ReleaseSuccessors(SUnit *SU);
178 void ReleasePending();
179 void AdvanceToCycle(unsigned NextCycle);
180 void AdvancePastStalls(SUnit *SU);
181 void EmitNode(SUnit *SU);
182 void ScheduleNodeBottomUp(SUnit*);
183 void CapturePred(SDep *PredEdge);
184 void UnscheduleNodeBottomUp(SUnit*);
185 void RestoreHazardCheckerBottomUp();
186 void BacktrackBottomUp(SUnit*, SUnit*);
187 SUnit *CopyAndMoveSuccessors(SUnit*);
188 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
189 const TargetRegisterClass*,
190 const TargetRegisterClass*,
191 SmallVector<SUnit*, 2>&);
192 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
194 SUnit *PickNodeToScheduleBottomUp();
195 void ListScheduleBottomUp();
197 void ScheduleNodeTopDown(SUnit*);
198 void ListScheduleTopDown();
201 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
202 /// Updates the topological ordering if required.
203 SUnit *CreateNewSUnit(SDNode *N) {
204 unsigned NumSUnits = SUnits.size();
205 SUnit *NewNode = NewSUnit(N);
206 // Update the topological ordering.
207 if (NewNode->NodeNum >= NumSUnits)
208 Topo.InitDAGTopologicalSorting();
212 /// CreateClone - Creates a new SUnit from an existing one.
213 /// Updates the topological ordering if required.
214 SUnit *CreateClone(SUnit *N) {
215 unsigned NumSUnits = SUnits.size();
216 SUnit *NewNode = Clone(N);
217 // Update the topological ordering.
218 if (NewNode->NodeNum >= NumSUnits)
219 Topo.InitDAGTopologicalSorting();
223 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
224 /// need actual latency information but the hybrid scheduler does.
225 bool ForceUnitLatencies() const {
229 } // end anonymous namespace
232 /// Schedule - Schedule the DAG using list scheduling.
233 void ScheduleDAGRRList::Schedule() {
235 << "********** List Scheduling BB#" << BB->getNumber()
236 << " '" << BB->getName() << "' **********\n");
239 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
241 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
242 LiveRegGens.resize(TRI->getNumRegs(), NULL);
244 // Build the scheduling graph.
245 BuildSchedGraph(NULL);
247 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
248 SUnits[su].dumpAll(this));
249 Topo.InitDAGTopologicalSorting();
251 AvailableQueue->initNodes(SUnits);
255 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
257 ListScheduleBottomUp();
259 ListScheduleTopDown();
261 AvailableQueue->releaseState();
264 //===----------------------------------------------------------------------===//
265 // Bottom-Up Scheduling
266 //===----------------------------------------------------------------------===//
268 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
269 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
270 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
271 SUnit *PredSU = PredEdge->getSUnit();
274 if (PredSU->NumSuccsLeft == 0) {
275 dbgs() << "*** Scheduling failed! ***\n";
277 dbgs() << " has been released too many times!\n";
281 --PredSU->NumSuccsLeft;
283 if (!ForceUnitLatencies()) {
284 // Updating predecessor's height. This is now the cycle when the
285 // predecessor can be scheduled without causing a pipeline stall.
286 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
289 // If all the node's successors are scheduled, this node is ready
290 // to be scheduled. Ignore the special EntrySU node.
291 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
292 PredSU->isAvailable = true;
294 unsigned Height = PredSU->getHeight();
295 if (Height < MinAvailableCycle)
296 MinAvailableCycle = Height;
298 if (isReady(PredSU)) {
299 AvailableQueue->push(PredSU);
301 // CapturePred and others may have left the node in the pending queue, avoid
303 else if (!PredSU->isPending) {
304 PredSU->isPending = true;
305 PendingQueue.push_back(PredSU);
310 /// Call ReleasePred for each predecessor, then update register live def/gen.
311 /// Always update LiveRegDefs for a register dependence even if the current SU
312 /// also defines the register. This effectively create one large live range
313 /// across a sequence of two-address node. This is important because the
314 /// entire chain must be scheduled together. Example:
317 /// flags = (2) addc flags
318 /// flags = (1) addc flags
322 /// LiveRegDefs[flags] = 3
323 /// LiveRegGens[flags] = 1
325 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
326 /// interference on flags.
327 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
328 // Bottom up: release predecessors
329 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
331 ReleasePred(SU, &*I);
332 if (I->isAssignedRegDep()) {
333 // This is a physical register dependency and it's impossible or
334 // expensive to copy the register. Make sure nothing that can
335 // clobber the register is scheduled between the predecessor and
337 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
338 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
339 "interference on register dependence");
340 LiveRegDefs[I->getReg()] = I->getSUnit();
341 if (!LiveRegGens[I->getReg()]) {
343 LiveRegGens[I->getReg()] = SU;
349 /// Check to see if any of the pending instructions are ready to issue. If
350 /// so, add them to the available queue.
351 void ScheduleDAGRRList::ReleasePending() {
352 if (DisableSchedCycles) {
353 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
357 // If the available queue is empty, it is safe to reset MinAvailableCycle.
358 if (AvailableQueue->empty())
359 MinAvailableCycle = UINT_MAX;
361 // Check to see if any of the pending instructions are ready to issue. If
362 // so, add them to the available queue.
363 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
364 unsigned ReadyCycle =
365 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
366 if (ReadyCycle < MinAvailableCycle)
367 MinAvailableCycle = ReadyCycle;
369 if (PendingQueue[i]->isAvailable) {
370 if (!isReady(PendingQueue[i]))
372 AvailableQueue->push(PendingQueue[i]);
374 PendingQueue[i]->isPending = false;
375 PendingQueue[i] = PendingQueue.back();
376 PendingQueue.pop_back();
381 /// Move the scheduler state forward by the specified number of Cycles.
382 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
383 if (NextCycle <= CurCycle)
386 AvailableQueue->setCurCycle(NextCycle);
387 if (!HazardRec->isEnabled()) {
388 // Bypass lots of virtual calls in case of long latency.
389 CurCycle = NextCycle;
392 for (; CurCycle != NextCycle; ++CurCycle) {
394 HazardRec->RecedeCycle();
396 HazardRec->AdvanceCycle();
399 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
400 // available Q to release pending nodes at least once before popping.
404 /// Move the scheduler state forward until the specified node's dependents are
405 /// ready and can be scheduled with no resource conflicts.
406 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
407 if (DisableSchedCycles)
410 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
412 // Bump CurCycle to account for latency. We assume the latency of other
413 // available instructions may be hidden by the stall (not a full pipe stall).
414 // This updates the hazard recognizer's cycle before reserving resources for
416 AdvanceToCycle(ReadyCycle);
418 // Calls are scheduled in their preceding cycle, so don't conflict with
419 // hazards from instructions after the call. EmitNode will reset the
420 // scoreboard state before emitting the call.
421 if (isBottomUp && SU->isCall)
424 // FIXME: For resource conflicts in very long non-pipelined stages, we
425 // should probably skip ahead here to avoid useless scoreboard checks.
428 ScheduleHazardRecognizer::HazardType HT =
429 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
431 if (HT == ScheduleHazardRecognizer::NoHazard)
436 AdvanceToCycle(CurCycle + Stalls);
439 /// Record this SUnit in the HazardRecognizer.
440 /// Does not update CurCycle.
441 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
442 if (!HazardRec->isEnabled())
445 // Check for phys reg copy.
449 switch (SU->getNode()->getOpcode()) {
451 assert(SU->getNode()->isMachineOpcode() &&
452 "This target-independent node should not be scheduled.");
454 case ISD::MERGE_VALUES:
455 case ISD::TokenFactor:
457 case ISD::CopyFromReg:
459 // Noops don't affect the scoreboard state. Copies are likely to be
463 // For inline asm, clear the pipeline state.
467 if (isBottomUp && SU->isCall) {
468 // Calls are scheduled with their preceding instructions. For bottom-up
469 // scheduling, clear the pipeline state before emitting.
473 HazardRec->EmitInstruction(SU);
475 if (!isBottomUp && SU->isCall) {
480 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
481 /// count of its predecessors. If a predecessor pending count is zero, add it to
482 /// the Available queue.
483 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
484 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
485 DEBUG(SU->dump(this));
488 if (CurCycle < SU->getHeight())
489 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
492 // FIXME: Do not modify node height. It may interfere with
493 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
494 // node it's ready cycle can aid heuristics, and after scheduling it can
495 // indicate the scheduled cycle.
496 SU->setHeightToAtLeast(CurCycle);
498 // Reserve resources for the scheduled intruction.
501 Sequence.push_back(SU);
503 AvailableQueue->ScheduledNode(SU);
505 // If HazardRec is disabled, count each inst as one cycle.
506 // Advance CurCycle before ReleasePredecessors to avoid useles pushed to
507 // PendingQueue for schedulers that implement HasReadyFilter.
508 if (!HazardRec->isEnabled())
509 AdvanceToCycle(CurCycle + 1);
511 // Update liveness of predecessors before successors to avoid treating a
512 // two-address node as a live range def.
513 ReleasePredecessors(SU);
515 // Release all the implicit physical register defs that are live.
516 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
518 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
519 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
520 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
522 LiveRegDefs[I->getReg()] = NULL;
523 LiveRegGens[I->getReg()] = NULL;
527 SU->isScheduled = true;
529 // Conditions under which the scheduler should eagerly advance the cycle:
530 // (1) No available instructions
531 // (2) All pipelines full, so available instructions must have hazards.
533 // If HazardRec is disabled, the cycle was advanced earlier.
535 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
536 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
537 || AvailableQueue->empty())
538 AdvanceToCycle(CurCycle + 1);
541 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
542 /// unscheduled, incrcease the succ left count of its predecessors. Remove
543 /// them from AvailableQueue if necessary.
544 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
545 SUnit *PredSU = PredEdge->getSUnit();
546 if (PredSU->isAvailable) {
547 PredSU->isAvailable = false;
548 if (!PredSU->isPending)
549 AvailableQueue->remove(PredSU);
552 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
553 ++PredSU->NumSuccsLeft;
556 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
557 /// its predecessor states to reflect the change.
558 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
559 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
560 DEBUG(SU->dump(this));
562 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
565 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
566 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
567 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
568 "Physical register dependency violated?");
570 LiveRegDefs[I->getReg()] = NULL;
571 LiveRegGens[I->getReg()] = NULL;
575 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
577 if (I->isAssignedRegDep()) {
578 // This becomes the nearest def. Note that an earlier def may still be
579 // pending if this is a two-address node.
580 LiveRegDefs[I->getReg()] = SU;
581 if (!LiveRegDefs[I->getReg()]) {
584 if (LiveRegGens[I->getReg()] == NULL ||
585 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
586 LiveRegGens[I->getReg()] = I->getSUnit();
589 if (SU->getHeight() < MinAvailableCycle)
590 MinAvailableCycle = SU->getHeight();
592 SU->setHeightDirty();
593 SU->isScheduled = false;
594 SU->isAvailable = true;
595 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
596 // Don't make available until backtracking is complete.
597 SU->isPending = true;
598 PendingQueue.push_back(SU);
601 AvailableQueue->push(SU);
603 AvailableQueue->UnscheduledNode(SU);
606 /// After backtracking, the hazard checker needs to be restored to a state
607 /// corresponding the the current cycle.
608 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
611 unsigned LookAhead = std::min((unsigned)Sequence.size(),
612 HazardRec->getMaxLookAhead());
616 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
617 unsigned HazardCycle = (*I)->getHeight();
618 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
620 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
621 HazardRec->RecedeCycle();
627 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
628 /// BTCycle in order to schedule a specific node.
629 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
630 SUnit *OldSU = Sequence.back();
633 if (SU->isSucc(OldSU))
634 // Don't try to remove SU from AvailableQueue.
635 SU->isAvailable = false;
636 // FIXME: use ready cycle instead of height
637 CurCycle = OldSU->getHeight();
638 UnscheduleNodeBottomUp(OldSU);
639 AvailableQueue->setCurCycle(CurCycle);
642 OldSU = Sequence.back();
645 assert(!SU->isSucc(OldSU) && "Something is wrong!");
647 RestoreHazardCheckerBottomUp();
654 static bool isOperandOf(const SUnit *SU, SDNode *N) {
655 for (const SDNode *SUNode = SU->getNode(); SUNode;
656 SUNode = SUNode->getGluedNode()) {
657 if (SUNode->isOperandOf(N))
663 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
664 /// successors to the newly created node.
665 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
666 SDNode *N = SU->getNode();
670 if (SU->getNode()->getGluedNode())
674 bool TryUnfold = false;
675 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
676 EVT VT = N->getValueType(i);
679 else if (VT == MVT::Other)
682 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
683 const SDValue &Op = N->getOperand(i);
684 EVT VT = Op.getNode()->getValueType(Op.getResNo());
690 SmallVector<SDNode*, 2> NewNodes;
691 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
694 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
695 assert(NewNodes.size() == 2 && "Expected a load folding node!");
698 SDNode *LoadNode = NewNodes[0];
699 unsigned NumVals = N->getNumValues();
700 unsigned OldNumVals = SU->getNode()->getNumValues();
701 for (unsigned i = 0; i != NumVals; ++i)
702 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
703 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
704 SDValue(LoadNode, 1));
706 // LoadNode may already exist. This can happen when there is another
707 // load from the same location and producing the same type of value
708 // but it has different alignment or volatileness.
709 bool isNewLoad = true;
711 if (LoadNode->getNodeId() != -1) {
712 LoadSU = &SUnits[LoadNode->getNodeId()];
715 LoadSU = CreateNewSUnit(LoadNode);
716 LoadNode->setNodeId(LoadSU->NodeNum);
718 InitNumRegDefsLeft(LoadSU);
719 ComputeLatency(LoadSU);
722 SUnit *NewSU = CreateNewSUnit(N);
723 assert(N->getNodeId() == -1 && "Node already inserted!");
724 N->setNodeId(NewSU->NodeNum);
726 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
727 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
728 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
729 NewSU->isTwoAddress = true;
733 if (TID.isCommutable())
734 NewSU->isCommutable = true;
736 InitNumRegDefsLeft(NewSU);
737 ComputeLatency(NewSU);
739 // Record all the edges to and from the old SU, by category.
740 SmallVector<SDep, 4> ChainPreds;
741 SmallVector<SDep, 4> ChainSuccs;
742 SmallVector<SDep, 4> LoadPreds;
743 SmallVector<SDep, 4> NodePreds;
744 SmallVector<SDep, 4> NodeSuccs;
745 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
748 ChainPreds.push_back(*I);
749 else if (isOperandOf(I->getSUnit(), LoadNode))
750 LoadPreds.push_back(*I);
752 NodePreds.push_back(*I);
754 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
757 ChainSuccs.push_back(*I);
759 NodeSuccs.push_back(*I);
762 // Now assign edges to the newly-created nodes.
763 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
764 const SDep &Pred = ChainPreds[i];
765 RemovePred(SU, Pred);
767 AddPred(LoadSU, Pred);
769 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
770 const SDep &Pred = LoadPreds[i];
771 RemovePred(SU, Pred);
773 AddPred(LoadSU, Pred);
775 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
776 const SDep &Pred = NodePreds[i];
777 RemovePred(SU, Pred);
778 AddPred(NewSU, Pred);
780 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
781 SDep D = NodeSuccs[i];
782 SUnit *SuccDep = D.getSUnit();
784 RemovePred(SuccDep, D);
787 // Balance register pressure.
788 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
789 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
790 --NewSU->NumRegDefsLeft;
792 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
793 SDep D = ChainSuccs[i];
794 SUnit *SuccDep = D.getSUnit();
796 RemovePred(SuccDep, D);
803 // Add a data dependency to reflect that NewSU reads the value defined
805 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
808 AvailableQueue->addNode(LoadSU);
809 AvailableQueue->addNode(NewSU);
813 if (NewSU->NumSuccsLeft == 0) {
814 NewSU->isAvailable = true;
820 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
821 NewSU = CreateClone(SU);
823 // New SUnit has the exact same predecessors.
824 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
826 if (!I->isArtificial())
829 // Only copy scheduled successors. Cut them from old node's successor
830 // list and move them over.
831 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
832 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
834 if (I->isArtificial())
836 SUnit *SuccSU = I->getSUnit();
837 if (SuccSU->isScheduled) {
842 DelDeps.push_back(std::make_pair(SuccSU, D));
845 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
846 RemovePred(DelDeps[i].first, DelDeps[i].second);
848 AvailableQueue->updateNode(SU);
849 AvailableQueue->addNode(NewSU);
855 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
856 /// scheduled successors of the given SUnit to the last copy.
857 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
858 const TargetRegisterClass *DestRC,
859 const TargetRegisterClass *SrcRC,
860 SmallVector<SUnit*, 2> &Copies) {
861 SUnit *CopyFromSU = CreateNewSUnit(NULL);
862 CopyFromSU->CopySrcRC = SrcRC;
863 CopyFromSU->CopyDstRC = DestRC;
865 SUnit *CopyToSU = CreateNewSUnit(NULL);
866 CopyToSU->CopySrcRC = DestRC;
867 CopyToSU->CopyDstRC = SrcRC;
869 // Only copy scheduled successors. Cut them from old node's successor
870 // list and move them over.
871 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
872 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
874 if (I->isArtificial())
876 SUnit *SuccSU = I->getSUnit();
877 if (SuccSU->isScheduled) {
879 D.setSUnit(CopyToSU);
881 DelDeps.push_back(std::make_pair(SuccSU, *I));
884 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
885 RemovePred(DelDeps[i].first, DelDeps[i].second);
887 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
888 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
890 AvailableQueue->updateNode(SU);
891 AvailableQueue->addNode(CopyFromSU);
892 AvailableQueue->addNode(CopyToSU);
893 Copies.push_back(CopyFromSU);
894 Copies.push_back(CopyToSU);
899 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
900 /// definition of the specified node.
901 /// FIXME: Move to SelectionDAG?
902 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
903 const TargetInstrInfo *TII) {
904 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
905 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
906 unsigned NumRes = TID.getNumDefs();
907 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
912 return N->getValueType(NumRes);
915 /// CheckForLiveRegDef - Return true and update live register vector if the
916 /// specified register def of the specified SUnit clobbers any "live" registers.
917 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
918 std::vector<SUnit*> &LiveRegDefs,
919 SmallSet<unsigned, 4> &RegAdded,
920 SmallVector<unsigned, 4> &LRegs,
921 const TargetRegisterInfo *TRI) {
922 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
924 // Check if Ref is live.
925 if (!LiveRegDefs[Reg]) continue;
927 // Allow multiple uses of the same def.
928 if (LiveRegDefs[Reg] == SU) continue;
930 // Add Reg to the set of interfering live regs.
931 if (RegAdded.insert(Reg))
932 LRegs.push_back(Reg);
936 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
937 /// scheduling of the given node to satisfy live physical register dependencies.
938 /// If the specific node is the last one that's available to schedule, do
939 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
940 bool ScheduleDAGRRList::
941 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
942 if (NumLiveRegs == 0)
945 SmallSet<unsigned, 4> RegAdded;
946 // If this node would clobber any "live" register, then it's not ready.
948 // If SU is the currently live definition of the same register that it uses,
949 // then we are free to schedule it.
950 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
952 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
953 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
954 RegAdded, LRegs, TRI);
957 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
958 if (Node->getOpcode() == ISD::INLINEASM) {
959 // Inline asm can clobber physical defs.
960 unsigned NumOps = Node->getNumOperands();
961 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
962 --NumOps; // Ignore the glue operand.
964 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
966 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
967 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
969 ++i; // Skip the ID value.
970 if (InlineAsm::isRegDefKind(Flags) ||
971 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
972 // Check for def of register or earlyclobber register.
973 for (; NumVals; --NumVals, ++i) {
974 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
975 if (TargetRegisterInfo::isPhysicalRegister(Reg))
976 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
984 if (!Node->isMachineOpcode())
986 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
987 if (!TID.ImplicitDefs)
989 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
990 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
993 return !LRegs.empty();
996 /// Return a node that can be scheduled in this cycle. Requirements:
997 /// (1) Ready: latency has been satisfied
998 /// (2) No Hazards: resources are available
999 /// (3) No Interferences: may unschedule to break register interferences.
1000 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1001 SmallVector<SUnit*, 4> Interferences;
1002 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1004 SUnit *CurSU = AvailableQueue->pop();
1006 SmallVector<unsigned, 4> LRegs;
1007 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1009 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1011 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1012 Interferences.push_back(CurSU);
1013 CurSU = AvailableQueue->pop();
1016 // Add the nodes that aren't ready back onto the available list.
1017 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1018 Interferences[i]->isPending = false;
1019 assert(Interferences[i]->isAvailable && "must still be available");
1020 AvailableQueue->push(Interferences[i]);
1025 // All candidates are delayed due to live physical reg dependencies.
1026 // Try backtracking, code duplication, or inserting cross class copies
1028 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1029 SUnit *TrySU = Interferences[i];
1030 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1032 // Try unscheduling up to the point where it's safe to schedule
1035 unsigned LiveCycle = UINT_MAX;
1036 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1037 unsigned Reg = LRegs[j];
1038 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1039 BtSU = LiveRegGens[Reg];
1040 LiveCycle = BtSU->getHeight();
1043 if (!WillCreateCycle(TrySU, BtSU)) {
1044 BacktrackBottomUp(TrySU, BtSU);
1046 // Force the current node to be scheduled before the node that
1047 // requires the physical reg dep.
1048 if (BtSU->isAvailable) {
1049 BtSU->isAvailable = false;
1050 if (!BtSU->isPending)
1051 AvailableQueue->remove(BtSU);
1053 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1054 /*Reg=*/0, /*isNormalMemory=*/false,
1055 /*isMustAlias=*/false, /*isArtificial=*/true));
1057 // If one or more successors has been unscheduled, then the current
1058 // node is no longer avaialable. Schedule a successor that's now
1059 // available instead.
1060 if (!TrySU->isAvailable) {
1061 CurSU = AvailableQueue->pop();
1065 TrySU->isPending = false;
1066 Interferences.erase(Interferences.begin()+i);
1073 // Can't backtrack. If it's too expensive to copy the value, then try
1074 // duplicate the nodes that produces these "too expensive to copy"
1075 // values to break the dependency. In case even that doesn't work,
1076 // insert cross class copies.
1077 // If it's not too expensive, i.e. cost != -1, issue copies.
1078 SUnit *TrySU = Interferences[0];
1079 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1080 assert(LRegs.size() == 1 && "Can't handle this yet!");
1081 unsigned Reg = LRegs[0];
1082 SUnit *LRDef = LiveRegDefs[Reg];
1083 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1084 const TargetRegisterClass *RC =
1085 TRI->getMinimalPhysRegClass(Reg, VT);
1086 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1088 // If cross copy register class is null, then it must be possible copy
1089 // the value directly. Do not try duplicate the def.
1092 NewDef = CopyAndMoveSuccessors(LRDef);
1096 // Issue copies, these can be expensive cross register class copies.
1097 SmallVector<SUnit*, 2> Copies;
1098 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1099 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1100 << " to SU #" << Copies.front()->NodeNum << "\n");
1101 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1102 /*Reg=*/0, /*isNormalMemory=*/false,
1103 /*isMustAlias=*/false,
1104 /*isArtificial=*/true));
1105 NewDef = Copies.back();
1108 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1109 << " to SU #" << TrySU->NodeNum << "\n");
1110 LiveRegDefs[Reg] = NewDef;
1111 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1112 /*Reg=*/0, /*isNormalMemory=*/false,
1113 /*isMustAlias=*/false,
1114 /*isArtificial=*/true));
1115 TrySU->isAvailable = false;
1119 assert(CurSU && "Unable to resolve live physical register dependencies!");
1121 // Add the nodes that aren't ready back onto the available list.
1122 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1123 Interferences[i]->isPending = false;
1124 // May no longer be available due to backtracking.
1125 if (Interferences[i]->isAvailable) {
1126 AvailableQueue->push(Interferences[i]);
1132 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1134 void ScheduleDAGRRList::ListScheduleBottomUp() {
1135 // Release any predecessors of the special Exit node.
1136 ReleasePredecessors(&ExitSU);
1138 // Add root to Available queue.
1139 if (!SUnits.empty()) {
1140 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1141 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1142 RootSU->isAvailable = true;
1143 AvailableQueue->push(RootSU);
1146 // While Available queue is not empty, grab the node with the highest
1147 // priority. If it is not ready put it back. Schedule the node.
1148 Sequence.reserve(SUnits.size());
1149 while (!AvailableQueue->empty()) {
1150 DEBUG(dbgs() << "\n*** Examining Available\n";
1151 AvailableQueue->dump(this));
1153 // Pick the best node to schedule taking all constraints into
1155 SUnit *SU = PickNodeToScheduleBottomUp();
1157 AdvancePastStalls(SU);
1159 ScheduleNodeBottomUp(SU);
1161 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1162 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1163 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1164 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1168 // Reverse the order if it is bottom up.
1169 std::reverse(Sequence.begin(), Sequence.end());
1172 VerifySchedule(isBottomUp);
1176 //===----------------------------------------------------------------------===//
1177 // Top-Down Scheduling
1178 //===----------------------------------------------------------------------===//
1180 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1181 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1182 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1183 SUnit *SuccSU = SuccEdge->getSUnit();
1186 if (SuccSU->NumPredsLeft == 0) {
1187 dbgs() << "*** Scheduling failed! ***\n";
1189 dbgs() << " has been released too many times!\n";
1190 llvm_unreachable(0);
1193 --SuccSU->NumPredsLeft;
1195 // If all the node's predecessors are scheduled, this node is ready
1196 // to be scheduled. Ignore the special ExitSU node.
1197 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1198 SuccSU->isAvailable = true;
1199 AvailableQueue->push(SuccSU);
1203 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1204 // Top down: release successors
1205 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1207 assert(!I->isAssignedRegDep() &&
1208 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1210 ReleaseSucc(SU, &*I);
1214 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1215 /// count of its successors. If a successor pending count is zero, add it to
1216 /// the Available queue.
1217 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1218 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1219 DEBUG(SU->dump(this));
1221 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1222 SU->setDepthToAtLeast(CurCycle);
1223 Sequence.push_back(SU);
1225 ReleaseSuccessors(SU);
1226 SU->isScheduled = true;
1227 AvailableQueue->ScheduledNode(SU);
1230 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1232 void ScheduleDAGRRList::ListScheduleTopDown() {
1233 AvailableQueue->setCurCycle(CurCycle);
1235 // Release any successors of the special Entry node.
1236 ReleaseSuccessors(&EntrySU);
1238 // All leaves to Available queue.
1239 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1240 // It is available if it has no predecessors.
1241 if (SUnits[i].Preds.empty()) {
1242 AvailableQueue->push(&SUnits[i]);
1243 SUnits[i].isAvailable = true;
1247 // While Available queue is not empty, grab the node with the highest
1248 // priority. If it is not ready put it back. Schedule the node.
1249 Sequence.reserve(SUnits.size());
1250 while (!AvailableQueue->empty()) {
1251 SUnit *CurSU = AvailableQueue->pop();
1254 ScheduleNodeTopDown(CurSU);
1256 AvailableQueue->setCurCycle(CurCycle);
1260 VerifySchedule(isBottomUp);
1265 //===----------------------------------------------------------------------===//
1266 // RegReductionPriorityQueue Definition
1267 //===----------------------------------------------------------------------===//
1269 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1270 // to reduce register pressure.
1273 class RegReductionPQBase;
1275 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1276 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1279 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1280 // reduction scheduler.
1281 struct bu_ls_rr_sort : public queue_sort {
1284 HasReadyFilter = false
1287 RegReductionPQBase *SPQ;
1288 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1289 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1291 bool operator()(SUnit* left, SUnit* right) const;
1294 // td_ls_rr_sort - Priority function for top down register pressure reduction
1296 struct td_ls_rr_sort : public queue_sort {
1299 HasReadyFilter = false
1302 RegReductionPQBase *SPQ;
1303 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1304 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1306 bool operator()(const SUnit* left, const SUnit* right) const;
1309 // src_ls_rr_sort - Priority function for source order scheduler.
1310 struct src_ls_rr_sort : public queue_sort {
1313 HasReadyFilter = false
1316 RegReductionPQBase *SPQ;
1317 src_ls_rr_sort(RegReductionPQBase *spq)
1319 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1322 bool operator()(SUnit* left, SUnit* right) const;
1325 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1326 struct hybrid_ls_rr_sort : public queue_sort {
1329 HasReadyFilter = false
1332 RegReductionPQBase *SPQ;
1333 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1335 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1338 bool isReady(SUnit *SU, unsigned CurCycle) const;
1340 bool operator()(SUnit* left, SUnit* right) const;
1343 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1345 struct ilp_ls_rr_sort : public queue_sort {
1348 HasReadyFilter = false
1351 RegReductionPQBase *SPQ;
1352 ilp_ls_rr_sort(RegReductionPQBase *spq)
1354 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1357 bool isReady(SUnit *SU, unsigned CurCycle) const;
1359 bool operator()(SUnit* left, SUnit* right) const;
1362 class RegReductionPQBase : public SchedulingPriorityQueue {
1364 std::vector<SUnit*> Queue;
1365 unsigned CurQueueId;
1366 bool TracksRegPressure;
1368 // SUnits - The SUnits for the current graph.
1369 std::vector<SUnit> *SUnits;
1371 MachineFunction &MF;
1372 const TargetInstrInfo *TII;
1373 const TargetRegisterInfo *TRI;
1374 const TargetLowering *TLI;
1375 ScheduleDAGRRList *scheduleDAG;
1377 // SethiUllmanNumbers - The SethiUllman number for each node.
1378 std::vector<unsigned> SethiUllmanNumbers;
1380 /// RegPressure - Tracking current reg pressure per register class.
1382 std::vector<unsigned> RegPressure;
1384 /// RegLimit - Tracking the number of allocatable registers per register
1386 std::vector<unsigned> RegLimit;
1389 RegReductionPQBase(MachineFunction &mf,
1390 bool hasReadyFilter,
1392 const TargetInstrInfo *tii,
1393 const TargetRegisterInfo *tri,
1394 const TargetLowering *tli)
1395 : SchedulingPriorityQueue(hasReadyFilter),
1396 CurQueueId(0), TracksRegPressure(tracksrp),
1397 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1398 if (TracksRegPressure) {
1399 unsigned NumRC = TRI->getNumRegClasses();
1400 RegLimit.resize(NumRC);
1401 RegPressure.resize(NumRC);
1402 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1403 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1404 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1405 E = TRI->regclass_end(); I != E; ++I)
1406 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1410 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1411 scheduleDAG = scheduleDag;
1414 ScheduleHazardRecognizer* getHazardRec() {
1415 return scheduleDAG->getHazardRec();
1418 void initNodes(std::vector<SUnit> &sunits);
1420 void addNode(const SUnit *SU);
1422 void updateNode(const SUnit *SU);
1424 void releaseState() {
1426 SethiUllmanNumbers.clear();
1427 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1430 unsigned getNodePriority(const SUnit *SU) const;
1432 unsigned getNodeOrdering(const SUnit *SU) const {
1433 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1436 bool empty() const { return Queue.empty(); }
1438 void push(SUnit *U) {
1439 assert(!U->NodeQueueId && "Node in the queue already");
1440 U->NodeQueueId = ++CurQueueId;
1444 void remove(SUnit *SU) {
1445 assert(!Queue.empty() && "Queue is empty!");
1446 assert(SU->NodeQueueId != 0 && "Not in queue!");
1447 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1449 if (I != prior(Queue.end()))
1450 std::swap(*I, Queue.back());
1452 SU->NodeQueueId = 0;
1455 bool tracksRegPressure() const { return TracksRegPressure; }
1457 void dumpRegPressure() const;
1459 bool HighRegPressure(const SUnit *SU) const;
1461 bool MayReduceRegPressure(SUnit *SU);
1463 void ScheduledNode(SUnit *SU);
1465 void UnscheduledNode(SUnit *SU);
1468 bool canClobber(const SUnit *SU, const SUnit *Op);
1469 void AddPseudoTwoAddrDeps();
1470 void PrescheduleNodesWithMultipleUses();
1471 void CalculateSethiUllmanNumbers();
1475 class RegReductionPriorityQueue : public RegReductionPQBase {
1476 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1477 std::vector<SUnit *>::iterator Best = Q.begin();
1478 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1479 E = Q.end(); I != E; ++I)
1480 if (Picker(*Best, *I))
1483 if (Best != prior(Q.end()))
1484 std::swap(*Best, Q.back());
1492 RegReductionPriorityQueue(MachineFunction &mf,
1494 const TargetInstrInfo *tii,
1495 const TargetRegisterInfo *tri,
1496 const TargetLowering *tli)
1497 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1500 bool isBottomUp() const { return SF::IsBottomUp; }
1502 bool isReady(SUnit *U) const {
1503 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1507 if (Queue.empty()) return NULL;
1509 SUnit *V = popFromQueue(Queue, Picker);
1514 void dump(ScheduleDAG *DAG) const {
1515 // Emulate pop() without clobbering NodeQueueIds.
1516 std::vector<SUnit*> DumpQueue = Queue;
1517 SF DumpPicker = Picker;
1518 while (!DumpQueue.empty()) {
1519 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1521 dbgs() << "Height " << SU->getHeight() << ": ";
1523 dbgs() << "Depth " << SU->getDepth() << ": ";
1529 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1530 BURegReductionPriorityQueue;
1532 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1533 TDRegReductionPriorityQueue;
1535 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1536 SrcRegReductionPriorityQueue;
1538 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1539 HybridBURRPriorityQueue;
1541 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1542 ILPBURRPriorityQueue;
1543 } // end anonymous namespace
1545 //===----------------------------------------------------------------------===//
1546 // Static Node Priority for Register Pressure Reduction
1547 //===----------------------------------------------------------------------===//
1549 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1550 /// Smaller number is the higher priority.
1552 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1553 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1554 if (SethiUllmanNumber != 0)
1555 return SethiUllmanNumber;
1558 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1560 if (I->isCtrl()) continue; // ignore chain preds
1561 SUnit *PredSU = I->getSUnit();
1562 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1563 if (PredSethiUllman > SethiUllmanNumber) {
1564 SethiUllmanNumber = PredSethiUllman;
1566 } else if (PredSethiUllman == SethiUllmanNumber)
1570 SethiUllmanNumber += Extra;
1572 if (SethiUllmanNumber == 0)
1573 SethiUllmanNumber = 1;
1575 return SethiUllmanNumber;
1578 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1579 /// scheduling units.
1580 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1581 SethiUllmanNumbers.assign(SUnits->size(), 0);
1583 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1584 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1587 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1589 // Add pseudo dependency edges for two-address nodes.
1590 AddPseudoTwoAddrDeps();
1591 // Reroute edges to nodes with multiple uses.
1592 if (!TracksRegPressure)
1593 PrescheduleNodesWithMultipleUses();
1594 // Calculate node priorities.
1595 CalculateSethiUllmanNumbers();
1598 void RegReductionPQBase::addNode(const SUnit *SU) {
1599 unsigned SUSize = SethiUllmanNumbers.size();
1600 if (SUnits->size() > SUSize)
1601 SethiUllmanNumbers.resize(SUSize*2, 0);
1602 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1605 void RegReductionPQBase::updateNode(const SUnit *SU) {
1606 SethiUllmanNumbers[SU->NodeNum] = 0;
1607 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1610 // Lower priority means schedule further down. For bottom-up scheduling, lower
1611 // priority SUs are scheduled before higher priority SUs.
1612 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1613 assert(SU->NodeNum < SethiUllmanNumbers.size());
1614 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1615 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1616 // CopyToReg should be close to its uses to facilitate coalescing and
1619 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1620 Opc == TargetOpcode::SUBREG_TO_REG ||
1621 Opc == TargetOpcode::INSERT_SUBREG)
1622 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1623 // close to their uses to facilitate coalescing.
1625 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1626 // If SU does not have a register use, i.e. it doesn't produce a value
1627 // that would be consumed (e.g. store), then it terminates a chain of
1628 // computation. Give it a large SethiUllman number so it will be
1629 // scheduled right before its predecessors that it doesn't lengthen
1630 // their live ranges.
1632 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1633 // If SU does not have a register def, schedule it close to its uses
1634 // because it does not lengthen any live ranges.
1636 return SethiUllmanNumbers[SU->NodeNum];
1639 //===----------------------------------------------------------------------===//
1640 // Register Pressure Tracking
1641 //===----------------------------------------------------------------------===//
1643 void RegReductionPQBase::dumpRegPressure() const {
1644 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1645 E = TRI->regclass_end(); I != E; ++I) {
1646 const TargetRegisterClass *RC = *I;
1647 unsigned Id = RC->getID();
1648 unsigned RP = RegPressure[Id];
1650 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1655 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1659 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1663 SUnit *PredSU = I->getSUnit();
1664 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1665 // to cover the number of registers defined (they are all live).
1666 if (PredSU->NumRegDefsLeft == 0) {
1669 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1670 RegDefPos.IsValid(); RegDefPos.Advance()) {
1671 EVT VT = RegDefPos.GetValue();
1672 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1673 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1674 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1681 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1682 const SDNode *N = SU->getNode();
1684 if (!N->isMachineOpcode() || !SU->NumSuccs)
1687 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1688 for (unsigned i = 0; i != NumDefs; ++i) {
1689 EVT VT = N->getValueType(i);
1690 if (!N->hasAnyUseOfValue(i))
1692 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1693 if (RegPressure[RCId] >= RegLimit[RCId])
1699 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1700 if (!TracksRegPressure)
1703 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1707 SUnit *PredSU = I->getSUnit();
1708 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1709 // to cover the number of registers defined (they are all live).
1710 if (PredSU->NumRegDefsLeft == 0) {
1713 // FIXME: The ScheduleDAG currently loses information about which of a
1714 // node's values is consumed by each dependence. Consequently, if the node
1715 // defines multiple register classes, we don't know which to pressurize
1716 // here. Instead the following loop consumes the register defs in an
1717 // arbitrary order. At least it handles the common case of clustered loads
1718 // to the same class. For precise liveness, each SDep needs to indicate the
1719 // result number. But that tightly couples the ScheduleDAG with the
1720 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1721 // value type or register class to SDep.
1723 // The most important aspect of register tracking is balancing the increase
1724 // here with the reduction further below. Note that this SU may use multiple
1725 // defs in PredSU. The can't be determined here, but we've already
1726 // compensated by reducing NumRegDefsLeft in PredSU during
1727 // ScheduleDAGSDNodes::AddSchedEdges.
1728 --PredSU->NumRegDefsLeft;
1729 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1730 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1731 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1734 EVT VT = RegDefPos.GetValue();
1735 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1736 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1741 // We should have this assert, but there may be dead SDNodes that never
1742 // materialize as SUnits, so they don't appear to generate liveness.
1743 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1744 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1745 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1746 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1747 if (SkipRegDefs > 0)
1749 EVT VT = RegDefPos.GetValue();
1750 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1751 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1752 // Register pressure tracking is imprecise. This can happen. But we try
1753 // hard not to let it happen because it likely results in poor scheduling.
1754 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1755 RegPressure[RCId] = 0;
1758 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1764 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1765 if (!TracksRegPressure)
1768 const SDNode *N = SU->getNode();
1769 if (!N->isMachineOpcode()) {
1770 if (N->getOpcode() != ISD::CopyToReg)
1773 unsigned Opc = N->getMachineOpcode();
1774 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1775 Opc == TargetOpcode::INSERT_SUBREG ||
1776 Opc == TargetOpcode::SUBREG_TO_REG ||
1777 Opc == TargetOpcode::REG_SEQUENCE ||
1778 Opc == TargetOpcode::IMPLICIT_DEF)
1782 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1786 SUnit *PredSU = I->getSUnit();
1787 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1788 // counts data deps.
1789 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1791 const SDNode *PN = PredSU->getNode();
1792 if (!PN->isMachineOpcode()) {
1793 if (PN->getOpcode() == ISD::CopyFromReg) {
1794 EVT VT = PN->getValueType(0);
1795 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1796 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1800 unsigned POpc = PN->getMachineOpcode();
1801 if (POpc == TargetOpcode::IMPLICIT_DEF)
1803 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1804 EVT VT = PN->getOperand(0).getValueType();
1805 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1806 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1808 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1809 POpc == TargetOpcode::SUBREG_TO_REG) {
1810 EVT VT = PN->getValueType(0);
1811 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1812 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1815 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1816 for (unsigned i = 0; i != NumDefs; ++i) {
1817 EVT VT = PN->getValueType(i);
1818 if (!PN->hasAnyUseOfValue(i))
1820 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1821 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1822 // Register pressure tracking is imprecise. This can happen.
1823 RegPressure[RCId] = 0;
1825 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1829 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1830 // may transfer data dependencies to CopyToReg.
1831 if (SU->NumSuccs && N->isMachineOpcode()) {
1832 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1833 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1834 EVT VT = N->getValueType(i);
1835 if (VT == MVT::Glue || VT == MVT::Other)
1837 if (!N->hasAnyUseOfValue(i))
1839 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1840 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1847 //===----------------------------------------------------------------------===//
1848 // Dynamic Node Priority for Register Pressure Reduction
1849 //===----------------------------------------------------------------------===//
1851 /// closestSucc - Returns the scheduled cycle of the successor which is
1852 /// closest to the current cycle.
1853 static unsigned closestSucc(const SUnit *SU) {
1854 unsigned MaxHeight = 0;
1855 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1857 if (I->isCtrl()) continue; // ignore chain succs
1858 unsigned Height = I->getSUnit()->getHeight();
1859 // If there are bunch of CopyToRegs stacked up, they should be considered
1860 // to be at the same position.
1861 if (I->getSUnit()->getNode() &&
1862 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1863 Height = closestSucc(I->getSUnit())+1;
1864 if (Height > MaxHeight)
1870 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1871 /// for scratch registers, i.e. number of data dependencies.
1872 static unsigned calcMaxScratches(const SUnit *SU) {
1873 unsigned Scratches = 0;
1874 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1876 if (I->isCtrl()) continue; // ignore chain preds
1882 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1883 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1884 /// it has no other use. It should be scheduled closer to the terminator.
1885 static bool hasOnlyLiveOutUses(const SUnit *SU) {
1886 bool RetVal = false;
1887 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1889 if (I->isCtrl()) continue;
1890 const SUnit *SuccSU = I->getSUnit();
1891 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1893 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1894 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1904 /// UnitsSharePred - Return true if the two scheduling units share a common
1905 /// data predecessor.
1906 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1907 SmallSet<const SUnit*, 4> Preds;
1908 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1910 if (I->isCtrl()) continue; // ignore chain preds
1911 Preds.insert(I->getSUnit());
1913 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1915 if (I->isCtrl()) continue; // ignore chain preds
1916 if (Preds.count(I->getSUnit()))
1922 // Check for either a dependence (latency) or resource (hazard) stall.
1924 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1925 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1926 if ((int)SPQ->getCurCycle() < Height) return true;
1927 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1928 != ScheduleHazardRecognizer::NoHazard)
1933 // Return -1 if left has higher priority, 1 if right has higher priority.
1934 // Return 0 if latency-based priority is equivalent.
1935 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1936 RegReductionPQBase *SPQ) {
1937 // If the two nodes share an operand and one of them has a single
1938 // use that is a live out copy, favor the one that is live out. Otherwise
1939 // it will be difficult to eliminate the copy if the instruction is a
1940 // loop induction variable update. e.g.
1947 bool SharePred = UnitsSharePred(left, right);
1948 // FIXME: Only adjust if BB is a loop back edge.
1949 // FIXME: What's the cost of a copy?
1950 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1951 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1952 int LHeight = (int)left->getHeight() - LBonus;
1953 int RHeight = (int)right->getHeight() - RBonus;
1955 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1956 BUHasStall(left, LHeight, SPQ);
1957 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
1958 BUHasStall(right, RHeight, SPQ);
1960 // If scheduling one of the node will cause a pipeline stall, delay it.
1961 // If scheduling either one of the node will cause a pipeline stall, sort
1962 // them according to their height.
1966 if (LHeight != RHeight)
1967 return LHeight > RHeight ? 1 : -1;
1971 // If either node is scheduling for latency, sort them by height/depth
1973 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
1974 right->SchedulingPref == Sched::Latency)) {
1975 if (DisableSchedCycles) {
1976 if (LHeight != RHeight)
1977 return LHeight > RHeight ? 1 : -1;
1980 // If neither instruction stalls (!LStall && !RStall) then
1981 // it's height is already covered so only its depth matters. We also reach
1982 // this if both stall but have the same height.
1983 unsigned LDepth = left->getDepth();
1984 unsigned RDepth = right->getDepth();
1985 if (LDepth != RDepth) {
1986 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
1987 << ") depth " << LDepth << " vs SU (" << right->NodeNum
1988 << ") depth " << RDepth << "\n");
1989 return LDepth < RDepth ? 1 : -1;
1992 if (left->Latency != right->Latency)
1993 return left->Latency > right->Latency ? 1 : -1;
1998 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
1999 unsigned LPriority = SPQ->getNodePriority(left);
2000 unsigned RPriority = SPQ->getNodePriority(right);
2001 if (LPriority != RPriority)
2002 return LPriority > RPriority;
2004 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2009 // and the following instructions are both ready.
2013 // Then schedule t2 = op first.
2020 // This creates more short live intervals.
2021 unsigned LDist = closestSucc(left);
2022 unsigned RDist = closestSucc(right);
2024 return LDist < RDist;
2026 // How many registers becomes live when the node is scheduled.
2027 unsigned LScratch = calcMaxScratches(left);
2028 unsigned RScratch = calcMaxScratches(right);
2029 if (LScratch != RScratch)
2030 return LScratch > RScratch;
2032 if (!DisableSchedCycles) {
2033 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2038 if (left->getHeight() != right->getHeight())
2039 return left->getHeight() > right->getHeight();
2041 if (left->getDepth() != right->getDepth())
2042 return left->getDepth() < right->getDepth();
2045 assert(left->NodeQueueId && right->NodeQueueId &&
2046 "NodeQueueId cannot be zero");
2047 return (left->NodeQueueId > right->NodeQueueId);
2051 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2052 return BURRSort(left, right, SPQ);
2055 // Source order, otherwise bottom up.
2056 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2057 unsigned LOrder = SPQ->getNodeOrdering(left);
2058 unsigned ROrder = SPQ->getNodeOrdering(right);
2060 // Prefer an ordering where the lower the non-zero order number, the higher
2062 if ((LOrder || ROrder) && LOrder != ROrder)
2063 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2065 return BURRSort(left, right, SPQ);
2068 // If the time between now and when the instruction will be ready can cover
2069 // the spill code, then avoid adding it to the ready queue. This gives long
2070 // stalls highest priority and allows hoisting across calls. It should also
2071 // speed up processing the available queue.
2072 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2073 static const unsigned ReadyDelay = 3;
2075 if (SPQ->MayReduceRegPressure(SU)) return true;
2077 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2079 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2080 != ScheduleHazardRecognizer::NoHazard)
2086 // Return true if right should be scheduled with higher priority than left.
2087 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2088 if (left->isCall || right->isCall)
2089 // No way to compute latency of calls.
2090 return BURRSort(left, right, SPQ);
2092 bool LHigh = SPQ->HighRegPressure(left);
2093 bool RHigh = SPQ->HighRegPressure(right);
2094 // Avoid causing spills. If register pressure is high, schedule for
2095 // register pressure reduction.
2096 if (LHigh && !RHigh) {
2097 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2098 << right->NodeNum << ")\n");
2101 else if (!LHigh && RHigh) {
2102 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2103 << left->NodeNum << ")\n");
2106 else if (!LHigh && !RHigh) {
2107 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2111 return BURRSort(left, right, SPQ);
2114 // Schedule as many instructions in each cycle as possible. So don't make an
2115 // instruction available unless it is ready in the current cycle.
2116 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2117 if (SU->getHeight() > CurCycle) return false;
2119 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2120 != ScheduleHazardRecognizer::NoHazard)
2126 bool ilp_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)
2137 else if (!LHigh && RHigh)
2139 else if (!LHigh && !RHigh) {
2140 // Low register pressure situation, schedule to maximize instruction level
2142 if (left->NumPreds > right->NumPreds)
2144 else if (left->NumPreds < right->NumPreds)
2148 return BURRSort(left, right, SPQ);
2151 //===----------------------------------------------------------------------===//
2152 // Preschedule for Register Pressure
2153 //===----------------------------------------------------------------------===//
2155 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2156 if (SU->isTwoAddress) {
2157 unsigned Opc = SU->getNode()->getMachineOpcode();
2158 const TargetInstrDesc &TID = TII->get(Opc);
2159 unsigned NumRes = TID.getNumDefs();
2160 unsigned NumOps = TID.getNumOperands() - NumRes;
2161 for (unsigned i = 0; i != NumOps; ++i) {
2162 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2163 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2164 if (DU->getNodeId() != -1 &&
2165 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2173 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2174 /// physical register defs.
2175 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2176 const TargetInstrInfo *TII,
2177 const TargetRegisterInfo *TRI) {
2178 SDNode *N = SuccSU->getNode();
2179 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2180 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2181 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2182 for (const SDNode *SUNode = SU->getNode(); SUNode;
2183 SUNode = SUNode->getGluedNode()) {
2184 if (!SUNode->isMachineOpcode())
2186 const unsigned *SUImpDefs =
2187 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2190 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2191 EVT VT = N->getValueType(i);
2192 if (VT == MVT::Glue || VT == MVT::Other)
2194 if (!N->hasAnyUseOfValue(i))
2196 unsigned Reg = ImpDefs[i - NumDefs];
2197 for (;*SUImpDefs; ++SUImpDefs) {
2198 unsigned SUReg = *SUImpDefs;
2199 if (TRI->regsOverlap(Reg, SUReg))
2207 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2208 /// are not handled well by the general register pressure reduction
2209 /// heuristics. When presented with code like this:
2218 /// the heuristics tend to push the store up, but since the
2219 /// operand of the store has another use (U), this would increase
2220 /// the length of that other use (the U->N edge).
2222 /// This function transforms code like the above to route U's
2223 /// dependence through the store when possible, like this:
2234 /// This results in the store being scheduled immediately
2235 /// after N, which shortens the U->N live range, reducing
2236 /// register pressure.
2238 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2239 // Visit all the nodes in topological order, working top-down.
2240 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2241 SUnit *SU = &(*SUnits)[i];
2242 // For now, only look at nodes with no data successors, such as stores.
2243 // These are especially important, due to the heuristics in
2244 // getNodePriority for nodes with no data successors.
2245 if (SU->NumSuccs != 0)
2247 // For now, only look at nodes with exactly one data predecessor.
2248 if (SU->NumPreds != 1)
2250 // Avoid prescheduling copies to virtual registers, which don't behave
2251 // like other nodes from the perspective of scheduling heuristics.
2252 if (SDNode *N = SU->getNode())
2253 if (N->getOpcode() == ISD::CopyToReg &&
2254 TargetRegisterInfo::isVirtualRegister
2255 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2258 // Locate the single data predecessor.
2260 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2261 EE = SU->Preds.end(); II != EE; ++II)
2262 if (!II->isCtrl()) {
2263 PredSU = II->getSUnit();
2268 // Don't rewrite edges that carry physregs, because that requires additional
2269 // support infrastructure.
2270 if (PredSU->hasPhysRegDefs)
2272 // Short-circuit the case where SU is PredSU's only data successor.
2273 if (PredSU->NumSuccs == 1)
2275 // Avoid prescheduling to copies from virtual registers, which don't behave
2276 // like other nodes from the perspective of scheduling heuristics.
2277 if (SDNode *N = SU->getNode())
2278 if (N->getOpcode() == ISD::CopyFromReg &&
2279 TargetRegisterInfo::isVirtualRegister
2280 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2283 // Perform checks on the successors of PredSU.
2284 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2285 EE = PredSU->Succs.end(); II != EE; ++II) {
2286 SUnit *PredSuccSU = II->getSUnit();
2287 if (PredSuccSU == SU) continue;
2288 // If PredSU has another successor with no data successors, for
2289 // now don't attempt to choose either over the other.
2290 if (PredSuccSU->NumSuccs == 0)
2291 goto outer_loop_continue;
2292 // Don't break physical register dependencies.
2293 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2294 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2295 goto outer_loop_continue;
2296 // Don't introduce graph cycles.
2297 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2298 goto outer_loop_continue;
2301 // Ok, the transformation is safe and the heuristics suggest it is
2302 // profitable. Update the graph.
2303 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2304 << " next to PredSU #" << PredSU->NodeNum
2305 << " to guide scheduling in the presence of multiple uses\n");
2306 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2307 SDep Edge = PredSU->Succs[i];
2308 assert(!Edge.isAssignedRegDep());
2309 SUnit *SuccSU = Edge.getSUnit();
2311 Edge.setSUnit(PredSU);
2312 scheduleDAG->RemovePred(SuccSU, Edge);
2313 scheduleDAG->AddPred(SU, Edge);
2315 scheduleDAG->AddPred(SuccSU, Edge);
2319 outer_loop_continue:;
2323 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2324 /// it as a def&use operand. Add a pseudo control edge from it to the other
2325 /// node (if it won't create a cycle) so the two-address one will be scheduled
2326 /// first (lower in the schedule). If both nodes are two-address, favor the
2327 /// one that has a CopyToReg use (more likely to be a loop induction update).
2328 /// If both are two-address, but one is commutable while the other is not
2329 /// commutable, favor the one that's not commutable.
2330 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2331 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2332 SUnit *SU = &(*SUnits)[i];
2333 if (!SU->isTwoAddress)
2336 SDNode *Node = SU->getNode();
2337 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2340 bool isLiveOut = hasOnlyLiveOutUses(SU);
2341 unsigned Opc = Node->getMachineOpcode();
2342 const TargetInstrDesc &TID = TII->get(Opc);
2343 unsigned NumRes = TID.getNumDefs();
2344 unsigned NumOps = TID.getNumOperands() - NumRes;
2345 for (unsigned j = 0; j != NumOps; ++j) {
2346 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2348 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2349 if (DU->getNodeId() == -1)
2351 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2352 if (!DUSU) continue;
2353 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2354 E = DUSU->Succs.end(); I != E; ++I) {
2355 if (I->isCtrl()) continue;
2356 SUnit *SuccSU = I->getSUnit();
2359 // Be conservative. Ignore if nodes aren't at roughly the same
2360 // depth and height.
2361 if (SuccSU->getHeight() < SU->getHeight() &&
2362 (SU->getHeight() - SuccSU->getHeight()) > 1)
2364 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2365 // constrains whatever is using the copy, instead of the copy
2366 // itself. In the case that the copy is coalesced, this
2367 // preserves the intent of the pseudo two-address heurietics.
2368 while (SuccSU->Succs.size() == 1 &&
2369 SuccSU->getNode()->isMachineOpcode() &&
2370 SuccSU->getNode()->getMachineOpcode() ==
2371 TargetOpcode::COPY_TO_REGCLASS)
2372 SuccSU = SuccSU->Succs.front().getSUnit();
2373 // Don't constrain non-instruction nodes.
2374 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2376 // Don't constrain nodes with physical register defs if the
2377 // predecessor can clobber them.
2378 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2379 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2382 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2383 // these may be coalesced away. We want them close to their uses.
2384 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2385 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2386 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2387 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2389 if ((!canClobber(SuccSU, DUSU) ||
2390 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2391 (!SU->isCommutable && SuccSU->isCommutable)) &&
2392 !scheduleDAG->IsReachable(SuccSU, SU)) {
2393 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2394 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2395 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2396 /*Reg=*/0, /*isNormalMemory=*/false,
2397 /*isMustAlias=*/false,
2398 /*isArtificial=*/true));
2405 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2406 /// predecessors of the successors of the SUnit SU. Stop when the provided
2407 /// limit is exceeded.
2408 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2411 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2413 const SUnit *SuccSU = I->getSUnit();
2414 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2415 EE = SuccSU->Preds.end(); II != EE; ++II) {
2416 SUnit *PredSU = II->getSUnit();
2417 if (!PredSU->isScheduled)
2427 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2428 unsigned LPriority = SPQ->getNodePriority(left);
2429 unsigned RPriority = SPQ->getNodePriority(right);
2430 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2431 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2432 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2433 bool RIsFloater = RIsTarget && right->NumPreds == 0;
2434 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2435 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2437 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2439 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2446 if (left->NumSuccs == 1)
2448 if (right->NumSuccs == 1)
2451 if (LPriority+LBonus != RPriority+RBonus)
2452 return LPriority+LBonus < RPriority+RBonus;
2454 if (left->getDepth() != right->getDepth())
2455 return left->getDepth() < right->getDepth();
2457 if (left->NumSuccsLeft != right->NumSuccsLeft)
2458 return left->NumSuccsLeft > right->NumSuccsLeft;
2460 assert(left->NodeQueueId && right->NodeQueueId &&
2461 "NodeQueueId cannot be zero");
2462 return (left->NodeQueueId > right->NodeQueueId);
2465 //===----------------------------------------------------------------------===//
2466 // Public Constructor Functions
2467 //===----------------------------------------------------------------------===//
2469 llvm::ScheduleDAGSDNodes *
2470 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2471 CodeGenOpt::Level OptLevel) {
2472 const TargetMachine &TM = IS->TM;
2473 const TargetInstrInfo *TII = TM.getInstrInfo();
2474 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2476 BURegReductionPriorityQueue *PQ =
2477 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2478 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2479 PQ->setScheduleDAG(SD);
2483 llvm::ScheduleDAGSDNodes *
2484 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2485 CodeGenOpt::Level OptLevel) {
2486 const TargetMachine &TM = IS->TM;
2487 const TargetInstrInfo *TII = TM.getInstrInfo();
2488 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2490 TDRegReductionPriorityQueue *PQ =
2491 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2492 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2493 PQ->setScheduleDAG(SD);
2497 llvm::ScheduleDAGSDNodes *
2498 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2499 CodeGenOpt::Level OptLevel) {
2500 const TargetMachine &TM = IS->TM;
2501 const TargetInstrInfo *TII = TM.getInstrInfo();
2502 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2504 SrcRegReductionPriorityQueue *PQ =
2505 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2506 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2507 PQ->setScheduleDAG(SD);
2511 llvm::ScheduleDAGSDNodes *
2512 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2513 CodeGenOpt::Level OptLevel) {
2514 const TargetMachine &TM = IS->TM;
2515 const TargetInstrInfo *TII = TM.getInstrInfo();
2516 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2517 const TargetLowering *TLI = &IS->getTargetLowering();
2519 HybridBURRPriorityQueue *PQ =
2520 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2522 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2523 PQ->setScheduleDAG(SD);
2527 llvm::ScheduleDAGSDNodes *
2528 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2529 CodeGenOpt::Level OptLevel) {
2530 const TargetMachine &TM = IS->TM;
2531 const TargetInstrInfo *TII = TM.getInstrInfo();
2532 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2533 const TargetLowering *TLI = &IS->getTargetLowering();
2535 ILPBURRPriorityQueue *PQ =
2536 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2537 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2538 PQ->setScheduleDAG(SD);