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::vector<SUnit*> LiveRegDefs;
145 std::vector<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() {
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.resize(TRI->getNumRegs() + 1, nullptr);
332 LiveRegGens.resize(TRI->getNumRegs() + 1, nullptr);
333 CallSeqEndForStart.clear();
334 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
336 // Build the scheduling graph.
337 BuildSchedGraph(nullptr);
339 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
340 SUnits[su].dumpAll(this));
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 (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
419 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
423 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
424 if (N->isMachineOpcode()) {
425 if (N->getMachineOpcode() ==
426 (unsigned)TII->getCallFrameDestroyOpcode()) {
428 } else if (N->getMachineOpcode() ==
429 (unsigned)TII->getCallFrameSetupOpcode()) {
435 // Otherwise, find the chain and continue climbing.
436 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
437 if (N->getOperand(i).getValueType() == MVT::Other) {
438 N = N->getOperand(i).getNode();
439 goto found_chain_operand;
442 found_chain_operand:;
443 if (N->getOpcode() == ISD::EntryToken)
448 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
449 /// the corresponding (lowered) CALLSEQ_BEGIN node.
451 /// NestLevel and MaxNested are used in recursion to indcate the current level
452 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
453 /// level seen so far.
455 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
456 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
458 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
459 const TargetInstrInfo *TII) {
461 // For a TokenFactor, examine each operand. There may be multiple ways
462 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
463 // most nesting in order to ensure that we find the corresponding match.
464 if (N->getOpcode() == ISD::TokenFactor) {
465 SDNode *Best = nullptr;
466 unsigned BestMaxNest = MaxNest;
467 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
468 unsigned MyNestLevel = NestLevel;
469 unsigned MyMaxNest = MaxNest;
470 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
471 MyNestLevel, MyMaxNest, TII))
472 if (!Best || (MyMaxNest > BestMaxNest)) {
474 BestMaxNest = MyMaxNest;
478 MaxNest = BestMaxNest;
481 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
482 if (N->isMachineOpcode()) {
483 if (N->getMachineOpcode() ==
484 (unsigned)TII->getCallFrameDestroyOpcode()) {
486 MaxNest = std::max(MaxNest, NestLevel);
487 } else if (N->getMachineOpcode() ==
488 (unsigned)TII->getCallFrameSetupOpcode()) {
489 assert(NestLevel != 0);
495 // Otherwise, find the chain and continue climbing.
496 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
497 if (N->getOperand(i).getValueType() == MVT::Other) {
498 N = N->getOperand(i).getNode();
499 goto found_chain_operand;
502 found_chain_operand:;
503 if (N->getOpcode() == ISD::EntryToken)
508 /// Call ReleasePred for each predecessor, then update register live def/gen.
509 /// Always update LiveRegDefs for a register dependence even if the current SU
510 /// also defines the register. This effectively create one large live range
511 /// across a sequence of two-address node. This is important because the
512 /// entire chain must be scheduled together. Example:
515 /// flags = (2) addc flags
516 /// flags = (1) addc flags
520 /// LiveRegDefs[flags] = 3
521 /// LiveRegGens[flags] = 1
523 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
524 /// interference on flags.
525 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
526 // Bottom up: release predecessors
527 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
529 ReleasePred(SU, &*I);
530 if (I->isAssignedRegDep()) {
531 // This is a physical register dependency and it's impossible or
532 // expensive to copy the register. Make sure nothing that can
533 // clobber the register is scheduled between the predecessor and
535 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
536 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
537 "interference on register dependence");
538 LiveRegDefs[I->getReg()] = I->getSUnit();
539 if (!LiveRegGens[I->getReg()]) {
541 LiveRegGens[I->getReg()] = SU;
546 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
547 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
548 // these nodes, to prevent other calls from being interscheduled with them.
549 unsigned CallResource = TRI->getNumRegs();
550 if (!LiveRegDefs[CallResource])
551 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
552 if (Node->isMachineOpcode() &&
553 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
554 unsigned NestLevel = 0;
555 unsigned MaxNest = 0;
556 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
558 SUnit *Def = &SUnits[N->getNodeId()];
559 CallSeqEndForStart[Def] = SU;
562 LiveRegDefs[CallResource] = Def;
563 LiveRegGens[CallResource] = SU;
568 /// Check to see if any of the pending instructions are ready to issue. If
569 /// so, add them to the available queue.
570 void ScheduleDAGRRList::ReleasePending() {
571 if (DisableSchedCycles) {
572 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
576 // If the available queue is empty, it is safe to reset MinAvailableCycle.
577 if (AvailableQueue->empty())
578 MinAvailableCycle = UINT_MAX;
580 // Check to see if any of the pending instructions are ready to issue. If
581 // so, add them to the available queue.
582 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
583 unsigned ReadyCycle = PendingQueue[i]->getHeight();
584 if (ReadyCycle < MinAvailableCycle)
585 MinAvailableCycle = ReadyCycle;
587 if (PendingQueue[i]->isAvailable) {
588 if (!isReady(PendingQueue[i]))
590 AvailableQueue->push(PendingQueue[i]);
592 PendingQueue[i]->isPending = false;
593 PendingQueue[i] = PendingQueue.back();
594 PendingQueue.pop_back();
599 /// Move the scheduler state forward by the specified number of Cycles.
600 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
601 if (NextCycle <= CurCycle)
605 AvailableQueue->setCurCycle(NextCycle);
606 if (!HazardRec->isEnabled()) {
607 // Bypass lots of virtual calls in case of long latency.
608 CurCycle = NextCycle;
611 for (; CurCycle != NextCycle; ++CurCycle) {
612 HazardRec->RecedeCycle();
615 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
616 // available Q to release pending nodes at least once before popping.
620 /// Move the scheduler state forward until the specified node's dependents are
621 /// ready and can be scheduled with no resource conflicts.
622 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
623 if (DisableSchedCycles)
626 // FIXME: Nodes such as CopyFromReg probably should not advance the current
627 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
628 // has predecessors the cycle will be advanced when they are scheduled.
629 // But given the crude nature of modeling latency though such nodes, we
630 // currently need to treat these nodes like real instructions.
631 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
633 unsigned ReadyCycle = SU->getHeight();
635 // Bump CurCycle to account for latency. We assume the latency of other
636 // available instructions may be hidden by the stall (not a full pipe stall).
637 // This updates the hazard recognizer's cycle before reserving resources for
639 AdvanceToCycle(ReadyCycle);
641 // Calls are scheduled in their preceding cycle, so don't conflict with
642 // hazards from instructions after the call. EmitNode will reset the
643 // scoreboard state before emitting the call.
647 // FIXME: For resource conflicts in very long non-pipelined stages, we
648 // should probably skip ahead here to avoid useless scoreboard checks.
651 ScheduleHazardRecognizer::HazardType HT =
652 HazardRec->getHazardType(SU, -Stalls);
654 if (HT == ScheduleHazardRecognizer::NoHazard)
659 AdvanceToCycle(CurCycle + Stalls);
662 /// Record this SUnit in the HazardRecognizer.
663 /// Does not update CurCycle.
664 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
665 if (!HazardRec->isEnabled())
668 // Check for phys reg copy.
672 switch (SU->getNode()->getOpcode()) {
674 assert(SU->getNode()->isMachineOpcode() &&
675 "This target-independent node should not be scheduled.");
677 case ISD::MERGE_VALUES:
678 case ISD::TokenFactor:
679 case ISD::LIFETIME_START:
680 case ISD::LIFETIME_END:
682 case ISD::CopyFromReg:
684 // Noops don't affect the scoreboard state. Copies are likely to be
688 // For inline asm, clear the pipeline state.
693 // Calls are scheduled with their preceding instructions. For bottom-up
694 // scheduling, clear the pipeline state before emitting.
698 HazardRec->EmitInstruction(SU);
701 static void resetVRegCycle(SUnit *SU);
703 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
704 /// count of its predecessors. If a predecessor pending count is zero, add it to
705 /// the Available queue.
706 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
707 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
708 DEBUG(SU->dump(this));
711 if (CurCycle < SU->getHeight())
712 DEBUG(dbgs() << " Height [" << SU->getHeight()
713 << "] pipeline stall!\n");
716 // FIXME: Do not modify node height. It may interfere with
717 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
718 // node its ready cycle can aid heuristics, and after scheduling it can
719 // indicate the scheduled cycle.
720 SU->setHeightToAtLeast(CurCycle);
722 // Reserve resources for the scheduled instruction.
725 Sequence.push_back(SU);
727 AvailableQueue->scheduledNode(SU);
729 // If HazardRec is disabled, and each inst counts as one cycle, then
730 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
731 // PendingQueue for schedulers that implement HasReadyFilter.
732 if (!HazardRec->isEnabled() && AvgIPC < 2)
733 AdvanceToCycle(CurCycle + 1);
735 // Update liveness of predecessors before successors to avoid treating a
736 // two-address node as a live range def.
737 ReleasePredecessors(SU);
739 // Release all the implicit physical register defs that are live.
740 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
742 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
743 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
744 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
746 LiveRegDefs[I->getReg()] = nullptr;
747 LiveRegGens[I->getReg()] = nullptr;
748 releaseInterferences(I->getReg());
751 // Release the special call resource dependence, if this is the beginning
753 unsigned CallResource = TRI->getNumRegs();
754 if (LiveRegDefs[CallResource] == SU)
755 for (const SDNode *SUNode = SU->getNode(); SUNode;
756 SUNode = SUNode->getGluedNode()) {
757 if (SUNode->isMachineOpcode() &&
758 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
759 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
761 LiveRegDefs[CallResource] = nullptr;
762 LiveRegGens[CallResource] = nullptr;
763 releaseInterferences(CallResource);
769 SU->isScheduled = true;
771 // Conditions under which the scheduler should eagerly advance the cycle:
772 // (1) No available instructions
773 // (2) All pipelines full, so available instructions must have hazards.
775 // If HazardRec is disabled, the cycle was pre-advanced before calling
776 // ReleasePredecessors. In that case, IssueCount should remain 0.
778 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
779 if (HazardRec->isEnabled() || AvgIPC > 1) {
780 if (SU->getNode() && SU->getNode()->isMachineOpcode())
782 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
783 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
784 AdvanceToCycle(CurCycle + 1);
788 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
789 /// unscheduled, incrcease the succ left count of its predecessors. Remove
790 /// them from AvailableQueue if necessary.
791 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
792 SUnit *PredSU = PredEdge->getSUnit();
793 if (PredSU->isAvailable) {
794 PredSU->isAvailable = false;
795 if (!PredSU->isPending)
796 AvailableQueue->remove(PredSU);
799 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
800 ++PredSU->NumSuccsLeft;
803 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
804 /// its predecessor states to reflect the change.
805 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
806 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
807 DEBUG(SU->dump(this));
809 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
812 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
813 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
814 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
815 "Physical register dependency violated?");
817 LiveRegDefs[I->getReg()] = nullptr;
818 LiveRegGens[I->getReg()] = nullptr;
819 releaseInterferences(I->getReg());
823 // Reclaim the special call resource dependence, if this is the beginning
825 unsigned CallResource = TRI->getNumRegs();
826 for (const SDNode *SUNode = SU->getNode(); SUNode;
827 SUNode = SUNode->getGluedNode()) {
828 if (SUNode->isMachineOpcode() &&
829 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
831 LiveRegDefs[CallResource] = SU;
832 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
836 // Release the special call resource dependence, if this is the end
838 if (LiveRegGens[CallResource] == SU)
839 for (const SDNode *SUNode = SU->getNode(); SUNode;
840 SUNode = SUNode->getGluedNode()) {
841 if (SUNode->isMachineOpcode() &&
842 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
843 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
845 LiveRegDefs[CallResource] = nullptr;
846 LiveRegGens[CallResource] = nullptr;
847 releaseInterferences(CallResource);
851 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
853 if (I->isAssignedRegDep()) {
854 if (!LiveRegDefs[I->getReg()])
856 // This becomes the nearest def. Note that an earlier def may still be
857 // pending if this is a two-address node.
858 LiveRegDefs[I->getReg()] = SU;
859 if (LiveRegGens[I->getReg()] == nullptr ||
860 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
861 LiveRegGens[I->getReg()] = I->getSUnit();
864 if (SU->getHeight() < MinAvailableCycle)
865 MinAvailableCycle = SU->getHeight();
867 SU->setHeightDirty();
868 SU->isScheduled = false;
869 SU->isAvailable = true;
870 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
871 // Don't make available until backtracking is complete.
872 SU->isPending = true;
873 PendingQueue.push_back(SU);
876 AvailableQueue->push(SU);
878 AvailableQueue->unscheduledNode(SU);
881 /// After backtracking, the hazard checker needs to be restored to a state
882 /// corresponding the current cycle.
883 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
886 unsigned LookAhead = std::min((unsigned)Sequence.size(),
887 HazardRec->getMaxLookAhead());
891 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
892 unsigned HazardCycle = (*I)->getHeight();
893 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
895 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
896 HazardRec->RecedeCycle();
902 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
903 /// BTCycle in order to schedule a specific node.
904 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
905 SUnit *OldSU = Sequence.back();
908 // FIXME: use ready cycle instead of height
909 CurCycle = OldSU->getHeight();
910 UnscheduleNodeBottomUp(OldSU);
911 AvailableQueue->setCurCycle(CurCycle);
914 OldSU = Sequence.back();
917 assert(!SU->isSucc(OldSU) && "Something is wrong!");
919 RestoreHazardCheckerBottomUp();
926 static bool isOperandOf(const SUnit *SU, SDNode *N) {
927 for (const SDNode *SUNode = SU->getNode(); SUNode;
928 SUNode = SUNode->getGluedNode()) {
929 if (SUNode->isOperandOf(N))
935 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
936 /// successors to the newly created node.
937 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
938 SDNode *N = SU->getNode();
942 if (SU->getNode()->getGluedNode())
946 bool TryUnfold = false;
947 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
948 MVT VT = N->getSimpleValueType(i);
951 else if (VT == MVT::Other)
954 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
955 const SDValue &Op = N->getOperand(i);
956 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
962 SmallVector<SDNode*, 2> NewNodes;
963 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
966 // unfolding an x86 DEC64m operation results in store, dec, load which
967 // can't be handled here so quit
968 if (NewNodes.size() == 3)
971 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
972 assert(NewNodes.size() == 2 && "Expected a load folding node!");
975 SDNode *LoadNode = NewNodes[0];
976 unsigned NumVals = N->getNumValues();
977 unsigned OldNumVals = SU->getNode()->getNumValues();
978 for (unsigned i = 0; i != NumVals; ++i)
979 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
980 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
981 SDValue(LoadNode, 1));
983 // LoadNode may already exist. This can happen when there is another
984 // load from the same location and producing the same type of value
985 // but it has different alignment or volatileness.
986 bool isNewLoad = true;
988 if (LoadNode->getNodeId() != -1) {
989 LoadSU = &SUnits[LoadNode->getNodeId()];
992 LoadSU = CreateNewSUnit(LoadNode);
993 LoadNode->setNodeId(LoadSU->NodeNum);
995 InitNumRegDefsLeft(LoadSU);
996 computeLatency(LoadSU);
999 SUnit *NewSU = CreateNewSUnit(N);
1000 assert(N->getNodeId() == -1 && "Node already inserted!");
1001 N->setNodeId(NewSU->NodeNum);
1003 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1004 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1005 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
1006 NewSU->isTwoAddress = true;
1010 if (MCID.isCommutable())
1011 NewSU->isCommutable = true;
1013 InitNumRegDefsLeft(NewSU);
1014 computeLatency(NewSU);
1016 // Record all the edges to and from the old SU, by category.
1017 SmallVector<SDep, 4> ChainPreds;
1018 SmallVector<SDep, 4> ChainSuccs;
1019 SmallVector<SDep, 4> LoadPreds;
1020 SmallVector<SDep, 4> NodePreds;
1021 SmallVector<SDep, 4> NodeSuccs;
1022 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1025 ChainPreds.push_back(*I);
1026 else if (isOperandOf(I->getSUnit(), LoadNode))
1027 LoadPreds.push_back(*I);
1029 NodePreds.push_back(*I);
1031 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1034 ChainSuccs.push_back(*I);
1036 NodeSuccs.push_back(*I);
1039 // Now assign edges to the newly-created nodes.
1040 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1041 const SDep &Pred = ChainPreds[i];
1042 RemovePred(SU, Pred);
1044 AddPred(LoadSU, Pred);
1046 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
1047 const SDep &Pred = LoadPreds[i];
1048 RemovePred(SU, Pred);
1050 AddPred(LoadSU, Pred);
1052 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
1053 const SDep &Pred = NodePreds[i];
1054 RemovePred(SU, Pred);
1055 AddPred(NewSU, Pred);
1057 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
1058 SDep D = NodeSuccs[i];
1059 SUnit *SuccDep = D.getSUnit();
1061 RemovePred(SuccDep, D);
1063 AddPred(SuccDep, D);
1064 // Balance register pressure.
1065 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1066 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1067 --NewSU->NumRegDefsLeft;
1069 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
1070 SDep D = ChainSuccs[i];
1071 SUnit *SuccDep = D.getSUnit();
1073 RemovePred(SuccDep, D);
1076 AddPred(SuccDep, D);
1080 // Add a data dependency to reflect that NewSU reads the value defined
1082 SDep D(LoadSU, SDep::Data, 0);
1083 D.setLatency(LoadSU->Latency);
1087 AvailableQueue->addNode(LoadSU);
1088 AvailableQueue->addNode(NewSU);
1092 if (NewSU->NumSuccsLeft == 0) {
1093 NewSU->isAvailable = true;
1099 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
1100 NewSU = CreateClone(SU);
1102 // New SUnit has the exact same predecessors.
1103 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1105 if (!I->isArtificial())
1108 // Only copy scheduled successors. Cut them from old node's successor
1109 // list and move them over.
1110 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1111 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1113 if (I->isArtificial())
1115 SUnit *SuccSU = I->getSUnit();
1116 if (SuccSU->isScheduled) {
1121 DelDeps.push_back(std::make_pair(SuccSU, D));
1124 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1125 RemovePred(DelDeps[i].first, DelDeps[i].second);
1127 AvailableQueue->updateNode(SU);
1128 AvailableQueue->addNode(NewSU);
1134 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1135 /// scheduled successors of the given SUnit to the last copy.
1136 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1137 const TargetRegisterClass *DestRC,
1138 const TargetRegisterClass *SrcRC,
1139 SmallVectorImpl<SUnit*> &Copies) {
1140 SUnit *CopyFromSU = CreateNewSUnit(nullptr);
1141 CopyFromSU->CopySrcRC = SrcRC;
1142 CopyFromSU->CopyDstRC = DestRC;
1144 SUnit *CopyToSU = CreateNewSUnit(nullptr);
1145 CopyToSU->CopySrcRC = DestRC;
1146 CopyToSU->CopyDstRC = SrcRC;
1148 // Only copy scheduled successors. Cut them from old node's successor
1149 // list and move them over.
1150 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1151 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1153 if (I->isArtificial())
1155 SUnit *SuccSU = I->getSUnit();
1156 if (SuccSU->isScheduled) {
1158 D.setSUnit(CopyToSU);
1160 DelDeps.push_back(std::make_pair(SuccSU, *I));
1163 // Avoid scheduling the def-side copy before other successors. Otherwise
1164 // we could introduce another physreg interference on the copy and
1165 // continue inserting copies indefinitely.
1166 AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
1169 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1170 RemovePred(DelDeps[i].first, DelDeps[i].second);
1172 SDep FromDep(SU, SDep::Data, Reg);
1173 FromDep.setLatency(SU->Latency);
1174 AddPred(CopyFromSU, FromDep);
1175 SDep ToDep(CopyFromSU, SDep::Data, 0);
1176 ToDep.setLatency(CopyFromSU->Latency);
1177 AddPred(CopyToSU, ToDep);
1179 AvailableQueue->updateNode(SU);
1180 AvailableQueue->addNode(CopyFromSU);
1181 AvailableQueue->addNode(CopyToSU);
1182 Copies.push_back(CopyFromSU);
1183 Copies.push_back(CopyToSU);
1188 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1189 /// definition of the specified node.
1190 /// FIXME: Move to SelectionDAG?
1191 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1192 const TargetInstrInfo *TII) {
1194 if (N->getOpcode() == ISD::CopyFromReg) {
1195 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1200 NumRes = MCID.getNumDefs();
1201 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1207 return N->getSimpleValueType(NumRes);
1210 /// CheckForLiveRegDef - Return true and update live register vector if the
1211 /// specified register def of the specified SUnit clobbers any "live" registers.
1212 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1213 std::vector<SUnit*> &LiveRegDefs,
1214 SmallSet<unsigned, 4> &RegAdded,
1215 SmallVectorImpl<unsigned> &LRegs,
1216 const TargetRegisterInfo *TRI) {
1217 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
1219 // Check if Ref is live.
1220 if (!LiveRegDefs[*AliasI]) continue;
1222 // Allow multiple uses of the same def.
1223 if (LiveRegDefs[*AliasI] == SU) continue;
1225 // Add Reg to the set of interfering live regs.
1226 if (RegAdded.insert(*AliasI)) {
1227 LRegs.push_back(*AliasI);
1232 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1233 /// by RegMask, and add them to LRegs.
1234 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1235 std::vector<SUnit*> &LiveRegDefs,
1236 SmallSet<unsigned, 4> &RegAdded,
1237 SmallVectorImpl<unsigned> &LRegs) {
1238 // Look at all live registers. Skip Reg0 and the special CallResource.
1239 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1240 if (!LiveRegDefs[i]) continue;
1241 if (LiveRegDefs[i] == SU) continue;
1242 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1243 if (RegAdded.insert(i))
1248 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1249 static const uint32_t *getNodeRegMask(const SDNode *N) {
1250 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1251 if (const RegisterMaskSDNode *Op =
1252 dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1253 return Op->getRegMask();
1257 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1258 /// scheduling of the given node to satisfy live physical register dependencies.
1259 /// If the specific node is the last one that's available to schedule, do
1260 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1261 bool ScheduleDAGRRList::
1262 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
1263 if (NumLiveRegs == 0)
1266 SmallSet<unsigned, 4> RegAdded;
1267 // If this node would clobber any "live" register, then it's not ready.
1269 // If SU is the currently live definition of the same register that it uses,
1270 // then we are free to schedule it.
1271 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1273 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1274 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1275 RegAdded, LRegs, TRI);
1278 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1279 if (Node->getOpcode() == ISD::INLINEASM) {
1280 // Inline asm can clobber physical defs.
1281 unsigned NumOps = Node->getNumOperands();
1282 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1283 --NumOps; // Ignore the glue operand.
1285 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1287 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1288 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1290 ++i; // Skip the ID value.
1291 if (InlineAsm::isRegDefKind(Flags) ||
1292 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1293 InlineAsm::isClobberKind(Flags)) {
1294 // Check for def of register or earlyclobber register.
1295 for (; NumVals; --NumVals, ++i) {
1296 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1297 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1298 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1306 if (!Node->isMachineOpcode())
1308 // If we're in the middle of scheduling a call, don't begin scheduling
1309 // another call. Also, don't allow any physical registers to be live across
1311 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1312 // Check the special calling-sequence resource.
1313 unsigned CallResource = TRI->getNumRegs();
1314 if (LiveRegDefs[CallResource]) {
1315 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1316 while (SDNode *Glued = Gen->getGluedNode())
1318 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1319 LRegs.push_back(CallResource);
1322 if (const uint32_t *RegMask = getNodeRegMask(Node))
1323 CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1325 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1326 if (!MCID.ImplicitDefs)
1328 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1329 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1332 return !LRegs.empty();
1335 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1336 // Add the nodes that aren't ready back onto the available list.
1337 for (unsigned i = Interferences.size(); i > 0; --i) {
1338 SUnit *SU = Interferences[i-1];
1339 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1341 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
1342 if (std::find(LRegs.begin(), LRegs.end(), Reg) == LRegs.end())
1345 SU->isPending = false;
1346 // The interfering node may no longer be available due to backtracking.
1347 // Furthermore, it may have been made available again, in which case it is
1348 // now already in the AvailableQueue.
1349 if (SU->isAvailable && !SU->NodeQueueId) {
1350 DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
1351 AvailableQueue->push(SU);
1353 if (i < Interferences.size())
1354 Interferences[i-1] = Interferences.back();
1355 Interferences.pop_back();
1356 LRegsMap.erase(LRegsPos);
1360 /// Return a node that can be scheduled in this cycle. Requirements:
1361 /// (1) Ready: latency has been satisfied
1362 /// (2) No Hazards: resources are available
1363 /// (3) No Interferences: may unschedule to break register interferences.
1364 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1365 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
1367 SmallVector<unsigned, 4> LRegs;
1368 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1370 DEBUG(dbgs() << " Interfering reg " <<
1371 (LRegs[0] == TRI->getNumRegs() ? "CallResource"
1372 : TRI->getName(LRegs[0]))
1373 << " SU #" << CurSU->NodeNum << '\n');
1374 std::pair<LRegsMapT::iterator, bool> LRegsPair =
1375 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1376 if (LRegsPair.second) {
1377 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1378 Interferences.push_back(CurSU);
1381 assert(CurSU->isPending && "Interferences are pending");
1382 // Update the interference with current live regs.
1383 LRegsPair.first->second = LRegs;
1385 CurSU = AvailableQueue->pop();
1390 // All candidates are delayed due to live physical reg dependencies.
1391 // Try backtracking, code duplication, or inserting cross class copies
1393 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1394 SUnit *TrySU = Interferences[i];
1395 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1397 // Try unscheduling up to the point where it's safe to schedule
1399 SUnit *BtSU = nullptr;
1400 unsigned LiveCycle = UINT_MAX;
1401 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1402 unsigned Reg = LRegs[j];
1403 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1404 BtSU = LiveRegGens[Reg];
1405 LiveCycle = BtSU->getHeight();
1408 if (!WillCreateCycle(TrySU, BtSU)) {
1409 // BacktrackBottomUp mutates Interferences!
1410 BacktrackBottomUp(TrySU, BtSU);
1412 // Force the current node to be scheduled before the node that
1413 // requires the physical reg dep.
1414 if (BtSU->isAvailable) {
1415 BtSU->isAvailable = false;
1416 if (!BtSU->isPending)
1417 AvailableQueue->remove(BtSU);
1419 DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
1420 << TrySU->NodeNum << ")\n");
1421 AddPred(TrySU, SDep(BtSU, SDep::Artificial));
1423 // If one or more successors has been unscheduled, then the current
1424 // node is no longer available.
1425 if (!TrySU->isAvailable)
1426 CurSU = AvailableQueue->pop();
1428 AvailableQueue->remove(TrySU);
1431 // Interferences has been mutated. We must break.
1437 // Can't backtrack. If it's too expensive to copy the value, then try
1438 // duplicate the nodes that produces these "too expensive to copy"
1439 // values to break the dependency. In case even that doesn't work,
1440 // insert cross class copies.
1441 // If it's not too expensive, i.e. cost != -1, issue copies.
1442 SUnit *TrySU = Interferences[0];
1443 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1444 assert(LRegs.size() == 1 && "Can't handle this yet!");
1445 unsigned Reg = LRegs[0];
1446 SUnit *LRDef = LiveRegDefs[Reg];
1447 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1448 const TargetRegisterClass *RC =
1449 TRI->getMinimalPhysRegClass(Reg, VT);
1450 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1452 // If cross copy register class is the same as RC, then it must be possible
1453 // copy the value directly. Do not try duplicate the def.
1454 // If cross copy register class is not the same as RC, then it's possible to
1455 // copy the value but it require cross register class copies and it is
1457 // If cross copy register class is null, then it's not possible to copy
1458 // the value at all.
1459 SUnit *NewDef = nullptr;
1461 NewDef = CopyAndMoveSuccessors(LRDef);
1462 if (!DestRC && !NewDef)
1463 report_fatal_error("Can't handle live physical register dependency!");
1466 // Issue copies, these can be expensive cross register class copies.
1467 SmallVector<SUnit*, 2> Copies;
1468 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1469 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1470 << " to SU #" << Copies.front()->NodeNum << "\n");
1471 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
1472 NewDef = Copies.back();
1475 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1476 << " to SU #" << TrySU->NodeNum << "\n");
1477 LiveRegDefs[Reg] = NewDef;
1478 AddPred(NewDef, SDep(TrySU, SDep::Artificial));
1479 TrySU->isAvailable = false;
1482 assert(CurSU && "Unable to resolve live physical register dependencies!");
1486 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1488 void ScheduleDAGRRList::ListScheduleBottomUp() {
1489 // Release any predecessors of the special Exit node.
1490 ReleasePredecessors(&ExitSU);
1492 // Add root to Available queue.
1493 if (!SUnits.empty()) {
1494 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1495 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1496 RootSU->isAvailable = true;
1497 AvailableQueue->push(RootSU);
1500 // While Available queue is not empty, grab the node with the highest
1501 // priority. If it is not ready put it back. Schedule the node.
1502 Sequence.reserve(SUnits.size());
1503 while (!AvailableQueue->empty() || !Interferences.empty()) {
1504 DEBUG(dbgs() << "\nExamining Available:\n";
1505 AvailableQueue->dump(this));
1507 // Pick the best node to schedule taking all constraints into
1509 SUnit *SU = PickNodeToScheduleBottomUp();
1511 AdvancePastStalls(SU);
1513 ScheduleNodeBottomUp(SU);
1515 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1516 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1517 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1518 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1522 // Reverse the order if it is bottom up.
1523 std::reverse(Sequence.begin(), Sequence.end());
1526 VerifyScheduledSequence(/*isBottomUp=*/true);
1530 //===----------------------------------------------------------------------===//
1531 // RegReductionPriorityQueue Definition
1532 //===----------------------------------------------------------------------===//
1534 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1535 // to reduce register pressure.
1538 class RegReductionPQBase;
1540 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1541 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1546 struct reverse_sort : public queue_sort {
1548 reverse_sort(SF &sf) : SortFunc(sf) {}
1550 bool operator()(SUnit* left, SUnit* right) const {
1551 // reverse left/right rather than simply !SortFunc(left, right)
1552 // to expose different paths in the comparison logic.
1553 return SortFunc(right, left);
1558 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1559 // reduction scheduler.
1560 struct bu_ls_rr_sort : public queue_sort {
1563 HasReadyFilter = false
1566 RegReductionPQBase *SPQ;
1567 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1569 bool operator()(SUnit* left, SUnit* right) const;
1572 // src_ls_rr_sort - Priority function for source order scheduler.
1573 struct src_ls_rr_sort : public queue_sort {
1576 HasReadyFilter = false
1579 RegReductionPQBase *SPQ;
1580 src_ls_rr_sort(RegReductionPQBase *spq)
1583 bool operator()(SUnit* left, SUnit* right) const;
1586 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1587 struct hybrid_ls_rr_sort : public queue_sort {
1590 HasReadyFilter = false
1593 RegReductionPQBase *SPQ;
1594 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1597 bool isReady(SUnit *SU, unsigned CurCycle) const;
1599 bool operator()(SUnit* left, SUnit* right) const;
1602 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1604 struct ilp_ls_rr_sort : public queue_sort {
1607 HasReadyFilter = false
1610 RegReductionPQBase *SPQ;
1611 ilp_ls_rr_sort(RegReductionPQBase *spq)
1614 bool isReady(SUnit *SU, unsigned CurCycle) const;
1616 bool operator()(SUnit* left, SUnit* right) const;
1619 class RegReductionPQBase : public SchedulingPriorityQueue {
1621 std::vector<SUnit*> Queue;
1622 unsigned CurQueueId;
1623 bool TracksRegPressure;
1626 // SUnits - The SUnits for the current graph.
1627 std::vector<SUnit> *SUnits;
1629 MachineFunction &MF;
1630 const TargetInstrInfo *TII;
1631 const TargetRegisterInfo *TRI;
1632 const TargetLowering *TLI;
1633 ScheduleDAGRRList *scheduleDAG;
1635 // SethiUllmanNumbers - The SethiUllman number for each node.
1636 std::vector<unsigned> SethiUllmanNumbers;
1638 /// RegPressure - Tracking current reg pressure per register class.
1640 std::vector<unsigned> RegPressure;
1642 /// RegLimit - Tracking the number of allocatable registers per register
1644 std::vector<unsigned> RegLimit;
1647 RegReductionPQBase(MachineFunction &mf,
1648 bool hasReadyFilter,
1651 const TargetInstrInfo *tii,
1652 const TargetRegisterInfo *tri,
1653 const TargetLowering *tli)
1654 : SchedulingPriorityQueue(hasReadyFilter),
1655 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
1656 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
1657 if (TracksRegPressure) {
1658 unsigned NumRC = TRI->getNumRegClasses();
1659 RegLimit.resize(NumRC);
1660 RegPressure.resize(NumRC);
1661 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1662 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1663 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1664 E = TRI->regclass_end(); I != E; ++I)
1665 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1669 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1670 scheduleDAG = scheduleDag;
1673 ScheduleHazardRecognizer* getHazardRec() {
1674 return scheduleDAG->getHazardRec();
1677 void initNodes(std::vector<SUnit> &sunits) override;
1679 void addNode(const SUnit *SU) override;
1681 void updateNode(const SUnit *SU) override;
1683 void releaseState() override {
1685 SethiUllmanNumbers.clear();
1686 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1689 unsigned getNodePriority(const SUnit *SU) const;
1691 unsigned getNodeOrdering(const SUnit *SU) const {
1692 if (!SU->getNode()) return 0;
1694 return SU->getNode()->getIROrder();
1697 bool empty() const override { return Queue.empty(); }
1699 void push(SUnit *U) override {
1700 assert(!U->NodeQueueId && "Node in the queue already");
1701 U->NodeQueueId = ++CurQueueId;
1705 void remove(SUnit *SU) override {
1706 assert(!Queue.empty() && "Queue is empty!");
1707 assert(SU->NodeQueueId != 0 && "Not in queue!");
1708 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1710 if (I != std::prev(Queue.end()))
1711 std::swap(*I, Queue.back());
1713 SU->NodeQueueId = 0;
1716 bool tracksRegPressure() const override { return TracksRegPressure; }
1718 void dumpRegPressure() const;
1720 bool HighRegPressure(const SUnit *SU) const;
1722 bool MayReduceRegPressure(SUnit *SU) const;
1724 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1726 void scheduledNode(SUnit *SU) override;
1728 void unscheduledNode(SUnit *SU) override;
1731 bool canClobber(const SUnit *SU, const SUnit *Op);
1732 void AddPseudoTwoAddrDeps();
1733 void PrescheduleNodesWithMultipleUses();
1734 void CalculateSethiUllmanNumbers();
1738 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1739 std::vector<SUnit *>::iterator Best = Q.begin();
1740 for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
1741 E = Q.end(); I != E; ++I)
1742 if (Picker(*Best, *I))
1745 if (Best != std::prev(Q.end()))
1746 std::swap(*Best, Q.back());
1752 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1754 if (DAG->StressSched) {
1755 reverse_sort<SF> RPicker(Picker);
1756 return popFromQueueImpl(Q, RPicker);
1760 return popFromQueueImpl(Q, Picker);
1764 class RegReductionPriorityQueue : public RegReductionPQBase {
1768 RegReductionPriorityQueue(MachineFunction &mf,
1771 const TargetInstrInfo *tii,
1772 const TargetRegisterInfo *tri,
1773 const TargetLowering *tli)
1774 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1778 bool isBottomUp() const override { return SF::IsBottomUp; }
1780 bool isReady(SUnit *U) const override {
1781 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1784 SUnit *pop() override {
1785 if (Queue.empty()) return nullptr;
1787 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1792 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1793 void dump(ScheduleDAG *DAG) const override {
1794 // Emulate pop() without clobbering NodeQueueIds.
1795 std::vector<SUnit*> DumpQueue = Queue;
1796 SF DumpPicker = Picker;
1797 while (!DumpQueue.empty()) {
1798 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1799 dbgs() << "Height " << SU->getHeight() << ": ";
1806 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1807 BURegReductionPriorityQueue;
1809 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1810 SrcRegReductionPriorityQueue;
1812 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1813 HybridBURRPriorityQueue;
1815 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1816 ILPBURRPriorityQueue;
1817 } // end anonymous namespace
1819 //===----------------------------------------------------------------------===//
1820 // Static Node Priority for Register Pressure Reduction
1821 //===----------------------------------------------------------------------===//
1823 // Check for special nodes that bypass scheduling heuristics.
1824 // Currently this pushes TokenFactor nodes down, but may be used for other
1825 // pseudo-ops as well.
1827 // Return -1 to schedule right above left, 1 for left above right.
1828 // Return 0 if no bias exists.
1829 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1830 bool LSchedLow = left->isScheduleLow;
1831 bool RSchedLow = right->isScheduleLow;
1832 if (LSchedLow != RSchedLow)
1833 return LSchedLow < RSchedLow ? 1 : -1;
1837 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1838 /// Smaller number is the higher priority.
1840 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1841 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1842 if (SethiUllmanNumber != 0)
1843 return SethiUllmanNumber;
1846 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1848 if (I->isCtrl()) continue; // ignore chain preds
1849 SUnit *PredSU = I->getSUnit();
1850 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1851 if (PredSethiUllman > SethiUllmanNumber) {
1852 SethiUllmanNumber = PredSethiUllman;
1854 } else if (PredSethiUllman == SethiUllmanNumber)
1858 SethiUllmanNumber += Extra;
1860 if (SethiUllmanNumber == 0)
1861 SethiUllmanNumber = 1;
1863 return SethiUllmanNumber;
1866 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1867 /// scheduling units.
1868 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1869 SethiUllmanNumbers.assign(SUnits->size(), 0);
1871 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1872 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1875 void RegReductionPQBase::addNode(const SUnit *SU) {
1876 unsigned SUSize = SethiUllmanNumbers.size();
1877 if (SUnits->size() > SUSize)
1878 SethiUllmanNumbers.resize(SUSize*2, 0);
1879 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1882 void RegReductionPQBase::updateNode(const SUnit *SU) {
1883 SethiUllmanNumbers[SU->NodeNum] = 0;
1884 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1887 // Lower priority means schedule further down. For bottom-up scheduling, lower
1888 // priority SUs are scheduled before higher priority SUs.
1889 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1890 assert(SU->NodeNum < SethiUllmanNumbers.size());
1891 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1892 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1893 // CopyToReg should be close to its uses to facilitate coalescing and
1896 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1897 Opc == TargetOpcode::SUBREG_TO_REG ||
1898 Opc == TargetOpcode::INSERT_SUBREG)
1899 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1900 // close to their uses to facilitate coalescing.
1902 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1903 // If SU does not have a register use, i.e. it doesn't produce a value
1904 // that would be consumed (e.g. store), then it terminates a chain of
1905 // computation. Give it a large SethiUllman number so it will be
1906 // scheduled right before its predecessors that it doesn't lengthen
1907 // their live ranges.
1909 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1910 // If SU does not have a register def, schedule it close to its uses
1911 // because it does not lengthen any live ranges.
1914 return SethiUllmanNumbers[SU->NodeNum];
1916 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1918 // FIXME: This assumes all of the defs are used as call operands.
1919 int NP = (int)Priority - SU->getNode()->getNumValues();
1920 return (NP > 0) ? NP : 0;
1926 //===----------------------------------------------------------------------===//
1927 // Register Pressure Tracking
1928 //===----------------------------------------------------------------------===//
1930 void RegReductionPQBase::dumpRegPressure() const {
1931 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1932 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1933 E = TRI->regclass_end(); I != E; ++I) {
1934 const TargetRegisterClass *RC = *I;
1935 unsigned Id = RC->getID();
1936 unsigned RP = RegPressure[Id];
1938 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1944 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1948 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1952 SUnit *PredSU = I->getSUnit();
1953 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1954 // to cover the number of registers defined (they are all live).
1955 if (PredSU->NumRegDefsLeft == 0) {
1958 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1959 RegDefPos.IsValid(); RegDefPos.Advance()) {
1960 unsigned RCId, Cost;
1961 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
1963 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1970 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1971 const SDNode *N = SU->getNode();
1973 if (!N->isMachineOpcode() || !SU->NumSuccs)
1976 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1977 for (unsigned i = 0; i != NumDefs; ++i) {
1978 MVT VT = N->getSimpleValueType(i);
1979 if (!N->hasAnyUseOfValue(i))
1981 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1982 if (RegPressure[RCId] >= RegLimit[RCId])
1988 // Compute the register pressure contribution by this instruction by count up
1989 // for uses that are not live and down for defs. Only count register classes
1990 // that are already under high pressure. As a side effect, compute the number of
1991 // uses of registers that are already live.
1993 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1994 // so could probably be factored.
1995 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1998 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2002 SUnit *PredSU = I->getSUnit();
2003 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2004 // to cover the number of registers defined (they are all live).
2005 if (PredSU->NumRegDefsLeft == 0) {
2006 if (PredSU->getNode()->isMachineOpcode())
2010 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2011 RegDefPos.IsValid(); RegDefPos.Advance()) {
2012 MVT VT = RegDefPos.GetValue();
2013 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2014 if (RegPressure[RCId] >= RegLimit[RCId])
2018 const SDNode *N = SU->getNode();
2020 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
2023 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2024 for (unsigned i = 0; i != NumDefs; ++i) {
2025 MVT VT = N->getSimpleValueType(i);
2026 if (!N->hasAnyUseOfValue(i))
2028 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2029 if (RegPressure[RCId] >= RegLimit[RCId])
2035 void RegReductionPQBase::scheduledNode(SUnit *SU) {
2036 if (!TracksRegPressure)
2042 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2046 SUnit *PredSU = I->getSUnit();
2047 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2048 // to cover the number of registers defined (they are all live).
2049 if (PredSU->NumRegDefsLeft == 0) {
2052 // FIXME: The ScheduleDAG currently loses information about which of a
2053 // node's values is consumed by each dependence. Consequently, if the node
2054 // defines multiple register classes, we don't know which to pressurize
2055 // here. Instead the following loop consumes the register defs in an
2056 // arbitrary order. At least it handles the common case of clustered loads
2057 // to the same class. For precise liveness, each SDep needs to indicate the
2058 // result number. But that tightly couples the ScheduleDAG with the
2059 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2060 // value type or register class to SDep.
2062 // The most important aspect of register tracking is balancing the increase
2063 // here with the reduction further below. Note that this SU may use multiple
2064 // defs in PredSU. The can't be determined here, but we've already
2065 // compensated by reducing NumRegDefsLeft in PredSU during
2066 // ScheduleDAGSDNodes::AddSchedEdges.
2067 --PredSU->NumRegDefsLeft;
2068 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2069 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2070 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2074 unsigned RCId, Cost;
2075 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2076 RegPressure[RCId] += Cost;
2081 // We should have this assert, but there may be dead SDNodes that never
2082 // materialize as SUnits, so they don't appear to generate liveness.
2083 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2084 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2085 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2086 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2087 if (SkipRegDefs > 0)
2089 unsigned RCId, Cost;
2090 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2091 if (RegPressure[RCId] < Cost) {
2092 // Register pressure tracking is imprecise. This can happen. But we try
2093 // hard not to let it happen because it likely results in poor scheduling.
2094 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2095 RegPressure[RCId] = 0;
2098 RegPressure[RCId] -= Cost;
2104 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2105 if (!TracksRegPressure)
2108 const SDNode *N = SU->getNode();
2111 if (!N->isMachineOpcode()) {
2112 if (N->getOpcode() != ISD::CopyToReg)
2115 unsigned Opc = N->getMachineOpcode();
2116 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2117 Opc == TargetOpcode::INSERT_SUBREG ||
2118 Opc == TargetOpcode::SUBREG_TO_REG ||
2119 Opc == TargetOpcode::REG_SEQUENCE ||
2120 Opc == TargetOpcode::IMPLICIT_DEF)
2124 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2128 SUnit *PredSU = I->getSUnit();
2129 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2130 // counts data deps.
2131 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2133 const SDNode *PN = PredSU->getNode();
2134 if (!PN->isMachineOpcode()) {
2135 if (PN->getOpcode() == ISD::CopyFromReg) {
2136 MVT VT = PN->getSimpleValueType(0);
2137 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2138 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2142 unsigned POpc = PN->getMachineOpcode();
2143 if (POpc == TargetOpcode::IMPLICIT_DEF)
2145 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2146 POpc == TargetOpcode::INSERT_SUBREG ||
2147 POpc == TargetOpcode::SUBREG_TO_REG) {
2148 MVT VT = PN->getSimpleValueType(0);
2149 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2150 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2153 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2154 for (unsigned i = 0; i != NumDefs; ++i) {
2155 MVT VT = PN->getSimpleValueType(i);
2156 if (!PN->hasAnyUseOfValue(i))
2158 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2159 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2160 // Register pressure tracking is imprecise. This can happen.
2161 RegPressure[RCId] = 0;
2163 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2167 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2168 // may transfer data dependencies to CopyToReg.
2169 if (SU->NumSuccs && N->isMachineOpcode()) {
2170 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2171 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2172 MVT VT = N->getSimpleValueType(i);
2173 if (VT == MVT::Glue || VT == MVT::Other)
2175 if (!N->hasAnyUseOfValue(i))
2177 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2178 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2185 //===----------------------------------------------------------------------===//
2186 // Dynamic Node Priority for Register Pressure Reduction
2187 //===----------------------------------------------------------------------===//
2189 /// closestSucc - Returns the scheduled cycle of the successor which is
2190 /// closest to the current cycle.
2191 static unsigned closestSucc(const SUnit *SU) {
2192 unsigned MaxHeight = 0;
2193 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2195 if (I->isCtrl()) continue; // ignore chain succs
2196 unsigned Height = I->getSUnit()->getHeight();
2197 // If there are bunch of CopyToRegs stacked up, they should be considered
2198 // to be at the same position.
2199 if (I->getSUnit()->getNode() &&
2200 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2201 Height = closestSucc(I->getSUnit())+1;
2202 if (Height > MaxHeight)
2208 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2209 /// for scratch registers, i.e. number of data dependencies.
2210 static unsigned calcMaxScratches(const SUnit *SU) {
2211 unsigned Scratches = 0;
2212 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2214 if (I->isCtrl()) continue; // ignore chain preds
2220 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2221 /// CopyFromReg from a virtual register.
2222 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2223 bool RetVal = false;
2224 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2226 if (I->isCtrl()) continue;
2227 const SUnit *PredSU = I->getSUnit();
2228 if (PredSU->getNode() &&
2229 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2231 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2232 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2242 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2243 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2244 /// it has no other use. It should be scheduled closer to the terminator.
2245 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2246 bool RetVal = false;
2247 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2249 if (I->isCtrl()) continue;
2250 const SUnit *SuccSU = I->getSUnit();
2251 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2253 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2254 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2264 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2265 // set isVRegCycle for its CopyFromReg operands.
2267 // This is only relevant for single-block loops, in which case the VRegCycle
2268 // node is likely an induction variable in which the operand and target virtual
2269 // registers should be coalesced (e.g. pre/post increment values). Setting the
2270 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2271 // CopyFromReg so that this node becomes the virtual register "kill". This
2272 // avoids interference between the values live in and out of the block and
2273 // eliminates a copy inside the loop.
2274 static void initVRegCycle(SUnit *SU) {
2275 if (DisableSchedVRegCycle)
2278 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2281 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2283 SU->isVRegCycle = true;
2285 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2287 if (I->isCtrl()) continue;
2288 I->getSUnit()->isVRegCycle = true;
2292 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2293 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2294 static void resetVRegCycle(SUnit *SU) {
2295 if (!SU->isVRegCycle)
2298 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2300 if (I->isCtrl()) continue; // ignore chain preds
2301 SUnit *PredSU = I->getSUnit();
2302 if (PredSU->isVRegCycle) {
2303 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2304 "VRegCycle def must be CopyFromReg");
2305 I->getSUnit()->isVRegCycle = 0;
2310 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2311 // means a node that defines the VRegCycle has not been scheduled yet.
2312 static bool hasVRegCycleUse(const SUnit *SU) {
2313 // If this SU also defines the VReg, don't hoist it as a "use".
2314 if (SU->isVRegCycle)
2317 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2319 if (I->isCtrl()) continue; // ignore chain preds
2320 if (I->getSUnit()->isVRegCycle &&
2321 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2322 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2329 // Check for either a dependence (latency) or resource (hazard) stall.
2331 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2332 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2333 if ((int)SPQ->getCurCycle() < Height) return true;
2334 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2335 != ScheduleHazardRecognizer::NoHazard)
2340 // Return -1 if left has higher priority, 1 if right has higher priority.
2341 // Return 0 if latency-based priority is equivalent.
2342 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2343 RegReductionPQBase *SPQ) {
2344 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2345 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2346 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2347 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2348 int LHeight = (int)left->getHeight() + LPenalty;
2349 int RHeight = (int)right->getHeight() + RPenalty;
2351 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2352 BUHasStall(left, LHeight, SPQ);
2353 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2354 BUHasStall(right, RHeight, SPQ);
2356 // If scheduling one of the node will cause a pipeline stall, delay it.
2357 // If scheduling either one of the node will cause a pipeline stall, sort
2358 // them according to their height.
2362 if (LHeight != RHeight)
2363 return LHeight > RHeight ? 1 : -1;
2367 // If either node is scheduling for latency, sort them by height/depth
2369 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2370 right->SchedulingPref == Sched::ILP)) {
2371 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2372 // is enabled, grouping instructions by cycle, then its height is already
2373 // covered so only its depth matters. We also reach this point if both stall
2374 // but have the same height.
2375 if (!SPQ->getHazardRec()->isEnabled()) {
2376 if (LHeight != RHeight)
2377 return LHeight > RHeight ? 1 : -1;
2379 int LDepth = left->getDepth() - LPenalty;
2380 int RDepth = right->getDepth() - RPenalty;
2381 if (LDepth != RDepth) {
2382 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2383 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2384 << ") depth " << RDepth << "\n");
2385 return LDepth < RDepth ? 1 : -1;
2387 if (left->Latency != right->Latency)
2388 return left->Latency > right->Latency ? 1 : -1;
2393 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2394 // Schedule physical register definitions close to their use. This is
2395 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2396 // long as shortening physreg live ranges is generally good, we can defer
2397 // creating a subtarget hook.
2398 if (!DisableSchedPhysRegJoin) {
2399 bool LHasPhysReg = left->hasPhysRegDefs;
2400 bool RHasPhysReg = right->hasPhysRegDefs;
2401 if (LHasPhysReg != RHasPhysReg) {
2403 static const char *const PhysRegMsg[] = { " has no physreg",
2404 " defines a physreg" };
2406 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2407 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2408 << PhysRegMsg[RHasPhysReg] << "\n");
2409 return LHasPhysReg < RHasPhysReg;
2413 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2414 unsigned LPriority = SPQ->getNodePriority(left);
2415 unsigned RPriority = SPQ->getNodePriority(right);
2417 // Be really careful about hoisting call operands above previous calls.
2418 // Only allows it if it would reduce register pressure.
2419 if (left->isCall && right->isCallOp) {
2420 unsigned RNumVals = right->getNode()->getNumValues();
2421 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2423 if (right->isCall && left->isCallOp) {
2424 unsigned LNumVals = left->getNode()->getNumValues();
2425 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2428 if (LPriority != RPriority)
2429 return LPriority > RPriority;
2431 // One or both of the nodes are calls and their sethi-ullman numbers are the
2432 // same, then keep source order.
2433 if (left->isCall || right->isCall) {
2434 unsigned LOrder = SPQ->getNodeOrdering(left);
2435 unsigned ROrder = SPQ->getNodeOrdering(right);
2437 // Prefer an ordering where the lower the non-zero order number, the higher
2439 if ((LOrder || ROrder) && LOrder != ROrder)
2440 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2443 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2448 // and the following instructions are both ready.
2452 // Then schedule t2 = op first.
2459 // This creates more short live intervals.
2460 unsigned LDist = closestSucc(left);
2461 unsigned RDist = closestSucc(right);
2463 return LDist < RDist;
2465 // How many registers becomes live when the node is scheduled.
2466 unsigned LScratch = calcMaxScratches(left);
2467 unsigned RScratch = calcMaxScratches(right);
2468 if (LScratch != RScratch)
2469 return LScratch > RScratch;
2471 // Comparing latency against a call makes little sense unless the node
2472 // is register pressure-neutral.
2473 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2474 return (left->NodeQueueId > right->NodeQueueId);
2476 // Do not compare latencies when one or both of the nodes are calls.
2477 if (!DisableSchedCycles &&
2478 !(left->isCall || right->isCall)) {
2479 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2484 if (left->getHeight() != right->getHeight())
2485 return left->getHeight() > right->getHeight();
2487 if (left->getDepth() != right->getDepth())
2488 return left->getDepth() < right->getDepth();
2491 assert(left->NodeQueueId && right->NodeQueueId &&
2492 "NodeQueueId cannot be zero");
2493 return (left->NodeQueueId > right->NodeQueueId);
2497 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2498 if (int res = checkSpecialNodes(left, right))
2501 return BURRSort(left, right, SPQ);
2504 // Source order, otherwise bottom up.
2505 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2506 if (int res = checkSpecialNodes(left, right))
2509 unsigned LOrder = SPQ->getNodeOrdering(left);
2510 unsigned ROrder = SPQ->getNodeOrdering(right);
2512 // Prefer an ordering where the lower the non-zero order number, the higher
2514 if ((LOrder || ROrder) && LOrder != ROrder)
2515 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2517 return BURRSort(left, right, SPQ);
2520 // If the time between now and when the instruction will be ready can cover
2521 // the spill code, then avoid adding it to the ready queue. This gives long
2522 // stalls highest priority and allows hoisting across calls. It should also
2523 // speed up processing the available queue.
2524 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2525 static const unsigned ReadyDelay = 3;
2527 if (SPQ->MayReduceRegPressure(SU)) return true;
2529 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2531 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2532 != ScheduleHazardRecognizer::NoHazard)
2538 // Return true if right should be scheduled with higher priority than left.
2539 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2540 if (int res = checkSpecialNodes(left, right))
2543 if (left->isCall || right->isCall)
2544 // No way to compute latency of calls.
2545 return BURRSort(left, right, SPQ);
2547 bool LHigh = SPQ->HighRegPressure(left);
2548 bool RHigh = SPQ->HighRegPressure(right);
2549 // Avoid causing spills. If register pressure is high, schedule for
2550 // register pressure reduction.
2551 if (LHigh && !RHigh) {
2552 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2553 << right->NodeNum << ")\n");
2556 else if (!LHigh && RHigh) {
2557 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2558 << left->NodeNum << ")\n");
2561 if (!LHigh && !RHigh) {
2562 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2566 return BURRSort(left, right, SPQ);
2569 // Schedule as many instructions in each cycle as possible. So don't make an
2570 // instruction available unless it is ready in the current cycle.
2571 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2572 if (SU->getHeight() > CurCycle) return false;
2574 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2575 != ScheduleHazardRecognizer::NoHazard)
2581 static bool canEnableCoalescing(SUnit *SU) {
2582 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2583 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2584 // CopyToReg should be close to its uses to facilitate coalescing and
2588 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2589 Opc == TargetOpcode::SUBREG_TO_REG ||
2590 Opc == TargetOpcode::INSERT_SUBREG)
2591 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2592 // close to their uses to facilitate coalescing.
2595 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2596 // If SU does not have a register def, schedule it close to its uses
2597 // because it does not lengthen any live ranges.
2603 // list-ilp is currently an experimental scheduler that allows various
2604 // heuristics to be enabled prior to the normal register reduction logic.
2605 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2606 if (int res = checkSpecialNodes(left, right))
2609 if (left->isCall || right->isCall)
2610 // No way to compute latency of calls.
2611 return BURRSort(left, right, SPQ);
2613 unsigned LLiveUses = 0, RLiveUses = 0;
2614 int LPDiff = 0, RPDiff = 0;
2615 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2616 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2617 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2619 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2620 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2621 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2622 return LPDiff > RPDiff;
2625 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2626 bool LReduce = canEnableCoalescing(left);
2627 bool RReduce = canEnableCoalescing(right);
2628 if (LReduce && !RReduce) return false;
2629 if (RReduce && !LReduce) return true;
2632 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2633 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2634 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2635 return LLiveUses < RLiveUses;
2638 if (!DisableSchedStalls) {
2639 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2640 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2641 if (LStall != RStall)
2642 return left->getHeight() > right->getHeight();
2645 if (!DisableSchedCriticalPath) {
2646 int spread = (int)left->getDepth() - (int)right->getDepth();
2647 if (std::abs(spread) > MaxReorderWindow) {
2648 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2649 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2650 << right->getDepth() << "\n");
2651 return left->getDepth() < right->getDepth();
2655 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2656 int spread = (int)left->getHeight() - (int)right->getHeight();
2657 if (std::abs(spread) > MaxReorderWindow)
2658 return left->getHeight() > right->getHeight();
2661 return BURRSort(left, right, SPQ);
2664 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2666 // Add pseudo dependency edges for two-address nodes.
2667 if (!Disable2AddrHack)
2668 AddPseudoTwoAddrDeps();
2669 // Reroute edges to nodes with multiple uses.
2670 if (!TracksRegPressure && !SrcOrder)
2671 PrescheduleNodesWithMultipleUses();
2672 // Calculate node priorities.
2673 CalculateSethiUllmanNumbers();
2675 // For single block loops, mark nodes that look like canonical IV increments.
2676 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2677 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2678 initVRegCycle(&sunits[i]);
2683 //===----------------------------------------------------------------------===//
2684 // Preschedule for Register Pressure
2685 //===----------------------------------------------------------------------===//
2687 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2688 if (SU->isTwoAddress) {
2689 unsigned Opc = SU->getNode()->getMachineOpcode();
2690 const MCInstrDesc &MCID = TII->get(Opc);
2691 unsigned NumRes = MCID.getNumDefs();
2692 unsigned NumOps = MCID.getNumOperands() - NumRes;
2693 for (unsigned i = 0; i != NumOps; ++i) {
2694 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2695 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2696 if (DU->getNodeId() != -1 &&
2697 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2705 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2706 /// successor's explicit physregs whose definition can reach DepSU.
2707 /// i.e. DepSU should not be scheduled above SU.
2708 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2709 ScheduleDAGRRList *scheduleDAG,
2710 const TargetInstrInfo *TII,
2711 const TargetRegisterInfo *TRI) {
2712 const uint16_t *ImpDefs
2713 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2714 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2715 if(!ImpDefs && !RegMask)
2718 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2720 SUnit *SuccSU = SI->getSUnit();
2721 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2722 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2723 if (!PI->isAssignedRegDep())
2726 if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2727 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2731 for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2732 // Return true if SU clobbers this physical register use and the
2733 // definition of the register reaches from DepSU. IsReachable queries
2734 // a topological forward sort of the DAG (following the successors).
2735 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2736 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2743 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2744 /// physical register defs.
2745 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2746 const TargetInstrInfo *TII,
2747 const TargetRegisterInfo *TRI) {
2748 SDNode *N = SuccSU->getNode();
2749 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2750 const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2751 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2752 for (const SDNode *SUNode = SU->getNode(); SUNode;
2753 SUNode = SUNode->getGluedNode()) {
2754 if (!SUNode->isMachineOpcode())
2756 const uint16_t *SUImpDefs =
2757 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2758 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2759 if (!SUImpDefs && !SURegMask)
2761 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2762 MVT VT = N->getSimpleValueType(i);
2763 if (VT == MVT::Glue || VT == MVT::Other)
2765 if (!N->hasAnyUseOfValue(i))
2767 unsigned Reg = ImpDefs[i - NumDefs];
2768 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2772 for (;*SUImpDefs; ++SUImpDefs) {
2773 unsigned SUReg = *SUImpDefs;
2774 if (TRI->regsOverlap(Reg, SUReg))
2782 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2783 /// are not handled well by the general register pressure reduction
2784 /// heuristics. When presented with code like this:
2793 /// the heuristics tend to push the store up, but since the
2794 /// operand of the store has another use (U), this would increase
2795 /// the length of that other use (the U->N edge).
2797 /// This function transforms code like the above to route U's
2798 /// dependence through the store when possible, like this:
2809 /// This results in the store being scheduled immediately
2810 /// after N, which shortens the U->N live range, reducing
2811 /// register pressure.
2813 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2814 // Visit all the nodes in topological order, working top-down.
2815 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2816 SUnit *SU = &(*SUnits)[i];
2817 // For now, only look at nodes with no data successors, such as stores.
2818 // These are especially important, due to the heuristics in
2819 // getNodePriority for nodes with no data successors.
2820 if (SU->NumSuccs != 0)
2822 // For now, only look at nodes with exactly one data predecessor.
2823 if (SU->NumPreds != 1)
2825 // Avoid prescheduling copies to 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::CopyToReg &&
2829 TargetRegisterInfo::isVirtualRegister
2830 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2833 // Locate the single data predecessor.
2834 SUnit *PredSU = nullptr;
2835 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2836 EE = SU->Preds.end(); II != EE; ++II)
2837 if (!II->isCtrl()) {
2838 PredSU = II->getSUnit();
2843 // Don't rewrite edges that carry physregs, because that requires additional
2844 // support infrastructure.
2845 if (PredSU->hasPhysRegDefs)
2847 // Short-circuit the case where SU is PredSU's only data successor.
2848 if (PredSU->NumSuccs == 1)
2850 // Avoid prescheduling to copies from virtual registers, which don't behave
2851 // like other nodes from the perspective of scheduling heuristics.
2852 if (SDNode *N = SU->getNode())
2853 if (N->getOpcode() == ISD::CopyFromReg &&
2854 TargetRegisterInfo::isVirtualRegister
2855 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2858 // Perform checks on the successors of PredSU.
2859 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2860 EE = PredSU->Succs.end(); II != EE; ++II) {
2861 SUnit *PredSuccSU = II->getSUnit();
2862 if (PredSuccSU == SU) continue;
2863 // If PredSU has another successor with no data successors, for
2864 // now don't attempt to choose either over the other.
2865 if (PredSuccSU->NumSuccs == 0)
2866 goto outer_loop_continue;
2867 // Don't break physical register dependencies.
2868 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2869 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2870 goto outer_loop_continue;
2871 // Don't introduce graph cycles.
2872 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2873 goto outer_loop_continue;
2876 // Ok, the transformation is safe and the heuristics suggest it is
2877 // profitable. Update the graph.
2878 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2879 << " next to PredSU #" << PredSU->NodeNum
2880 << " to guide scheduling in the presence of multiple uses\n");
2881 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2882 SDep Edge = PredSU->Succs[i];
2883 assert(!Edge.isAssignedRegDep());
2884 SUnit *SuccSU = Edge.getSUnit();
2886 Edge.setSUnit(PredSU);
2887 scheduleDAG->RemovePred(SuccSU, Edge);
2888 scheduleDAG->AddPred(SU, Edge);
2890 scheduleDAG->AddPred(SuccSU, Edge);
2894 outer_loop_continue:;
2898 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2899 /// it as a def&use operand. Add a pseudo control edge from it to the other
2900 /// node (if it won't create a cycle) so the two-address one will be scheduled
2901 /// first (lower in the schedule). If both nodes are two-address, favor the
2902 /// one that has a CopyToReg use (more likely to be a loop induction update).
2903 /// If both are two-address, but one is commutable while the other is not
2904 /// commutable, favor the one that's not commutable.
2905 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2906 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2907 SUnit *SU = &(*SUnits)[i];
2908 if (!SU->isTwoAddress)
2911 SDNode *Node = SU->getNode();
2912 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2915 bool isLiveOut = hasOnlyLiveOutUses(SU);
2916 unsigned Opc = Node->getMachineOpcode();
2917 const MCInstrDesc &MCID = TII->get(Opc);
2918 unsigned NumRes = MCID.getNumDefs();
2919 unsigned NumOps = MCID.getNumOperands() - NumRes;
2920 for (unsigned j = 0; j != NumOps; ++j) {
2921 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2923 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2924 if (DU->getNodeId() == -1)
2926 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2927 if (!DUSU) continue;
2928 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2929 E = DUSU->Succs.end(); I != E; ++I) {
2930 if (I->isCtrl()) continue;
2931 SUnit *SuccSU = I->getSUnit();
2934 // Be conservative. Ignore if nodes aren't at roughly the same
2935 // depth and height.
2936 if (SuccSU->getHeight() < SU->getHeight() &&
2937 (SU->getHeight() - SuccSU->getHeight()) > 1)
2939 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2940 // constrains whatever is using the copy, instead of the copy
2941 // itself. In the case that the copy is coalesced, this
2942 // preserves the intent of the pseudo two-address heurietics.
2943 while (SuccSU->Succs.size() == 1 &&
2944 SuccSU->getNode()->isMachineOpcode() &&
2945 SuccSU->getNode()->getMachineOpcode() ==
2946 TargetOpcode::COPY_TO_REGCLASS)
2947 SuccSU = SuccSU->Succs.front().getSUnit();
2948 // Don't constrain non-instruction nodes.
2949 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2951 // Don't constrain nodes with physical register defs if the
2952 // predecessor can clobber them.
2953 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2954 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2957 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2958 // these may be coalesced away. We want them close to their uses.
2959 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2960 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2961 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2962 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2964 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2965 (!canClobber(SuccSU, DUSU) ||
2966 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2967 (!SU->isCommutable && SuccSU->isCommutable)) &&
2968 !scheduleDAG->IsReachable(SuccSU, SU)) {
2969 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2970 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2971 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Artificial));
2978 //===----------------------------------------------------------------------===//
2979 // Public Constructor Functions
2980 //===----------------------------------------------------------------------===//
2982 llvm::ScheduleDAGSDNodes *
2983 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2984 CodeGenOpt::Level OptLevel) {
2985 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2986 const TargetInstrInfo *TII = STI.getInstrInfo();
2987 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2989 BURegReductionPriorityQueue *PQ =
2990 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
2991 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2992 PQ->setScheduleDAG(SD);
2996 llvm::ScheduleDAGSDNodes *
2997 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2998 CodeGenOpt::Level OptLevel) {
2999 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3000 const TargetInstrInfo *TII = STI.getInstrInfo();
3001 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3003 SrcRegReductionPriorityQueue *PQ =
3004 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
3005 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
3006 PQ->setScheduleDAG(SD);
3010 llvm::ScheduleDAGSDNodes *
3011 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
3012 CodeGenOpt::Level OptLevel) {
3013 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3014 const TargetInstrInfo *TII = STI.getInstrInfo();
3015 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3016 const TargetLowering *TLI = IS->TLI;
3018 HybridBURRPriorityQueue *PQ =
3019 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3021 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3022 PQ->setScheduleDAG(SD);
3026 llvm::ScheduleDAGSDNodes *
3027 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
3028 CodeGenOpt::Level OptLevel) {
3029 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3030 const TargetInstrInfo *TII = STI.getInstrInfo();
3031 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3032 const TargetLowering *TLI = IS->TLI;
3034 ILPBURRPriorityQueue *PQ =
3035 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3036 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3037 PQ->setScheduleDAG(SD);