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 #include "llvm/CodeGen/SchedulerRegistry.h"
19 #include "ScheduleDAGSDNodes.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 #define DEBUG_TYPE "pre-RA-sched"
40 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
41 STATISTIC(NumUnfolds, "Number of nodes unfolded");
42 STATISTIC(NumDups, "Number of duplicated nodes");
43 STATISTIC(NumPRCopies, "Number of physical register copies");
45 static RegisterScheduler
46 burrListDAGScheduler("list-burr",
47 "Bottom-up register reduction list scheduling",
48 createBURRListDAGScheduler);
49 static RegisterScheduler
50 sourceListDAGScheduler("source",
51 "Similar to list-burr but schedules in source "
52 "order when possible",
53 createSourceListDAGScheduler);
55 static RegisterScheduler
56 hybridListDAGScheduler("list-hybrid",
57 "Bottom-up register pressure aware list scheduling "
58 "which tries to balance latency and register pressure",
59 createHybridListDAGScheduler);
61 static RegisterScheduler
62 ILPListDAGScheduler("list-ilp",
63 "Bottom-up register pressure aware list scheduling "
64 "which tries to balance ILP and register pressure",
65 createILPListDAGScheduler);
67 static cl::opt<bool> DisableSchedCycles(
68 "disable-sched-cycles", cl::Hidden, cl::init(false),
69 cl::desc("Disable cycle-level precision during preRA scheduling"));
71 // Temporary sched=list-ilp flags until the heuristics are robust.
72 // Some options are also available under sched=list-hybrid.
73 static cl::opt<bool> DisableSchedRegPressure(
74 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
75 cl::desc("Disable regpressure priority in sched=list-ilp"));
76 static cl::opt<bool> DisableSchedLiveUses(
77 "disable-sched-live-uses", cl::Hidden, cl::init(true),
78 cl::desc("Disable live use priority in sched=list-ilp"));
79 static cl::opt<bool> DisableSchedVRegCycle(
80 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
81 cl::desc("Disable virtual register cycle interference checks"));
82 static cl::opt<bool> DisableSchedPhysRegJoin(
83 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
84 cl::desc("Disable physreg def-use affinity"));
85 static cl::opt<bool> DisableSchedStalls(
86 "disable-sched-stalls", cl::Hidden, cl::init(true),
87 cl::desc("Disable no-stall priority in sched=list-ilp"));
88 static cl::opt<bool> DisableSchedCriticalPath(
89 "disable-sched-critical-path", cl::Hidden, cl::init(false),
90 cl::desc("Disable critical path priority in sched=list-ilp"));
91 static cl::opt<bool> DisableSchedHeight(
92 "disable-sched-height", cl::Hidden, cl::init(false),
93 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
94 static cl::opt<bool> Disable2AddrHack(
95 "disable-2addr-hack", cl::Hidden, cl::init(true),
96 cl::desc("Disable scheduler's two-address hack"));
98 static cl::opt<int> MaxReorderWindow(
99 "max-sched-reorder", cl::Hidden, cl::init(6),
100 cl::desc("Number of instructions to allow ahead of the critical path "
101 "in sched=list-ilp"));
103 static cl::opt<unsigned> AvgIPC(
104 "sched-avg-ipc", cl::Hidden, cl::init(1),
105 cl::desc("Average inst/cycle whan no target itinerary exists."));
108 //===----------------------------------------------------------------------===//
109 /// ScheduleDAGRRList - The actual register reduction list scheduler
110 /// implementation. This supports both top-down and bottom-up scheduling.
112 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
114 /// NeedLatency - True if the scheduler will make use of latency information.
118 /// AvailableQueue - The priority queue to use for the available SUnits.
119 SchedulingPriorityQueue *AvailableQueue;
121 /// PendingQueue - This contains all of the instructions whose operands have
122 /// been issued, but their results are not ready yet (due to the latency of
123 /// the operation). Once the operands becomes available, the instruction is
124 /// added to the AvailableQueue.
125 std::vector<SUnit*> PendingQueue;
127 /// HazardRec - The hazard recognizer to use.
128 ScheduleHazardRecognizer *HazardRec;
130 /// CurCycle - The current scheduler state corresponds to this cycle.
133 /// MinAvailableCycle - Cycle of the soonest available instruction.
134 unsigned MinAvailableCycle;
136 /// IssueCount - Count instructions issued in this cycle
137 /// Currently valid only for bottom-up scheduling.
140 /// LiveRegDefs - A set of physical registers and their definition
141 /// that are "live". These nodes must be scheduled before any other nodes that
142 /// modifies the registers can be scheduled.
143 unsigned NumLiveRegs;
144 std::unique_ptr<SUnit*[]> LiveRegDefs;
145 std::unique_ptr<SUnit*[]> LiveRegGens;
147 // Collect interferences between physical register use/defs.
148 // Each interference is an SUnit and set of physical registers.
149 SmallVector<SUnit*, 4> Interferences;
150 typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT;
153 /// Topo - A topological ordering for SUnits which permits fast IsReachable
154 /// and similar queries.
155 ScheduleDAGTopologicalSort Topo;
157 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
159 DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
163 SchedulingPriorityQueue *availqueue,
164 CodeGenOpt::Level OptLevel)
165 : ScheduleDAGSDNodes(mf),
166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
167 Topo(SUnits, nullptr) {
169 const TargetSubtargetInfo &STI = mf.getSubtarget();
170 if (DisableSchedCycles || !NeedLatency)
171 HazardRec = new ScheduleHazardRecognizer();
173 HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
176 ~ScheduleDAGRRList() override {
178 delete AvailableQueue;
181 void Schedule() override;
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 ReleasePending();
221 void AdvanceToCycle(unsigned NextCycle);
222 void AdvancePastStalls(SUnit *SU);
223 void EmitNode(SUnit *SU);
224 void ScheduleNodeBottomUp(SUnit*);
225 void CapturePred(SDep *PredEdge);
226 void UnscheduleNodeBottomUp(SUnit*);
227 void RestoreHazardCheckerBottomUp();
228 void BacktrackBottomUp(SUnit*, SUnit*);
229 SUnit *CopyAndMoveSuccessors(SUnit*);
230 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
231 const TargetRegisterClass*,
232 const TargetRegisterClass*,
233 SmallVectorImpl<SUnit*>&);
234 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
236 void releaseInterferences(unsigned Reg = 0);
238 SUnit *PickNodeToScheduleBottomUp();
239 void ListScheduleBottomUp();
241 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
242 /// Updates the topological ordering if required.
243 SUnit *CreateNewSUnit(SDNode *N) {
244 unsigned NumSUnits = SUnits.size();
245 SUnit *NewNode = newSUnit(N);
246 // Update the topological ordering.
247 if (NewNode->NodeNum >= NumSUnits)
248 Topo.InitDAGTopologicalSorting();
252 /// CreateClone - Creates a new SUnit from an existing one.
253 /// Updates the topological ordering if required.
254 SUnit *CreateClone(SUnit *N) {
255 unsigned NumSUnits = SUnits.size();
256 SUnit *NewNode = Clone(N);
257 // Update the topological ordering.
258 if (NewNode->NodeNum >= NumSUnits)
259 Topo.InitDAGTopologicalSorting();
263 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
264 /// need actual latency information but the hybrid scheduler does.
265 bool forceUnitLatencies() const override {
269 } // end anonymous namespace
271 /// GetCostForDef - Looks up the register class and cost for a given definition.
272 /// Typically this just means looking up the representative register class,
273 /// but for untyped values (MVT::Untyped) it means inspecting the node's
274 /// opcode to determine what register class is being generated.
275 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
276 const TargetLowering *TLI,
277 const TargetInstrInfo *TII,
278 const TargetRegisterInfo *TRI,
279 unsigned &RegClass, unsigned &Cost,
280 const MachineFunction &MF) {
281 MVT VT = RegDefPos.GetValue();
283 // Special handling for untyped values. These values can only come from
284 // the expansion of custom DAG-to-DAG patterns.
285 if (VT == MVT::Untyped) {
286 const SDNode *Node = RegDefPos.GetNode();
288 // Special handling for CopyFromReg of untyped values.
289 if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
290 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
291 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
292 RegClass = RC->getID();
297 unsigned Opcode = Node->getMachineOpcode();
298 if (Opcode == TargetOpcode::REG_SEQUENCE) {
299 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
300 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
301 RegClass = RC->getID();
306 unsigned Idx = RegDefPos.GetIdx();
307 const MCInstrDesc Desc = TII->get(Opcode);
308 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
309 RegClass = RC->getID();
310 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
311 // better way to determine it.
314 RegClass = TLI->getRepRegClassFor(VT)->getID();
315 Cost = TLI->getRepRegClassCostFor(VT);
319 /// Schedule - Schedule the DAG using list scheduling.
320 void ScheduleDAGRRList::Schedule() {
322 << "********** List Scheduling BB#" << BB->getNumber()
323 << " '" << BB->getName() << "' **********\n");
327 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
329 // Allocate slots for each physical register, plus one for a special register
330 // to track the virtual resource of a calling sequence.
331 LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
332 LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
333 CallSeqEndForStart.clear();
334 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
336 // Build the scheduling graph.
337 BuildSchedGraph(nullptr);
339 DEBUG(for (SUnit &SU : SUnits)
341 Topo.InitDAGTopologicalSorting();
343 AvailableQueue->initNodes(SUnits);
347 // Execute the actual scheduling loop.
348 ListScheduleBottomUp();
350 AvailableQueue->releaseState();
353 dbgs() << "*** Final schedule ***\n";
359 //===----------------------------------------------------------------------===//
360 // Bottom-Up Scheduling
361 //===----------------------------------------------------------------------===//
363 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
364 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
365 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
366 SUnit *PredSU = PredEdge->getSUnit();
369 if (PredSU->NumSuccsLeft == 0) {
370 dbgs() << "*** Scheduling failed! ***\n";
372 dbgs() << " has been released too many times!\n";
373 llvm_unreachable(nullptr);
376 --PredSU->NumSuccsLeft;
378 if (!forceUnitLatencies()) {
379 // Updating predecessor's height. This is now the cycle when the
380 // predecessor can be scheduled without causing a pipeline stall.
381 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
384 // If all the node's successors are scheduled, this node is ready
385 // to be scheduled. Ignore the special EntrySU node.
386 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
387 PredSU->isAvailable = true;
389 unsigned Height = PredSU->getHeight();
390 if (Height < MinAvailableCycle)
391 MinAvailableCycle = Height;
393 if (isReady(PredSU)) {
394 AvailableQueue->push(PredSU);
396 // CapturePred and others may have left the node in the pending queue, avoid
398 else if (!PredSU->isPending) {
399 PredSU->isPending = true;
400 PendingQueue.push_back(PredSU);
405 /// IsChainDependent - Test if Outer is reachable from Inner through
406 /// chain dependencies.
407 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
409 const TargetInstrInfo *TII) {
414 // For a TokenFactor, examine each operand. There may be multiple ways
415 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
416 // most nesting in order to ensure that we find the corresponding match.
417 if (N->getOpcode() == ISD::TokenFactor) {
418 for (const SDValue &Op : N->op_values())
419 if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
423 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
424 if (N->isMachineOpcode()) {
425 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
427 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
433 // Otherwise, find the chain and continue climbing.
434 for (const SDValue &Op : N->op_values())
435 if (Op.getValueType() == MVT::Other) {
437 goto found_chain_operand;
440 found_chain_operand:;
441 if (N->getOpcode() == ISD::EntryToken)
446 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
447 /// the corresponding (lowered) CALLSEQ_BEGIN node.
449 /// NestLevel and MaxNested are used in recursion to indcate the current level
450 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
451 /// level seen so far.
453 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
454 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
456 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
457 const TargetInstrInfo *TII) {
459 // For a TokenFactor, examine each operand. There may be multiple ways
460 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
461 // most nesting in order to ensure that we find the corresponding match.
462 if (N->getOpcode() == ISD::TokenFactor) {
463 SDNode *Best = nullptr;
464 unsigned BestMaxNest = MaxNest;
465 for (const SDValue &Op : N->op_values()) {
466 unsigned MyNestLevel = NestLevel;
467 unsigned MyMaxNest = MaxNest;
468 if (SDNode *New = FindCallSeqStart(Op.getNode(),
469 MyNestLevel, MyMaxNest, TII))
470 if (!Best || (MyMaxNest > BestMaxNest)) {
472 BestMaxNest = MyMaxNest;
476 MaxNest = BestMaxNest;
479 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
480 if (N->isMachineOpcode()) {
481 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
483 MaxNest = std::max(MaxNest, NestLevel);
484 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
485 assert(NestLevel != 0);
491 // Otherwise, find the chain and continue climbing.
492 for (const SDValue &Op : N->op_values())
493 if (Op.getValueType() == MVT::Other) {
495 goto found_chain_operand;
498 found_chain_operand:;
499 if (N->getOpcode() == ISD::EntryToken)
504 /// Call ReleasePred for each predecessor, then update register live def/gen.
505 /// Always update LiveRegDefs for a register dependence even if the current SU
506 /// also defines the register. This effectively create one large live range
507 /// across a sequence of two-address node. This is important because the
508 /// entire chain must be scheduled together. Example:
511 /// flags = (2) addc flags
512 /// flags = (1) addc flags
516 /// LiveRegDefs[flags] = 3
517 /// LiveRegGens[flags] = 1
519 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
520 /// interference on flags.
521 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
522 // Bottom up: release predecessors
523 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
525 ReleasePred(SU, &*I);
526 if (I->isAssignedRegDep()) {
527 // This is a physical register dependency and it's impossible or
528 // expensive to copy the register. Make sure nothing that can
529 // clobber the register is scheduled between the predecessor and
531 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
532 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
533 "interference on register dependence");
534 LiveRegDefs[I->getReg()] = I->getSUnit();
535 if (!LiveRegGens[I->getReg()]) {
537 LiveRegGens[I->getReg()] = SU;
542 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
543 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
544 // these nodes, to prevent other calls from being interscheduled with them.
545 unsigned CallResource = TRI->getNumRegs();
546 if (!LiveRegDefs[CallResource])
547 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
548 if (Node->isMachineOpcode() &&
549 Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
550 unsigned NestLevel = 0;
551 unsigned MaxNest = 0;
552 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
554 SUnit *Def = &SUnits[N->getNodeId()];
555 CallSeqEndForStart[Def] = SU;
558 LiveRegDefs[CallResource] = Def;
559 LiveRegGens[CallResource] = SU;
564 /// Check to see if any of the pending instructions are ready to issue. If
565 /// so, add them to the available queue.
566 void ScheduleDAGRRList::ReleasePending() {
567 if (DisableSchedCycles) {
568 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
572 // If the available queue is empty, it is safe to reset MinAvailableCycle.
573 if (AvailableQueue->empty())
574 MinAvailableCycle = UINT_MAX;
576 // Check to see if any of the pending instructions are ready to issue. If
577 // so, add them to the available queue.
578 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
579 unsigned ReadyCycle = PendingQueue[i]->getHeight();
580 if (ReadyCycle < MinAvailableCycle)
581 MinAvailableCycle = ReadyCycle;
583 if (PendingQueue[i]->isAvailable) {
584 if (!isReady(PendingQueue[i]))
586 AvailableQueue->push(PendingQueue[i]);
588 PendingQueue[i]->isPending = false;
589 PendingQueue[i] = PendingQueue.back();
590 PendingQueue.pop_back();
595 /// Move the scheduler state forward by the specified number of Cycles.
596 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
597 if (NextCycle <= CurCycle)
601 AvailableQueue->setCurCycle(NextCycle);
602 if (!HazardRec->isEnabled()) {
603 // Bypass lots of virtual calls in case of long latency.
604 CurCycle = NextCycle;
607 for (; CurCycle != NextCycle; ++CurCycle) {
608 HazardRec->RecedeCycle();
611 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
612 // available Q to release pending nodes at least once before popping.
616 /// Move the scheduler state forward until the specified node's dependents are
617 /// ready and can be scheduled with no resource conflicts.
618 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
619 if (DisableSchedCycles)
622 // FIXME: Nodes such as CopyFromReg probably should not advance the current
623 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
624 // has predecessors the cycle will be advanced when they are scheduled.
625 // But given the crude nature of modeling latency though such nodes, we
626 // currently need to treat these nodes like real instructions.
627 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
629 unsigned ReadyCycle = SU->getHeight();
631 // Bump CurCycle to account for latency. We assume the latency of other
632 // available instructions may be hidden by the stall (not a full pipe stall).
633 // This updates the hazard recognizer's cycle before reserving resources for
635 AdvanceToCycle(ReadyCycle);
637 // Calls are scheduled in their preceding cycle, so don't conflict with
638 // hazards from instructions after the call. EmitNode will reset the
639 // scoreboard state before emitting the call.
643 // FIXME: For resource conflicts in very long non-pipelined stages, we
644 // should probably skip ahead here to avoid useless scoreboard checks.
647 ScheduleHazardRecognizer::HazardType HT =
648 HazardRec->getHazardType(SU, -Stalls);
650 if (HT == ScheduleHazardRecognizer::NoHazard)
655 AdvanceToCycle(CurCycle + Stalls);
658 /// Record this SUnit in the HazardRecognizer.
659 /// Does not update CurCycle.
660 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
661 if (!HazardRec->isEnabled())
664 // Check for phys reg copy.
668 switch (SU->getNode()->getOpcode()) {
670 assert(SU->getNode()->isMachineOpcode() &&
671 "This target-independent node should not be scheduled.");
673 case ISD::MERGE_VALUES:
674 case ISD::TokenFactor:
675 case ISD::LIFETIME_START:
676 case ISD::LIFETIME_END:
678 case ISD::CopyFromReg:
680 // Noops don't affect the scoreboard state. Copies are likely to be
684 // For inline asm, clear the pipeline state.
689 // Calls are scheduled with their preceding instructions. For bottom-up
690 // scheduling, clear the pipeline state before emitting.
694 HazardRec->EmitInstruction(SU);
697 static void resetVRegCycle(SUnit *SU);
699 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
700 /// count of its predecessors. If a predecessor pending count is zero, add it to
701 /// the Available queue.
702 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
703 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
704 DEBUG(SU->dump(this));
707 if (CurCycle < SU->getHeight())
708 DEBUG(dbgs() << " Height [" << SU->getHeight()
709 << "] pipeline stall!\n");
712 // FIXME: Do not modify node height. It may interfere with
713 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
714 // node its ready cycle can aid heuristics, and after scheduling it can
715 // indicate the scheduled cycle.
716 SU->setHeightToAtLeast(CurCycle);
718 // Reserve resources for the scheduled instruction.
721 Sequence.push_back(SU);
723 AvailableQueue->scheduledNode(SU);
725 // If HazardRec is disabled, and each inst counts as one cycle, then
726 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
727 // PendingQueue for schedulers that implement HasReadyFilter.
728 if (!HazardRec->isEnabled() && AvgIPC < 2)
729 AdvanceToCycle(CurCycle + 1);
731 // Update liveness of predecessors before successors to avoid treating a
732 // two-address node as a live range def.
733 ReleasePredecessors(SU);
735 // Release all the implicit physical register defs that are live.
736 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
738 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
739 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
740 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
742 LiveRegDefs[I->getReg()] = nullptr;
743 LiveRegGens[I->getReg()] = nullptr;
744 releaseInterferences(I->getReg());
747 // Release the special call resource dependence, if this is the beginning
749 unsigned CallResource = TRI->getNumRegs();
750 if (LiveRegDefs[CallResource] == SU)
751 for (const SDNode *SUNode = SU->getNode(); SUNode;
752 SUNode = SUNode->getGluedNode()) {
753 if (SUNode->isMachineOpcode() &&
754 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
755 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
757 LiveRegDefs[CallResource] = nullptr;
758 LiveRegGens[CallResource] = nullptr;
759 releaseInterferences(CallResource);
765 SU->isScheduled = true;
767 // Conditions under which the scheduler should eagerly advance the cycle:
768 // (1) No available instructions
769 // (2) All pipelines full, so available instructions must have hazards.
771 // If HazardRec is disabled, the cycle was pre-advanced before calling
772 // ReleasePredecessors. In that case, IssueCount should remain 0.
774 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
775 if (HazardRec->isEnabled() || AvgIPC > 1) {
776 if (SU->getNode() && SU->getNode()->isMachineOpcode())
778 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
779 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
780 AdvanceToCycle(CurCycle + 1);
784 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
785 /// unscheduled, incrcease the succ left count of its predecessors. Remove
786 /// them from AvailableQueue if necessary.
787 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
788 SUnit *PredSU = PredEdge->getSUnit();
789 if (PredSU->isAvailable) {
790 PredSU->isAvailable = false;
791 if (!PredSU->isPending)
792 AvailableQueue->remove(PredSU);
795 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
796 ++PredSU->NumSuccsLeft;
799 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
800 /// its predecessor states to reflect the change.
801 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
802 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
803 DEBUG(SU->dump(this));
805 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
808 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
809 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
810 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
811 "Physical register dependency violated?");
813 LiveRegDefs[I->getReg()] = nullptr;
814 LiveRegGens[I->getReg()] = nullptr;
815 releaseInterferences(I->getReg());
819 // Reclaim the special call resource dependence, if this is the beginning
821 unsigned CallResource = TRI->getNumRegs();
822 for (const SDNode *SUNode = SU->getNode(); SUNode;
823 SUNode = SUNode->getGluedNode()) {
824 if (SUNode->isMachineOpcode() &&
825 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
827 LiveRegDefs[CallResource] = SU;
828 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
832 // Release the special call resource dependence, if this is the end
834 if (LiveRegGens[CallResource] == SU)
835 for (const SDNode *SUNode = SU->getNode(); SUNode;
836 SUNode = SUNode->getGluedNode()) {
837 if (SUNode->isMachineOpcode() &&
838 SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
839 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
841 LiveRegDefs[CallResource] = nullptr;
842 LiveRegGens[CallResource] = nullptr;
843 releaseInterferences(CallResource);
847 for (auto &Succ : SU->Succs) {
848 if (Succ.isAssignedRegDep()) {
849 auto Reg = Succ.getReg();
850 if (!LiveRegDefs[Reg])
852 // This becomes the nearest def. Note that an earlier def may still be
853 // pending if this is a two-address node.
854 LiveRegDefs[Reg] = SU;
856 // Update LiveRegGen only if was empty before this unscheduling.
857 // This is to avoid incorrect updating LiveRegGen set in previous run.
858 if (!LiveRegGens[Reg]) {
859 // Find the successor with the lowest height.
860 LiveRegGens[Reg] = Succ.getSUnit();
861 for (auto &Succ2 : SU->Succs) {
862 if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
863 Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
864 LiveRegGens[Reg] = Succ2.getSUnit();
869 if (SU->getHeight() < MinAvailableCycle)
870 MinAvailableCycle = SU->getHeight();
872 SU->setHeightDirty();
873 SU->isScheduled = false;
874 SU->isAvailable = true;
875 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
876 // Don't make available until backtracking is complete.
877 SU->isPending = true;
878 PendingQueue.push_back(SU);
881 AvailableQueue->push(SU);
883 AvailableQueue->unscheduledNode(SU);
886 /// After backtracking, the hazard checker needs to be restored to a state
887 /// corresponding the current cycle.
888 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
891 unsigned LookAhead = std::min((unsigned)Sequence.size(),
892 HazardRec->getMaxLookAhead());
896 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
897 unsigned HazardCycle = (*I)->getHeight();
898 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
900 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
901 HazardRec->RecedeCycle();
907 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
908 /// BTCycle in order to schedule a specific node.
909 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
910 SUnit *OldSU = Sequence.back();
913 // FIXME: use ready cycle instead of height
914 CurCycle = OldSU->getHeight();
915 UnscheduleNodeBottomUp(OldSU);
916 AvailableQueue->setCurCycle(CurCycle);
919 OldSU = Sequence.back();
922 assert(!SU->isSucc(OldSU) && "Something is wrong!");
924 RestoreHazardCheckerBottomUp();
931 static bool isOperandOf(const SUnit *SU, SDNode *N) {
932 for (const SDNode *SUNode = SU->getNode(); SUNode;
933 SUNode = SUNode->getGluedNode()) {
934 if (SUNode->isOperandOf(N))
940 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
941 /// successors to the newly created node.
942 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
943 SDNode *N = SU->getNode();
947 if (SU->getNode()->getGluedNode())
951 bool TryUnfold = false;
952 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
953 MVT VT = N->getSimpleValueType(i);
956 else if (VT == MVT::Other)
959 for (const SDValue &Op : N->op_values()) {
960 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
966 SmallVector<SDNode*, 2> NewNodes;
967 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
970 // unfolding an x86 DEC64m operation results in store, dec, load which
971 // can't be handled here so quit
972 if (NewNodes.size() == 3)
975 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
976 assert(NewNodes.size() == 2 && "Expected a load folding node!");
979 SDNode *LoadNode = NewNodes[0];
980 unsigned NumVals = N->getNumValues();
981 unsigned OldNumVals = SU->getNode()->getNumValues();
982 for (unsigned i = 0; i != NumVals; ++i)
983 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
984 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
985 SDValue(LoadNode, 1));
987 // LoadNode may already exist. This can happen when there is another
988 // load from the same location and producing the same type of value
989 // but it has different alignment or volatileness.
990 bool isNewLoad = true;
992 if (LoadNode->getNodeId() != -1) {
993 LoadSU = &SUnits[LoadNode->getNodeId()];
996 LoadSU = CreateNewSUnit(LoadNode);
997 LoadNode->setNodeId(LoadSU->NodeNum);
999 InitNumRegDefsLeft(LoadSU);
1000 computeLatency(LoadSU);
1003 SUnit *NewSU = CreateNewSUnit(N);
1004 assert(N->getNodeId() == -1 && "Node already inserted!");
1005 N->setNodeId(NewSU->NodeNum);
1007 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1008 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1009 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
1010 NewSU->isTwoAddress = true;
1014 if (MCID.isCommutable())
1015 NewSU->isCommutable = true;
1017 InitNumRegDefsLeft(NewSU);
1018 computeLatency(NewSU);
1020 // Record all the edges to and from the old SU, by category.
1021 SmallVector<SDep, 4> ChainPreds;
1022 SmallVector<SDep, 4> ChainSuccs;
1023 SmallVector<SDep, 4> LoadPreds;
1024 SmallVector<SDep, 4> NodePreds;
1025 SmallVector<SDep, 4> NodeSuccs;
1026 for (SDep &Pred : SU->Preds) {
1028 ChainPreds.push_back(Pred);
1029 else if (isOperandOf(Pred.getSUnit(), LoadNode))
1030 LoadPreds.push_back(Pred);
1032 NodePreds.push_back(Pred);
1034 for (SDep &Succ : SU->Succs) {
1036 ChainSuccs.push_back(Succ);
1038 NodeSuccs.push_back(Succ);
1041 // Now assign edges to the newly-created nodes.
1042 for (const SDep &Pred : ChainPreds) {
1043 RemovePred(SU, Pred);
1045 AddPred(LoadSU, Pred);
1047 for (const SDep &Pred : LoadPreds) {
1048 RemovePred(SU, Pred);
1050 AddPred(LoadSU, Pred);
1052 for (const SDep &Pred : NodePreds) {
1053 RemovePred(SU, Pred);
1054 AddPred(NewSU, Pred);
1056 for (SDep D : NodeSuccs) {
1057 SUnit *SuccDep = D.getSUnit();
1059 RemovePred(SuccDep, D);
1061 AddPred(SuccDep, D);
1062 // Balance register pressure.
1063 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1064 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1065 --NewSU->NumRegDefsLeft;
1067 for (SDep D : ChainSuccs) {
1068 SUnit *SuccDep = D.getSUnit();
1070 RemovePred(SuccDep, D);
1073 AddPred(SuccDep, D);
1077 // Add a data dependency to reflect that NewSU reads the value defined
1079 SDep D(LoadSU, SDep::Data, 0);
1080 D.setLatency(LoadSU->Latency);
1084 AvailableQueue->addNode(LoadSU);
1085 AvailableQueue->addNode(NewSU);
1089 if (NewSU->NumSuccsLeft == 0) {
1090 NewSU->isAvailable = true;
1096 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
1097 NewSU = CreateClone(SU);
1099 // New SUnit has the exact same predecessors.
1100 for (SDep &Pred : SU->Preds)
1101 if (!Pred.isArtificial())
1102 AddPred(NewSU, Pred);
1104 // Only copy scheduled successors. Cut them from old node's successor
1105 // list and move them over.
1106 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1107 for (SDep &Succ : SU->Succs) {
1108 if (Succ.isArtificial())
1110 SUnit *SuccSU = Succ.getSUnit();
1111 if (SuccSU->isScheduled) {
1116 DelDeps.push_back(std::make_pair(SuccSU, D));
1119 for (auto &DelDep : DelDeps)
1120 RemovePred(DelDep.first, DelDep.second);
1122 AvailableQueue->updateNode(SU);
1123 AvailableQueue->addNode(NewSU);
1129 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1130 /// scheduled successors of the given SUnit to the last copy.
1131 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1132 const TargetRegisterClass *DestRC,
1133 const TargetRegisterClass *SrcRC,
1134 SmallVectorImpl<SUnit*> &Copies) {
1135 SUnit *CopyFromSU = CreateNewSUnit(nullptr);
1136 CopyFromSU->CopySrcRC = SrcRC;
1137 CopyFromSU->CopyDstRC = DestRC;
1139 SUnit *CopyToSU = CreateNewSUnit(nullptr);
1140 CopyToSU->CopySrcRC = DestRC;
1141 CopyToSU->CopyDstRC = SrcRC;
1143 // Only copy scheduled successors. Cut them from old node's successor
1144 // list and move them over.
1145 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1146 for (SDep &Succ : SU->Succs) {
1147 if (Succ.isArtificial())
1149 SUnit *SuccSU = Succ.getSUnit();
1150 if (SuccSU->isScheduled) {
1152 D.setSUnit(CopyToSU);
1154 DelDeps.push_back(std::make_pair(SuccSU, Succ));
1157 // Avoid scheduling the def-side copy before other successors. Otherwise
1158 // we could introduce another physreg interference on the copy and
1159 // continue inserting copies indefinitely.
1160 AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
1163 for (auto &DelDep : DelDeps)
1164 RemovePred(DelDep.first, DelDep.second);
1166 SDep FromDep(SU, SDep::Data, Reg);
1167 FromDep.setLatency(SU->Latency);
1168 AddPred(CopyFromSU, FromDep);
1169 SDep ToDep(CopyFromSU, SDep::Data, 0);
1170 ToDep.setLatency(CopyFromSU->Latency);
1171 AddPred(CopyToSU, ToDep);
1173 AvailableQueue->updateNode(SU);
1174 AvailableQueue->addNode(CopyFromSU);
1175 AvailableQueue->addNode(CopyToSU);
1176 Copies.push_back(CopyFromSU);
1177 Copies.push_back(CopyToSU);
1182 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1183 /// definition of the specified node.
1184 /// FIXME: Move to SelectionDAG?
1185 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1186 const TargetInstrInfo *TII) {
1188 if (N->getOpcode() == ISD::CopyFromReg) {
1189 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
1192 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1193 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1194 NumRes = MCID.getNumDefs();
1195 for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1201 return N->getSimpleValueType(NumRes);
1204 /// CheckForLiveRegDef - Return true and update live register vector if the
1205 /// specified register def of the specified SUnit clobbers any "live" registers.
1206 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1207 SUnit **LiveRegDefs,
1208 SmallSet<unsigned, 4> &RegAdded,
1209 SmallVectorImpl<unsigned> &LRegs,
1210 const TargetRegisterInfo *TRI) {
1211 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
1213 // Check if Ref is live.
1214 if (!LiveRegDefs[*AliasI]) continue;
1216 // Allow multiple uses of the same def.
1217 if (LiveRegDefs[*AliasI] == SU) continue;
1219 // Add Reg to the set of interfering live regs.
1220 if (RegAdded.insert(*AliasI).second) {
1221 LRegs.push_back(*AliasI);
1226 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1227 /// by RegMask, and add them to LRegs.
1228 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1229 ArrayRef<SUnit*> LiveRegDefs,
1230 SmallSet<unsigned, 4> &RegAdded,
1231 SmallVectorImpl<unsigned> &LRegs) {
1232 // Look at all live registers. Skip Reg0 and the special CallResource.
1233 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1234 if (!LiveRegDefs[i]) continue;
1235 if (LiveRegDefs[i] == SU) continue;
1236 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1237 if (RegAdded.insert(i).second)
1242 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1243 static const uint32_t *getNodeRegMask(const SDNode *N) {
1244 for (const SDValue &Op : N->op_values())
1245 if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
1246 return RegOp->getRegMask();
1250 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1251 /// scheduling of the given node to satisfy live physical register dependencies.
1252 /// If the specific node is the last one that's available to schedule, do
1253 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1254 bool ScheduleDAGRRList::
1255 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
1256 if (NumLiveRegs == 0)
1259 SmallSet<unsigned, 4> RegAdded;
1260 // If this node would clobber any "live" register, then it's not ready.
1262 // If SU is the currently live definition of the same register that it uses,
1263 // then we are free to schedule it.
1264 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1266 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1267 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs.get(),
1268 RegAdded, LRegs, TRI);
1271 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1272 if (Node->getOpcode() == ISD::INLINEASM) {
1273 // Inline asm can clobber physical defs.
1274 unsigned NumOps = Node->getNumOperands();
1275 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1276 --NumOps; // Ignore the glue operand.
1278 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1280 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1281 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1283 ++i; // Skip the ID value.
1284 if (InlineAsm::isRegDefKind(Flags) ||
1285 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1286 InlineAsm::isClobberKind(Flags)) {
1287 // Check for def of register or earlyclobber register.
1288 for (; NumVals; --NumVals, ++i) {
1289 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1290 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1291 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
1299 if (!Node->isMachineOpcode())
1301 // If we're in the middle of scheduling a call, don't begin scheduling
1302 // another call. Also, don't allow any physical registers to be live across
1304 if ((Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) ||
1305 (Node->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
1306 // Check the special calling-sequence resource.
1307 unsigned CallResource = TRI->getNumRegs();
1308 if (LiveRegDefs[CallResource]) {
1309 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1310 while (SDNode *Glued = Gen->getGluedNode())
1312 if (!IsChainDependent(Gen, Node, 0, TII) &&
1313 RegAdded.insert(CallResource).second)
1314 LRegs.push_back(CallResource);
1317 if (const uint32_t *RegMask = getNodeRegMask(Node))
1318 CheckForLiveRegDefMasked(SU, RegMask,
1319 makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
1322 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1323 if (!MCID.ImplicitDefs)
1325 for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1326 CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
1329 return !LRegs.empty();
1332 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1333 // Add the nodes that aren't ready back onto the available list.
1334 for (unsigned i = Interferences.size(); i > 0; --i) {
1335 SUnit *SU = Interferences[i-1];
1336 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1338 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
1339 if (!is_contained(LRegs, Reg))
1342 SU->isPending = false;
1343 // The interfering node may no longer be available due to backtracking.
1344 // Furthermore, it may have been made available again, in which case it is
1345 // now already in the AvailableQueue.
1346 if (SU->isAvailable && !SU->NodeQueueId) {
1347 DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
1348 AvailableQueue->push(SU);
1350 if (i < Interferences.size())
1351 Interferences[i-1] = Interferences.back();
1352 Interferences.pop_back();
1353 LRegsMap.erase(LRegsPos);
1357 /// Return a node that can be scheduled in this cycle. Requirements:
1358 /// (1) Ready: latency has been satisfied
1359 /// (2) No Hazards: resources are available
1360 /// (3) No Interferences: may unschedule to break register interferences.
1361 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1362 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
1364 SmallVector<unsigned, 4> LRegs;
1365 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1367 DEBUG(dbgs() << " Interfering reg " <<
1368 (LRegs[0] == TRI->getNumRegs() ? "CallResource"
1369 : TRI->getName(LRegs[0]))
1370 << " SU #" << CurSU->NodeNum << '\n');
1371 std::pair<LRegsMapT::iterator, bool> LRegsPair =
1372 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1373 if (LRegsPair.second) {
1374 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1375 Interferences.push_back(CurSU);
1378 assert(CurSU->isPending && "Interferences are pending");
1379 // Update the interference with current live regs.
1380 LRegsPair.first->second = LRegs;
1382 CurSU = AvailableQueue->pop();
1387 // All candidates are delayed due to live physical reg dependencies.
1388 // Try backtracking, code duplication, or inserting cross class copies
1390 for (SUnit *TrySU : Interferences) {
1391 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1393 // Try unscheduling up to the point where it's safe to schedule
1395 SUnit *BtSU = nullptr;
1396 unsigned LiveCycle = UINT_MAX;
1397 for (unsigned Reg : LRegs) {
1398 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1399 BtSU = LiveRegGens[Reg];
1400 LiveCycle = BtSU->getHeight();
1403 if (!WillCreateCycle(TrySU, BtSU)) {
1404 // BacktrackBottomUp mutates Interferences!
1405 BacktrackBottomUp(TrySU, BtSU);
1407 // Force the current node to be scheduled before the node that
1408 // requires the physical reg dep.
1409 if (BtSU->isAvailable) {
1410 BtSU->isAvailable = false;
1411 if (!BtSU->isPending)
1412 AvailableQueue->remove(BtSU);
1414 DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
1415 << TrySU->NodeNum << ")\n");
1416 AddPred(TrySU, SDep(BtSU, SDep::Artificial));
1418 // If one or more successors has been unscheduled, then the current
1419 // node is no longer available.
1420 if (!TrySU->isAvailable || !TrySU->NodeQueueId)
1421 CurSU = AvailableQueue->pop();
1423 // Available and in AvailableQueue
1424 AvailableQueue->remove(TrySU);
1427 // Interferences has been mutated. We must break.
1433 // Can't backtrack. If it's too expensive to copy the value, then try
1434 // duplicate the nodes that produces these "too expensive to copy"
1435 // values to break the dependency. In case even that doesn't work,
1436 // insert cross class copies.
1437 // If it's not too expensive, i.e. cost != -1, issue copies.
1438 SUnit *TrySU = Interferences[0];
1439 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1440 assert(LRegs.size() == 1 && "Can't handle this yet!");
1441 unsigned Reg = LRegs[0];
1442 SUnit *LRDef = LiveRegDefs[Reg];
1443 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1444 const TargetRegisterClass *RC =
1445 TRI->getMinimalPhysRegClass(Reg, VT);
1446 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1448 // If cross copy register class is the same as RC, then it must be possible
1449 // copy the value directly. Do not try duplicate the def.
1450 // If cross copy register class is not the same as RC, then it's possible to
1451 // copy the value but it require cross register class copies and it is
1453 // If cross copy register class is null, then it's not possible to copy
1454 // the value at all.
1455 SUnit *NewDef = nullptr;
1457 NewDef = CopyAndMoveSuccessors(LRDef);
1458 if (!DestRC && !NewDef)
1459 report_fatal_error("Can't handle live physical register dependency!");
1462 // Issue copies, these can be expensive cross register class copies.
1463 SmallVector<SUnit*, 2> Copies;
1464 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1465 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1466 << " to SU #" << Copies.front()->NodeNum << "\n");
1467 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
1468 NewDef = Copies.back();
1471 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1472 << " to SU #" << TrySU->NodeNum << "\n");
1473 LiveRegDefs[Reg] = NewDef;
1474 AddPred(NewDef, SDep(TrySU, SDep::Artificial));
1475 TrySU->isAvailable = false;
1478 assert(CurSU && "Unable to resolve live physical register dependencies!");
1482 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1484 void ScheduleDAGRRList::ListScheduleBottomUp() {
1485 // Release any predecessors of the special Exit node.
1486 ReleasePredecessors(&ExitSU);
1488 // Add root to Available queue.
1489 if (!SUnits.empty()) {
1490 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1491 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1492 RootSU->isAvailable = true;
1493 AvailableQueue->push(RootSU);
1496 // While Available queue is not empty, grab the node with the highest
1497 // priority. If it is not ready put it back. Schedule the node.
1498 Sequence.reserve(SUnits.size());
1499 while (!AvailableQueue->empty() || !Interferences.empty()) {
1500 DEBUG(dbgs() << "\nExamining Available:\n";
1501 AvailableQueue->dump(this));
1503 // Pick the best node to schedule taking all constraints into
1505 SUnit *SU = PickNodeToScheduleBottomUp();
1507 AdvancePastStalls(SU);
1509 ScheduleNodeBottomUp(SU);
1511 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1512 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1513 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1514 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1518 // Reverse the order if it is bottom up.
1519 std::reverse(Sequence.begin(), Sequence.end());
1522 VerifyScheduledSequence(/*isBottomUp=*/true);
1526 //===----------------------------------------------------------------------===//
1527 // RegReductionPriorityQueue Definition
1528 //===----------------------------------------------------------------------===//
1530 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1531 // to reduce register pressure.
1534 class RegReductionPQBase;
1536 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1537 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1542 struct reverse_sort : public queue_sort {
1544 reverse_sort(SF &sf) : SortFunc(sf) {}
1546 bool operator()(SUnit* left, SUnit* right) const {
1547 // reverse left/right rather than simply !SortFunc(left, right)
1548 // to expose different paths in the comparison logic.
1549 return SortFunc(right, left);
1554 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1555 // reduction scheduler.
1556 struct bu_ls_rr_sort : public queue_sort {
1559 HasReadyFilter = false
1562 RegReductionPQBase *SPQ;
1563 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1565 bool operator()(SUnit* left, SUnit* right) const;
1568 // src_ls_rr_sort - Priority function for source order scheduler.
1569 struct src_ls_rr_sort : public queue_sort {
1572 HasReadyFilter = false
1575 RegReductionPQBase *SPQ;
1576 src_ls_rr_sort(RegReductionPQBase *spq)
1579 bool operator()(SUnit* left, SUnit* right) const;
1582 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1583 struct hybrid_ls_rr_sort : public queue_sort {
1586 HasReadyFilter = false
1589 RegReductionPQBase *SPQ;
1590 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1593 bool isReady(SUnit *SU, unsigned CurCycle) const;
1595 bool operator()(SUnit* left, SUnit* right) const;
1598 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1600 struct ilp_ls_rr_sort : public queue_sort {
1603 HasReadyFilter = false
1606 RegReductionPQBase *SPQ;
1607 ilp_ls_rr_sort(RegReductionPQBase *spq)
1610 bool isReady(SUnit *SU, unsigned CurCycle) const;
1612 bool operator()(SUnit* left, SUnit* right) const;
1615 class RegReductionPQBase : public SchedulingPriorityQueue {
1617 std::vector<SUnit*> Queue;
1618 unsigned CurQueueId;
1619 bool TracksRegPressure;
1622 // SUnits - The SUnits for the current graph.
1623 std::vector<SUnit> *SUnits;
1625 MachineFunction &MF;
1626 const TargetInstrInfo *TII;
1627 const TargetRegisterInfo *TRI;
1628 const TargetLowering *TLI;
1629 ScheduleDAGRRList *scheduleDAG;
1631 // SethiUllmanNumbers - The SethiUllman number for each node.
1632 std::vector<unsigned> SethiUllmanNumbers;
1634 /// RegPressure - Tracking current reg pressure per register class.
1636 std::vector<unsigned> RegPressure;
1638 /// RegLimit - Tracking the number of allocatable registers per register
1640 std::vector<unsigned> RegLimit;
1643 RegReductionPQBase(MachineFunction &mf,
1644 bool hasReadyFilter,
1647 const TargetInstrInfo *tii,
1648 const TargetRegisterInfo *tri,
1649 const TargetLowering *tli)
1650 : SchedulingPriorityQueue(hasReadyFilter),
1651 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
1652 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
1653 if (TracksRegPressure) {
1654 unsigned NumRC = TRI->getNumRegClasses();
1655 RegLimit.resize(NumRC);
1656 RegPressure.resize(NumRC);
1657 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1658 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1659 for (const TargetRegisterClass *RC : TRI->regclasses())
1660 RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
1664 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1665 scheduleDAG = scheduleDag;
1668 ScheduleHazardRecognizer* getHazardRec() {
1669 return scheduleDAG->getHazardRec();
1672 void initNodes(std::vector<SUnit> &sunits) override;
1674 void addNode(const SUnit *SU) override;
1676 void updateNode(const SUnit *SU) override;
1678 void releaseState() override {
1680 SethiUllmanNumbers.clear();
1681 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1684 unsigned getNodePriority(const SUnit *SU) const;
1686 unsigned getNodeOrdering(const SUnit *SU) const {
1687 if (!SU->getNode()) return 0;
1689 return SU->getNode()->getIROrder();
1692 bool empty() const override { return Queue.empty(); }
1694 void push(SUnit *U) override {
1695 assert(!U->NodeQueueId && "Node in the queue already");
1696 U->NodeQueueId = ++CurQueueId;
1700 void remove(SUnit *SU) override {
1701 assert(!Queue.empty() && "Queue is empty!");
1702 assert(SU->NodeQueueId != 0 && "Not in queue!");
1703 std::vector<SUnit *>::iterator I = find(Queue, SU);
1704 if (I != std::prev(Queue.end()))
1705 std::swap(*I, Queue.back());
1707 SU->NodeQueueId = 0;
1710 bool tracksRegPressure() const override { return TracksRegPressure; }
1712 void dumpRegPressure() const;
1714 bool HighRegPressure(const SUnit *SU) const;
1716 bool MayReduceRegPressure(SUnit *SU) const;
1718 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1720 void scheduledNode(SUnit *SU) override;
1722 void unscheduledNode(SUnit *SU) override;
1725 bool canClobber(const SUnit *SU, const SUnit *Op);
1726 void AddPseudoTwoAddrDeps();
1727 void PrescheduleNodesWithMultipleUses();
1728 void CalculateSethiUllmanNumbers();
1732 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1733 std::vector<SUnit *>::iterator Best = Q.begin();
1734 for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
1735 E = Q.end(); I != E; ++I)
1736 if (Picker(*Best, *I))
1739 if (Best != std::prev(Q.end()))
1740 std::swap(*Best, Q.back());
1746 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1748 if (DAG->StressSched) {
1749 reverse_sort<SF> RPicker(Picker);
1750 return popFromQueueImpl(Q, RPicker);
1754 return popFromQueueImpl(Q, Picker);
1758 class RegReductionPriorityQueue : public RegReductionPQBase {
1762 RegReductionPriorityQueue(MachineFunction &mf,
1765 const TargetInstrInfo *tii,
1766 const TargetRegisterInfo *tri,
1767 const TargetLowering *tli)
1768 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1772 bool isBottomUp() const override { return SF::IsBottomUp; }
1774 bool isReady(SUnit *U) const override {
1775 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1778 SUnit *pop() override {
1779 if (Queue.empty()) return nullptr;
1781 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1786 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1787 LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
1788 // Emulate pop() without clobbering NodeQueueIds.
1789 std::vector<SUnit*> DumpQueue = Queue;
1790 SF DumpPicker = Picker;
1791 while (!DumpQueue.empty()) {
1792 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1793 dbgs() << "Height " << SU->getHeight() << ": ";
1800 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1801 BURegReductionPriorityQueue;
1803 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1804 SrcRegReductionPriorityQueue;
1806 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1807 HybridBURRPriorityQueue;
1809 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1810 ILPBURRPriorityQueue;
1811 } // end anonymous namespace
1813 //===----------------------------------------------------------------------===//
1814 // Static Node Priority for Register Pressure Reduction
1815 //===----------------------------------------------------------------------===//
1817 // Check for special nodes that bypass scheduling heuristics.
1818 // Currently this pushes TokenFactor nodes down, but may be used for other
1819 // pseudo-ops as well.
1821 // Return -1 to schedule right above left, 1 for left above right.
1822 // Return 0 if no bias exists.
1823 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1824 bool LSchedLow = left->isScheduleLow;
1825 bool RSchedLow = right->isScheduleLow;
1826 if (LSchedLow != RSchedLow)
1827 return LSchedLow < RSchedLow ? 1 : -1;
1831 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1832 /// Smaller number is the higher priority.
1834 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1835 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1836 if (SethiUllmanNumber != 0)
1837 return SethiUllmanNumber;
1840 for (const SDep &Pred : SU->Preds) {
1841 if (Pred.isCtrl()) continue; // ignore chain preds
1842 SUnit *PredSU = Pred.getSUnit();
1843 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1844 if (PredSethiUllman > SethiUllmanNumber) {
1845 SethiUllmanNumber = PredSethiUllman;
1847 } else if (PredSethiUllman == SethiUllmanNumber)
1851 SethiUllmanNumber += Extra;
1853 if (SethiUllmanNumber == 0)
1854 SethiUllmanNumber = 1;
1856 return SethiUllmanNumber;
1859 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1860 /// scheduling units.
1861 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1862 SethiUllmanNumbers.assign(SUnits->size(), 0);
1864 for (const SUnit &SU : *SUnits)
1865 CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
1868 void RegReductionPQBase::addNode(const SUnit *SU) {
1869 unsigned SUSize = SethiUllmanNumbers.size();
1870 if (SUnits->size() > SUSize)
1871 SethiUllmanNumbers.resize(SUSize*2, 0);
1872 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1875 void RegReductionPQBase::updateNode(const SUnit *SU) {
1876 SethiUllmanNumbers[SU->NodeNum] = 0;
1877 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1880 // Lower priority means schedule further down. For bottom-up scheduling, lower
1881 // priority SUs are scheduled before higher priority SUs.
1882 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1883 assert(SU->NodeNum < SethiUllmanNumbers.size());
1884 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1885 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1886 // CopyToReg should be close to its uses to facilitate coalescing and
1889 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1890 Opc == TargetOpcode::SUBREG_TO_REG ||
1891 Opc == TargetOpcode::INSERT_SUBREG)
1892 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1893 // close to their uses to facilitate coalescing.
1895 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1896 // If SU does not have a register use, i.e. it doesn't produce a value
1897 // that would be consumed (e.g. store), then it terminates a chain of
1898 // computation. Give it a large SethiUllman number so it will be
1899 // scheduled right before its predecessors that it doesn't lengthen
1900 // their live ranges.
1902 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1903 // If SU does not have a register def, schedule it close to its uses
1904 // because it does not lengthen any live ranges.
1907 return SethiUllmanNumbers[SU->NodeNum];
1909 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1911 // FIXME: This assumes all of the defs are used as call operands.
1912 int NP = (int)Priority - SU->getNode()->getNumValues();
1913 return (NP > 0) ? NP : 0;
1919 //===----------------------------------------------------------------------===//
1920 // Register Pressure Tracking
1921 //===----------------------------------------------------------------------===//
1923 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1924 LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
1925 for (const TargetRegisterClass *RC : TRI->regclasses()) {
1926 unsigned Id = RC->getID();
1927 unsigned RP = RegPressure[Id];
1929 DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
1930 << RegLimit[Id] << '\n');
1935 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1939 for (const SDep &Pred : SU->Preds) {
1942 SUnit *PredSU = Pred.getSUnit();
1943 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1944 // to cover the number of registers defined (they are all live).
1945 if (PredSU->NumRegDefsLeft == 0) {
1948 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1949 RegDefPos.IsValid(); RegDefPos.Advance()) {
1950 unsigned RCId, Cost;
1951 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
1953 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1960 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1961 const SDNode *N = SU->getNode();
1963 if (!N->isMachineOpcode() || !SU->NumSuccs)
1966 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1967 for (unsigned i = 0; i != NumDefs; ++i) {
1968 MVT VT = N->getSimpleValueType(i);
1969 if (!N->hasAnyUseOfValue(i))
1971 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1972 if (RegPressure[RCId] >= RegLimit[RCId])
1978 // Compute the register pressure contribution by this instruction by count up
1979 // for uses that are not live and down for defs. Only count register classes
1980 // that are already under high pressure. As a side effect, compute the number of
1981 // uses of registers that are already live.
1983 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1984 // so could probably be factored.
1985 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1988 for (const SDep &Pred : SU->Preds) {
1991 SUnit *PredSU = Pred.getSUnit();
1992 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1993 // to cover the number of registers defined (they are all live).
1994 if (PredSU->NumRegDefsLeft == 0) {
1995 if (PredSU->getNode()->isMachineOpcode())
1999 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2000 RegDefPos.IsValid(); RegDefPos.Advance()) {
2001 MVT VT = RegDefPos.GetValue();
2002 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2003 if (RegPressure[RCId] >= RegLimit[RCId])
2007 const SDNode *N = SU->getNode();
2009 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
2012 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2013 for (unsigned i = 0; i != NumDefs; ++i) {
2014 MVT VT = N->getSimpleValueType(i);
2015 if (!N->hasAnyUseOfValue(i))
2017 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2018 if (RegPressure[RCId] >= RegLimit[RCId])
2024 void RegReductionPQBase::scheduledNode(SUnit *SU) {
2025 if (!TracksRegPressure)
2031 for (const SDep &Pred : SU->Preds) {
2034 SUnit *PredSU = Pred.getSUnit();
2035 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2036 // to cover the number of registers defined (they are all live).
2037 if (PredSU->NumRegDefsLeft == 0) {
2040 // FIXME: The ScheduleDAG currently loses information about which of a
2041 // node's values is consumed by each dependence. Consequently, if the node
2042 // defines multiple register classes, we don't know which to pressurize
2043 // here. Instead the following loop consumes the register defs in an
2044 // arbitrary order. At least it handles the common case of clustered loads
2045 // to the same class. For precise liveness, each SDep needs to indicate the
2046 // result number. But that tightly couples the ScheduleDAG with the
2047 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2048 // value type or register class to SDep.
2050 // The most important aspect of register tracking is balancing the increase
2051 // here with the reduction further below. Note that this SU may use multiple
2052 // defs in PredSU. The can't be determined here, but we've already
2053 // compensated by reducing NumRegDefsLeft in PredSU during
2054 // ScheduleDAGSDNodes::AddSchedEdges.
2055 --PredSU->NumRegDefsLeft;
2056 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2057 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2058 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2062 unsigned RCId, Cost;
2063 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2064 RegPressure[RCId] += Cost;
2069 // We should have this assert, but there may be dead SDNodes that never
2070 // materialize as SUnits, so they don't appear to generate liveness.
2071 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2072 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2073 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2074 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2075 if (SkipRegDefs > 0)
2077 unsigned RCId, Cost;
2078 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2079 if (RegPressure[RCId] < Cost) {
2080 // Register pressure tracking is imprecise. This can happen. But we try
2081 // hard not to let it happen because it likely results in poor scheduling.
2082 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2083 RegPressure[RCId] = 0;
2086 RegPressure[RCId] -= Cost;
2089 DEBUG(dumpRegPressure());
2092 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2093 if (!TracksRegPressure)
2096 const SDNode *N = SU->getNode();
2099 if (!N->isMachineOpcode()) {
2100 if (N->getOpcode() != ISD::CopyToReg)
2103 unsigned Opc = N->getMachineOpcode();
2104 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2105 Opc == TargetOpcode::INSERT_SUBREG ||
2106 Opc == TargetOpcode::SUBREG_TO_REG ||
2107 Opc == TargetOpcode::REG_SEQUENCE ||
2108 Opc == TargetOpcode::IMPLICIT_DEF)
2112 for (const SDep &Pred : SU->Preds) {
2115 SUnit *PredSU = Pred.getSUnit();
2116 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2117 // counts data deps.
2118 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2120 const SDNode *PN = PredSU->getNode();
2121 if (!PN->isMachineOpcode()) {
2122 if (PN->getOpcode() == ISD::CopyFromReg) {
2123 MVT VT = PN->getSimpleValueType(0);
2124 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2125 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2129 unsigned POpc = PN->getMachineOpcode();
2130 if (POpc == TargetOpcode::IMPLICIT_DEF)
2132 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2133 POpc == TargetOpcode::INSERT_SUBREG ||
2134 POpc == TargetOpcode::SUBREG_TO_REG) {
2135 MVT VT = PN->getSimpleValueType(0);
2136 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2137 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2140 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2141 for (unsigned i = 0; i != NumDefs; ++i) {
2142 MVT VT = PN->getSimpleValueType(i);
2143 if (!PN->hasAnyUseOfValue(i))
2145 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2146 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2147 // Register pressure tracking is imprecise. This can happen.
2148 RegPressure[RCId] = 0;
2150 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2154 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2155 // may transfer data dependencies to CopyToReg.
2156 if (SU->NumSuccs && N->isMachineOpcode()) {
2157 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2158 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2159 MVT VT = N->getSimpleValueType(i);
2160 if (VT == MVT::Glue || VT == MVT::Other)
2162 if (!N->hasAnyUseOfValue(i))
2164 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2165 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2169 DEBUG(dumpRegPressure());
2172 //===----------------------------------------------------------------------===//
2173 // Dynamic Node Priority for Register Pressure Reduction
2174 //===----------------------------------------------------------------------===//
2176 /// closestSucc - Returns the scheduled cycle of the successor which is
2177 /// closest to the current cycle.
2178 static unsigned closestSucc(const SUnit *SU) {
2179 unsigned MaxHeight = 0;
2180 for (const SDep &Succ : SU->Succs) {
2181 if (Succ.isCtrl()) continue; // ignore chain succs
2182 unsigned Height = Succ.getSUnit()->getHeight();
2183 // If there are bunch of CopyToRegs stacked up, they should be considered
2184 // to be at the same position.
2185 if (Succ.getSUnit()->getNode() &&
2186 Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2187 Height = closestSucc(Succ.getSUnit())+1;
2188 if (Height > MaxHeight)
2194 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2195 /// for scratch registers, i.e. number of data dependencies.
2196 static unsigned calcMaxScratches(const SUnit *SU) {
2197 unsigned Scratches = 0;
2198 for (const SDep &Pred : SU->Preds) {
2199 if (Pred.isCtrl()) continue; // ignore chain preds
2205 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2206 /// CopyFromReg from a virtual register.
2207 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2208 bool RetVal = false;
2209 for (const SDep &Pred : SU->Preds) {
2210 if (Pred.isCtrl()) continue;
2211 const SUnit *PredSU = Pred.getSUnit();
2212 if (PredSU->getNode() &&
2213 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2215 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2216 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2226 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2227 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2228 /// it has no other use. It should be scheduled closer to the terminator.
2229 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2230 bool RetVal = false;
2231 for (const SDep &Succ : SU->Succs) {
2232 if (Succ.isCtrl()) continue;
2233 const SUnit *SuccSU = Succ.getSUnit();
2234 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2236 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2237 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2247 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2248 // set isVRegCycle for its CopyFromReg operands.
2250 // This is only relevant for single-block loops, in which case the VRegCycle
2251 // node is likely an induction variable in which the operand and target virtual
2252 // registers should be coalesced (e.g. pre/post increment values). Setting the
2253 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2254 // CopyFromReg so that this node becomes the virtual register "kill". This
2255 // avoids interference between the values live in and out of the block and
2256 // eliminates a copy inside the loop.
2257 static void initVRegCycle(SUnit *SU) {
2258 if (DisableSchedVRegCycle)
2261 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2264 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2266 SU->isVRegCycle = true;
2268 for (const SDep &Pred : SU->Preds) {
2269 if (Pred.isCtrl()) continue;
2270 Pred.getSUnit()->isVRegCycle = true;
2274 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2275 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2276 static void resetVRegCycle(SUnit *SU) {
2277 if (!SU->isVRegCycle)
2280 for (const SDep &Pred : SU->Preds) {
2281 if (Pred.isCtrl()) continue; // ignore chain preds
2282 SUnit *PredSU = Pred.getSUnit();
2283 if (PredSU->isVRegCycle) {
2284 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2285 "VRegCycle def must be CopyFromReg");
2286 Pred.getSUnit()->isVRegCycle = false;
2291 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2292 // means a node that defines the VRegCycle has not been scheduled yet.
2293 static bool hasVRegCycleUse(const SUnit *SU) {
2294 // If this SU also defines the VReg, don't hoist it as a "use".
2295 if (SU->isVRegCycle)
2298 for (const SDep &Pred : SU->Preds) {
2299 if (Pred.isCtrl()) continue; // ignore chain preds
2300 if (Pred.getSUnit()->isVRegCycle &&
2301 Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2302 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2309 // Check for either a dependence (latency) or resource (hazard) stall.
2311 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2312 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2313 if ((int)SPQ->getCurCycle() < Height) return true;
2314 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2315 != ScheduleHazardRecognizer::NoHazard)
2320 // Return -1 if left has higher priority, 1 if right has higher priority.
2321 // Return 0 if latency-based priority is equivalent.
2322 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2323 RegReductionPQBase *SPQ) {
2324 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2325 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2326 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2327 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2328 int LHeight = (int)left->getHeight() + LPenalty;
2329 int RHeight = (int)right->getHeight() + RPenalty;
2331 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2332 BUHasStall(left, LHeight, SPQ);
2333 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2334 BUHasStall(right, RHeight, SPQ);
2336 // If scheduling one of the node will cause a pipeline stall, delay it.
2337 // If scheduling either one of the node will cause a pipeline stall, sort
2338 // them according to their height.
2342 if (LHeight != RHeight)
2343 return LHeight > RHeight ? 1 : -1;
2347 // If either node is scheduling for latency, sort them by height/depth
2349 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2350 right->SchedulingPref == Sched::ILP)) {
2351 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2352 // is enabled, grouping instructions by cycle, then its height is already
2353 // covered so only its depth matters. We also reach this point if both stall
2354 // but have the same height.
2355 if (!SPQ->getHazardRec()->isEnabled()) {
2356 if (LHeight != RHeight)
2357 return LHeight > RHeight ? 1 : -1;
2359 int LDepth = left->getDepth() - LPenalty;
2360 int RDepth = right->getDepth() - RPenalty;
2361 if (LDepth != RDepth) {
2362 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2363 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2364 << ") depth " << RDepth << "\n");
2365 return LDepth < RDepth ? 1 : -1;
2367 if (left->Latency != right->Latency)
2368 return left->Latency > right->Latency ? 1 : -1;
2373 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2374 // Schedule physical register definitions close to their use. This is
2375 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2376 // long as shortening physreg live ranges is generally good, we can defer
2377 // creating a subtarget hook.
2378 if (!DisableSchedPhysRegJoin) {
2379 bool LHasPhysReg = left->hasPhysRegDefs;
2380 bool RHasPhysReg = right->hasPhysRegDefs;
2381 if (LHasPhysReg != RHasPhysReg) {
2383 static const char *const PhysRegMsg[] = { " has no physreg",
2384 " defines a physreg" };
2386 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2387 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2388 << PhysRegMsg[RHasPhysReg] << "\n");
2389 return LHasPhysReg < RHasPhysReg;
2393 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2394 unsigned LPriority = SPQ->getNodePriority(left);
2395 unsigned RPriority = SPQ->getNodePriority(right);
2397 // Be really careful about hoisting call operands above previous calls.
2398 // Only allows it if it would reduce register pressure.
2399 if (left->isCall && right->isCallOp) {
2400 unsigned RNumVals = right->getNode()->getNumValues();
2401 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2403 if (right->isCall && left->isCallOp) {
2404 unsigned LNumVals = left->getNode()->getNumValues();
2405 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2408 if (LPriority != RPriority)
2409 return LPriority > RPriority;
2411 // One or both of the nodes are calls and their sethi-ullman numbers are the
2412 // same, then keep source order.
2413 if (left->isCall || right->isCall) {
2414 unsigned LOrder = SPQ->getNodeOrdering(left);
2415 unsigned ROrder = SPQ->getNodeOrdering(right);
2417 // Prefer an ordering where the lower the non-zero order number, the higher
2419 if ((LOrder || ROrder) && LOrder != ROrder)
2420 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2423 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2428 // and the following instructions are both ready.
2432 // Then schedule t2 = op first.
2439 // This creates more short live intervals.
2440 unsigned LDist = closestSucc(left);
2441 unsigned RDist = closestSucc(right);
2443 return LDist < RDist;
2445 // How many registers becomes live when the node is scheduled.
2446 unsigned LScratch = calcMaxScratches(left);
2447 unsigned RScratch = calcMaxScratches(right);
2448 if (LScratch != RScratch)
2449 return LScratch > RScratch;
2451 // Comparing latency against a call makes little sense unless the node
2452 // is register pressure-neutral.
2453 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2454 return (left->NodeQueueId > right->NodeQueueId);
2456 // Do not compare latencies when one or both of the nodes are calls.
2457 if (!DisableSchedCycles &&
2458 !(left->isCall || right->isCall)) {
2459 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2464 if (left->getHeight() != right->getHeight())
2465 return left->getHeight() > right->getHeight();
2467 if (left->getDepth() != right->getDepth())
2468 return left->getDepth() < right->getDepth();
2471 assert(left->NodeQueueId && right->NodeQueueId &&
2472 "NodeQueueId cannot be zero");
2473 return (left->NodeQueueId > right->NodeQueueId);
2477 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2478 if (int res = checkSpecialNodes(left, right))
2481 return BURRSort(left, right, SPQ);
2484 // Source order, otherwise bottom up.
2485 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2486 if (int res = checkSpecialNodes(left, right))
2489 unsigned LOrder = SPQ->getNodeOrdering(left);
2490 unsigned ROrder = SPQ->getNodeOrdering(right);
2492 // Prefer an ordering where the lower the non-zero order number, the higher
2494 if ((LOrder || ROrder) && LOrder != ROrder)
2495 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2497 return BURRSort(left, right, SPQ);
2500 // If the time between now and when the instruction will be ready can cover
2501 // the spill code, then avoid adding it to the ready queue. This gives long
2502 // stalls highest priority and allows hoisting across calls. It should also
2503 // speed up processing the available queue.
2504 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2505 static const unsigned ReadyDelay = 3;
2507 if (SPQ->MayReduceRegPressure(SU)) return true;
2509 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2511 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2512 != ScheduleHazardRecognizer::NoHazard)
2518 // Return true if right should be scheduled with higher priority than left.
2519 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2520 if (int res = checkSpecialNodes(left, right))
2523 if (left->isCall || right->isCall)
2524 // No way to compute latency of calls.
2525 return BURRSort(left, right, SPQ);
2527 bool LHigh = SPQ->HighRegPressure(left);
2528 bool RHigh = SPQ->HighRegPressure(right);
2529 // Avoid causing spills. If register pressure is high, schedule for
2530 // register pressure reduction.
2531 if (LHigh && !RHigh) {
2532 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2533 << right->NodeNum << ")\n");
2536 else if (!LHigh && RHigh) {
2537 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2538 << left->NodeNum << ")\n");
2541 if (!LHigh && !RHigh) {
2542 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2546 return BURRSort(left, right, SPQ);
2549 // Schedule as many instructions in each cycle as possible. So don't make an
2550 // instruction available unless it is ready in the current cycle.
2551 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2552 if (SU->getHeight() > CurCycle) return false;
2554 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2555 != ScheduleHazardRecognizer::NoHazard)
2561 static bool canEnableCoalescing(SUnit *SU) {
2562 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2563 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2564 // CopyToReg should be close to its uses to facilitate coalescing and
2568 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2569 Opc == TargetOpcode::SUBREG_TO_REG ||
2570 Opc == TargetOpcode::INSERT_SUBREG)
2571 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2572 // close to their uses to facilitate coalescing.
2575 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2576 // If SU does not have a register def, schedule it close to its uses
2577 // because it does not lengthen any live ranges.
2583 // list-ilp is currently an experimental scheduler that allows various
2584 // heuristics to be enabled prior to the normal register reduction logic.
2585 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2586 if (int res = checkSpecialNodes(left, right))
2589 if (left->isCall || right->isCall)
2590 // No way to compute latency of calls.
2591 return BURRSort(left, right, SPQ);
2593 unsigned LLiveUses = 0, RLiveUses = 0;
2594 int LPDiff = 0, RPDiff = 0;
2595 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2596 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2597 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2599 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2600 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2601 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2602 return LPDiff > RPDiff;
2605 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2606 bool LReduce = canEnableCoalescing(left);
2607 bool RReduce = canEnableCoalescing(right);
2608 if (LReduce && !RReduce) return false;
2609 if (RReduce && !LReduce) return true;
2612 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2613 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2614 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2615 return LLiveUses < RLiveUses;
2618 if (!DisableSchedStalls) {
2619 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2620 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2621 if (LStall != RStall)
2622 return left->getHeight() > right->getHeight();
2625 if (!DisableSchedCriticalPath) {
2626 int spread = (int)left->getDepth() - (int)right->getDepth();
2627 if (std::abs(spread) > MaxReorderWindow) {
2628 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2629 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2630 << right->getDepth() << "\n");
2631 return left->getDepth() < right->getDepth();
2635 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2636 int spread = (int)left->getHeight() - (int)right->getHeight();
2637 if (std::abs(spread) > MaxReorderWindow)
2638 return left->getHeight() > right->getHeight();
2641 return BURRSort(left, right, SPQ);
2644 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2646 // Add pseudo dependency edges for two-address nodes.
2647 if (!Disable2AddrHack)
2648 AddPseudoTwoAddrDeps();
2649 // Reroute edges to nodes with multiple uses.
2650 if (!TracksRegPressure && !SrcOrder)
2651 PrescheduleNodesWithMultipleUses();
2652 // Calculate node priorities.
2653 CalculateSethiUllmanNumbers();
2655 // For single block loops, mark nodes that look like canonical IV increments.
2656 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2657 for (SUnit &SU : sunits)
2661 //===----------------------------------------------------------------------===//
2662 // Preschedule for Register Pressure
2663 //===----------------------------------------------------------------------===//
2665 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2666 if (SU->isTwoAddress) {
2667 unsigned Opc = SU->getNode()->getMachineOpcode();
2668 const MCInstrDesc &MCID = TII->get(Opc);
2669 unsigned NumRes = MCID.getNumDefs();
2670 unsigned NumOps = MCID.getNumOperands() - NumRes;
2671 for (unsigned i = 0; i != NumOps; ++i) {
2672 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2673 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2674 if (DU->getNodeId() != -1 &&
2675 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2683 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2684 /// successor's explicit physregs whose definition can reach DepSU.
2685 /// i.e. DepSU should not be scheduled above SU.
2686 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2687 ScheduleDAGRRList *scheduleDAG,
2688 const TargetInstrInfo *TII,
2689 const TargetRegisterInfo *TRI) {
2690 const MCPhysReg *ImpDefs
2691 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2692 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2693 if(!ImpDefs && !RegMask)
2696 for (const SDep &Succ : SU->Succs) {
2697 SUnit *SuccSU = Succ.getSUnit();
2698 for (const SDep &SuccPred : SuccSU->Preds) {
2699 if (!SuccPred.isAssignedRegDep())
2703 MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
2704 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2708 for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2709 // Return true if SU clobbers this physical register use and the
2710 // definition of the register reaches from DepSU. IsReachable queries
2711 // a topological forward sort of the DAG (following the successors).
2712 if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
2713 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2720 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2721 /// physical register defs.
2722 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2723 const TargetInstrInfo *TII,
2724 const TargetRegisterInfo *TRI) {
2725 SDNode *N = SuccSU->getNode();
2726 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2727 const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2728 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2729 for (const SDNode *SUNode = SU->getNode(); SUNode;
2730 SUNode = SUNode->getGluedNode()) {
2731 if (!SUNode->isMachineOpcode())
2733 const MCPhysReg *SUImpDefs =
2734 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2735 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2736 if (!SUImpDefs && !SURegMask)
2738 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2739 MVT VT = N->getSimpleValueType(i);
2740 if (VT == MVT::Glue || VT == MVT::Other)
2742 if (!N->hasAnyUseOfValue(i))
2744 unsigned Reg = ImpDefs[i - NumDefs];
2745 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2749 for (;*SUImpDefs; ++SUImpDefs) {
2750 unsigned SUReg = *SUImpDefs;
2751 if (TRI->regsOverlap(Reg, SUReg))
2759 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2760 /// are not handled well by the general register pressure reduction
2761 /// heuristics. When presented with code like this:
2770 /// the heuristics tend to push the store up, but since the
2771 /// operand of the store has another use (U), this would increase
2772 /// the length of that other use (the U->N edge).
2774 /// This function transforms code like the above to route U's
2775 /// dependence through the store when possible, like this:
2786 /// This results in the store being scheduled immediately
2787 /// after N, which shortens the U->N live range, reducing
2788 /// register pressure.
2790 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2791 // Visit all the nodes in topological order, working top-down.
2792 for (SUnit &SU : *SUnits) {
2793 // For now, only look at nodes with no data successors, such as stores.
2794 // These are especially important, due to the heuristics in
2795 // getNodePriority for nodes with no data successors.
2796 if (SU.NumSuccs != 0)
2798 // For now, only look at nodes with exactly one data predecessor.
2799 if (SU.NumPreds != 1)
2801 // Avoid prescheduling copies to virtual registers, which don't behave
2802 // like other nodes from the perspective of scheduling heuristics.
2803 if (SDNode *N = SU.getNode())
2804 if (N->getOpcode() == ISD::CopyToReg &&
2805 TargetRegisterInfo::isVirtualRegister
2806 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2809 // Locate the single data predecessor.
2810 SUnit *PredSU = nullptr;
2811 for (const SDep &Pred : SU.Preds)
2812 if (!Pred.isCtrl()) {
2813 PredSU = Pred.getSUnit();
2818 // Don't rewrite edges that carry physregs, because that requires additional
2819 // support infrastructure.
2820 if (PredSU->hasPhysRegDefs)
2822 // Short-circuit the case where SU is PredSU's only data successor.
2823 if (PredSU->NumSuccs == 1)
2825 // Avoid prescheduling to copies from virtual registers, which don't behave
2826 // like other nodes from the perspective of scheduling heuristics.
2827 if (SDNode *N = SU.getNode())
2828 if (N->getOpcode() == ISD::CopyFromReg &&
2829 TargetRegisterInfo::isVirtualRegister
2830 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2833 // Perform checks on the successors of PredSU.
2834 for (const SDep &PredSucc : PredSU->Succs) {
2835 SUnit *PredSuccSU = PredSucc.getSUnit();
2836 if (PredSuccSU == &SU) continue;
2837 // If PredSU has another successor with no data successors, for
2838 // now don't attempt to choose either over the other.
2839 if (PredSuccSU->NumSuccs == 0)
2840 goto outer_loop_continue;
2841 // Don't break physical register dependencies.
2842 if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2843 if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
2844 goto outer_loop_continue;
2845 // Don't introduce graph cycles.
2846 if (scheduleDAG->IsReachable(&SU, PredSuccSU))
2847 goto outer_loop_continue;
2850 // Ok, the transformation is safe and the heuristics suggest it is
2851 // profitable. Update the graph.
2852 DEBUG(dbgs() << " Prescheduling SU #" << SU.NodeNum
2853 << " next to PredSU #" << PredSU->NodeNum
2854 << " to guide scheduling in the presence of multiple uses\n");
2855 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2856 SDep Edge = PredSU->Succs[i];
2857 assert(!Edge.isAssignedRegDep());
2858 SUnit *SuccSU = Edge.getSUnit();
2859 if (SuccSU != &SU) {
2860 Edge.setSUnit(PredSU);
2861 scheduleDAG->RemovePred(SuccSU, Edge);
2862 scheduleDAG->AddPred(&SU, Edge);
2864 scheduleDAG->AddPred(SuccSU, Edge);
2868 outer_loop_continue:;
2872 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2873 /// it as a def&use operand. Add a pseudo control edge from it to the other
2874 /// node (if it won't create a cycle) so the two-address one will be scheduled
2875 /// first (lower in the schedule). If both nodes are two-address, favor the
2876 /// one that has a CopyToReg use (more likely to be a loop induction update).
2877 /// If both are two-address, but one is commutable while the other is not
2878 /// commutable, favor the one that's not commutable.
2879 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2880 for (SUnit &SU : *SUnits) {
2881 if (!SU.isTwoAddress)
2884 SDNode *Node = SU.getNode();
2885 if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
2888 bool isLiveOut = hasOnlyLiveOutUses(&SU);
2889 unsigned Opc = Node->getMachineOpcode();
2890 const MCInstrDesc &MCID = TII->get(Opc);
2891 unsigned NumRes = MCID.getNumDefs();
2892 unsigned NumOps = MCID.getNumOperands() - NumRes;
2893 for (unsigned j = 0; j != NumOps; ++j) {
2894 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2896 SDNode *DU = SU.getNode()->getOperand(j).getNode();
2897 if (DU->getNodeId() == -1)
2899 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2902 for (const SDep &Succ : DUSU->Succs) {
2905 SUnit *SuccSU = Succ.getSUnit();
2908 // Be conservative. Ignore if nodes aren't at roughly the same
2909 // depth and height.
2910 if (SuccSU->getHeight() < SU.getHeight() &&
2911 (SU.getHeight() - SuccSU->getHeight()) > 1)
2913 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2914 // constrains whatever is using the copy, instead of the copy
2915 // itself. In the case that the copy is coalesced, this
2916 // preserves the intent of the pseudo two-address heurietics.
2917 while (SuccSU->Succs.size() == 1 &&
2918 SuccSU->getNode()->isMachineOpcode() &&
2919 SuccSU->getNode()->getMachineOpcode() ==
2920 TargetOpcode::COPY_TO_REGCLASS)
2921 SuccSU = SuccSU->Succs.front().getSUnit();
2922 // Don't constrain non-instruction nodes.
2923 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2925 // Don't constrain nodes with physical register defs if the
2926 // predecessor can clobber them.
2927 if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
2928 if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
2931 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2932 // these may be coalesced away. We want them close to their uses.
2933 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2934 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2935 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2936 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2938 if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
2939 (!canClobber(SuccSU, DUSU) ||
2940 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2941 (!SU.isCommutable && SuccSU->isCommutable)) &&
2942 !scheduleDAG->IsReachable(SuccSU, &SU)) {
2943 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2944 << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2945 scheduleDAG->AddPred(&SU, SDep(SuccSU, SDep::Artificial));
2952 //===----------------------------------------------------------------------===//
2953 // Public Constructor Functions
2954 //===----------------------------------------------------------------------===//
2956 llvm::ScheduleDAGSDNodes *
2957 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2958 CodeGenOpt::Level OptLevel) {
2959 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2960 const TargetInstrInfo *TII = STI.getInstrInfo();
2961 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2963 BURegReductionPriorityQueue *PQ =
2964 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
2965 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2966 PQ->setScheduleDAG(SD);
2970 llvm::ScheduleDAGSDNodes *
2971 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2972 CodeGenOpt::Level OptLevel) {
2973 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2974 const TargetInstrInfo *TII = STI.getInstrInfo();
2975 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2977 SrcRegReductionPriorityQueue *PQ =
2978 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
2979 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2980 PQ->setScheduleDAG(SD);
2984 llvm::ScheduleDAGSDNodes *
2985 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2986 CodeGenOpt::Level OptLevel) {
2987 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2988 const TargetInstrInfo *TII = STI.getInstrInfo();
2989 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2990 const TargetLowering *TLI = IS->TLI;
2992 HybridBURRPriorityQueue *PQ =
2993 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
2995 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2996 PQ->setScheduleDAG(SD);
3000 llvm::ScheduleDAGSDNodes *
3001 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
3002 CodeGenOpt::Level OptLevel) {
3003 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3004 const TargetInstrInfo *TII = STI.getInstrInfo();
3005 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3006 const TargetLowering *TLI = IS->TLI;
3008 ILPBURRPriorityQueue *PQ =
3009 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3010 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3011 PQ->setScheduleDAG(SD);