]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp
Merge llvm trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
16 //===----------------------------------------------------------------------===//
17
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"
35 #include <climits>
36 using namespace llvm;
37
38 #define DEBUG_TYPE "pre-RA-sched"
39
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");
44
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);
54
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);
60
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);
66
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"));
70
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"));
97
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"));
102
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."));
106
107 namespace {
108 //===----------------------------------------------------------------------===//
109 /// ScheduleDAGRRList - The actual register reduction list scheduler
110 /// implementation.  This supports both top-down and bottom-up scheduling.
111 ///
112 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
113 private:
114   /// NeedLatency - True if the scheduler will make use of latency information.
115   ///
116   bool NeedLatency;
117
118   /// AvailableQueue - The priority queue to use for the available SUnits.
119   SchedulingPriorityQueue *AvailableQueue;
120
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;
126
127   /// HazardRec - The hazard recognizer to use.
128   ScheduleHazardRecognizer *HazardRec;
129
130   /// CurCycle - The current scheduler state corresponds to this cycle.
131   unsigned CurCycle;
132
133   /// MinAvailableCycle - Cycle of the soonest available instruction.
134   unsigned MinAvailableCycle;
135
136   /// IssueCount - Count instructions issued in this cycle
137   /// Currently valid only for bottom-up scheduling.
138   unsigned IssueCount;
139
140   /// LiveRegDefs - A set of physical registers and their definition
141   /// that are "live". These nodes must be scheduled before any other nodes that
142   /// modifies the registers can be scheduled.
143   unsigned NumLiveRegs;
144   std::unique_ptr<SUnit*[]> LiveRegDefs;
145   std::unique_ptr<SUnit*[]> LiveRegGens;
146
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;
151   LRegsMapT LRegsMap;
152
153   /// Topo - A topological ordering for SUnits which permits fast IsReachable
154   /// and similar queries.
155   ScheduleDAGTopologicalSort Topo;
156
157   // Hack to keep track of the inverse of FindCallSeqStart without more crazy
158   // DAG crawling.
159   DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
160
161 public:
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) {
168
169     const TargetSubtargetInfo &STI = mf.getSubtarget();
170     if (DisableSchedCycles || !NeedLatency)
171       HazardRec = new ScheduleHazardRecognizer();
172     else
173       HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
174   }
175
176   ~ScheduleDAGRRList() override {
177     delete HazardRec;
178     delete AvailableQueue;
179   }
180
181   void Schedule() override;
182
183   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
184
185   /// IsReachable - Checks if SU is reachable from TargetSU.
186   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
187     return Topo.IsReachable(SU, TargetSU);
188   }
189
190   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
191   /// create a cycle.
192   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
193     return Topo.WillCreateCycle(SU, TargetSU);
194   }
195
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());
201     SU->addPred(D);
202   }
203
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());
209     SU->removePred(D);
210   }
211
212 private:
213   bool isReady(SUnit *SU) {
214     return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
215       AvailableQueue->isReady(SU);
216   }
217
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>&);
235
236   void releaseInterferences(unsigned Reg = 0);
237
238   SUnit *PickNodeToScheduleBottomUp();
239   void ListScheduleBottomUp();
240
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();
249     return NewNode;
250   }
251
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();
260     return NewNode;
261   }
262
263   /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
264   /// need actual latency information but the hybrid scheduler does.
265   bool forceUnitLatencies() const override {
266     return !NeedLatency;
267   }
268 };
269 }  // end anonymous namespace
270
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();
282
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();
287
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();
293       Cost = 1;
294       return;
295     }
296
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();
302       Cost = 1;
303       return;
304     }
305
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.
312     Cost = 1;
313   } else {
314     RegClass = TLI->getRepRegClassFor(VT)->getID();
315     Cost = TLI->getRepRegClassCostFor(VT);
316   }
317 }
318
319 /// Schedule - Schedule the DAG using list scheduling.
320 void ScheduleDAGRRList::Schedule() {
321   DEBUG(dbgs()
322         << "********** List Scheduling BB#" << BB->getNumber()
323         << " '" << BB->getName() << "' **********\n");
324
325   CurCycle = 0;
326   IssueCount = 0;
327   MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
328   NumLiveRegs = 0;
329   // Allocate slots for each physical register, plus one for a special register
330   // to track the virtual resource of a calling sequence.
331   LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
332   LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
333   CallSeqEndForStart.clear();
334   assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
335
336   // Build the scheduling graph.
337   BuildSchedGraph(nullptr);
338
339   DEBUG(for (SUnit &SU : SUnits)
340           SU.dumpAll(this));
341   Topo.InitDAGTopologicalSorting();
342
343   AvailableQueue->initNodes(SUnits);
344
345   HazardRec->Reset();
346
347   // Execute the actual scheduling loop.
348   ListScheduleBottomUp();
349
350   AvailableQueue->releaseState();
351
352   DEBUG({
353       dbgs() << "*** Final schedule ***\n";
354       dumpSchedule();
355       dbgs() << '\n';
356     });
357 }
358
359 //===----------------------------------------------------------------------===//
360 //  Bottom-Up Scheduling
361 //===----------------------------------------------------------------------===//
362
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();
367
368 #ifndef NDEBUG
369   if (PredSU->NumSuccsLeft == 0) {
370     dbgs() << "*** Scheduling failed! ***\n";
371     PredSU->dump(this);
372     dbgs() << " has been released too many times!\n";
373     llvm_unreachable(nullptr);
374   }
375 #endif
376   --PredSU->NumSuccsLeft;
377
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());
382   }
383
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;
388
389     unsigned Height = PredSU->getHeight();
390     if (Height < MinAvailableCycle)
391       MinAvailableCycle = Height;
392
393     if (isReady(PredSU)) {
394       AvailableQueue->push(PredSU);
395     }
396     // CapturePred and others may have left the node in the pending queue, avoid
397     // adding it twice.
398     else if (!PredSU->isPending) {
399       PredSU->isPending = true;
400       PendingQueue.push_back(PredSU);
401     }
402   }
403 }
404
405 /// IsChainDependent - Test if Outer is reachable from Inner through
406 /// chain dependencies.
407 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
408                              unsigned NestLevel,
409                              const TargetInstrInfo *TII) {
410   SDNode *N = Outer;
411   for (;;) {
412     if (N == Inner)
413       return true;
414     // For a TokenFactor, examine each operand. There may be multiple ways
415     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
416     // most nesting in order to ensure that we find the corresponding match.
417     if (N->getOpcode() == ISD::TokenFactor) {
418       for (const SDValue &Op : N->op_values())
419         if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
420           return true;
421       return false;
422     }
423     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
424     if (N->isMachineOpcode()) {
425       if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
426         ++NestLevel;
427       } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
428         if (NestLevel == 0)
429           return false;
430         --NestLevel;
431       }
432     }
433     // Otherwise, find the chain and continue climbing.
434     for (const SDValue &Op : N->op_values())
435       if (Op.getValueType() == MVT::Other) {
436         N = Op.getNode();
437         goto found_chain_operand;
438       }
439     return false;
440   found_chain_operand:;
441     if (N->getOpcode() == ISD::EntryToken)
442       return false;
443   }
444 }
445
446 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
447 /// the corresponding (lowered) CALLSEQ_BEGIN node.
448 ///
449 /// NestLevel and MaxNested are used in recursion to indcate the current level
450 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
451 /// level seen so far.
452 ///
453 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
454 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
455 static SDNode *
456 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
457                  const TargetInstrInfo *TII) {
458   for (;;) {
459     // For a TokenFactor, examine each operand. There may be multiple ways
460     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
461     // most nesting in order to ensure that we find the corresponding match.
462     if (N->getOpcode() == ISD::TokenFactor) {
463       SDNode *Best = nullptr;
464       unsigned BestMaxNest = MaxNest;
465       for (const SDValue &Op : N->op_values()) {
466         unsigned MyNestLevel = NestLevel;
467         unsigned MyMaxNest = MaxNest;
468         if (SDNode *New = FindCallSeqStart(Op.getNode(),
469                                            MyNestLevel, MyMaxNest, TII))
470           if (!Best || (MyMaxNest > BestMaxNest)) {
471             Best = New;
472             BestMaxNest = MyMaxNest;
473           }
474       }
475       assert(Best);
476       MaxNest = BestMaxNest;
477       return Best;
478     }
479     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
480     if (N->isMachineOpcode()) {
481       if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
482         ++NestLevel;
483         MaxNest = std::max(MaxNest, NestLevel);
484       } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
485         assert(NestLevel != 0);
486         --NestLevel;
487         if (NestLevel == 0)
488           return N;
489       }
490     }
491     // Otherwise, find the chain and continue climbing.
492     for (const SDValue &Op : N->op_values())
493       if (Op.getValueType() == MVT::Other) {
494         N = Op.getNode();
495         goto found_chain_operand;
496       }
497     return nullptr;
498   found_chain_operand:;
499     if (N->getOpcode() == ISD::EntryToken)
500       return nullptr;
501   }
502 }
503
504 /// Call ReleasePred for each predecessor, then update register live def/gen.
505 /// Always update LiveRegDefs for a register dependence even if the current SU
506 /// also defines the register. This effectively create one large live range
507 /// across a sequence of two-address node. This is important because the
508 /// entire chain must be scheduled together. Example:
509 ///
510 /// flags = (3) add
511 /// flags = (2) addc flags
512 /// flags = (1) addc flags
513 ///
514 /// results in
515 ///
516 /// LiveRegDefs[flags] = 3
517 /// LiveRegGens[flags] = 1
518 ///
519 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
520 /// interference on flags.
521 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
522   // Bottom up: release predecessors
523   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
524        I != E; ++I) {
525     ReleasePred(SU, &*I);
526     if (I->isAssignedRegDep()) {
527       // This is a physical register dependency and it's impossible or
528       // expensive to copy the register. Make sure nothing that can
529       // clobber the register is scheduled between the predecessor and
530       // this node.
531       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
532       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
533              "interference on register dependence");
534       LiveRegDefs[I->getReg()] = I->getSUnit();
535       if (!LiveRegGens[I->getReg()]) {
536         ++NumLiveRegs;
537         LiveRegGens[I->getReg()] = SU;
538       }
539     }
540   }
541
542   // If we're scheduling a lowered CALLSEQ_END, find the corresponding
543   // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
544   // these nodes, to prevent other calls from being interscheduled with them.
545   unsigned CallResource = TRI->getNumRegs();
546   if (!LiveRegDefs[CallResource])
547     for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
548       if (Node->isMachineOpcode() &&
549           Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
550         unsigned NestLevel = 0;
551         unsigned MaxNest = 0;
552         SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
553
554         SUnit *Def = &SUnits[N->getNodeId()];
555         CallSeqEndForStart[Def] = SU;
556
557         ++NumLiveRegs;
558         LiveRegDefs[CallResource] = Def;
559         LiveRegGens[CallResource] = SU;
560         break;
561       }
562 }
563
564 /// Check to see if any of the pending instructions are ready to issue.  If
565 /// so, add them to the available queue.
566 void ScheduleDAGRRList::ReleasePending() {
567   if (DisableSchedCycles) {
568     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
569     return;
570   }
571
572   // If the available queue is empty, it is safe to reset MinAvailableCycle.
573   if (AvailableQueue->empty())
574     MinAvailableCycle = UINT_MAX;
575
576   // Check to see if any of the pending instructions are ready to issue.  If
577   // so, add them to the available queue.
578   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
579     unsigned ReadyCycle = PendingQueue[i]->getHeight();
580     if (ReadyCycle < MinAvailableCycle)
581       MinAvailableCycle = ReadyCycle;
582
583     if (PendingQueue[i]->isAvailable) {
584       if (!isReady(PendingQueue[i]))
585           continue;
586       AvailableQueue->push(PendingQueue[i]);
587     }
588     PendingQueue[i]->isPending = false;
589     PendingQueue[i] = PendingQueue.back();
590     PendingQueue.pop_back();
591     --i; --e;
592   }
593 }
594
595 /// Move the scheduler state forward by the specified number of Cycles.
596 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
597   if (NextCycle <= CurCycle)
598     return;
599
600   IssueCount = 0;
601   AvailableQueue->setCurCycle(NextCycle);
602   if (!HazardRec->isEnabled()) {
603     // Bypass lots of virtual calls in case of long latency.
604     CurCycle = NextCycle;
605   }
606   else {
607     for (; CurCycle != NextCycle; ++CurCycle) {
608       HazardRec->RecedeCycle();
609     }
610   }
611   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
612   // available Q to release pending nodes at least once before popping.
613   ReleasePending();
614 }
615
616 /// Move the scheduler state forward until the specified node's dependents are
617 /// ready and can be scheduled with no resource conflicts.
618 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
619   if (DisableSchedCycles)
620     return;
621
622   // FIXME: Nodes such as CopyFromReg probably should not advance the current
623   // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
624   // has predecessors the cycle will be advanced when they are scheduled.
625   // But given the crude nature of modeling latency though such nodes, we
626   // currently need to treat these nodes like real instructions.
627   // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
628
629   unsigned ReadyCycle = SU->getHeight();
630
631   // Bump CurCycle to account for latency. We assume the latency of other
632   // available instructions may be hidden by the stall (not a full pipe stall).
633   // This updates the hazard recognizer's cycle before reserving resources for
634   // this instruction.
635   AdvanceToCycle(ReadyCycle);
636
637   // Calls are scheduled in their preceding cycle, so don't conflict with
638   // hazards from instructions after the call. EmitNode will reset the
639   // scoreboard state before emitting the call.
640   if (SU->isCall)
641     return;
642
643   // FIXME: For resource conflicts in very long non-pipelined stages, we
644   // should probably skip ahead here to avoid useless scoreboard checks.
645   int Stalls = 0;
646   while (true) {
647     ScheduleHazardRecognizer::HazardType HT =
648       HazardRec->getHazardType(SU, -Stalls);
649
650     if (HT == ScheduleHazardRecognizer::NoHazard)
651       break;
652
653     ++Stalls;
654   }
655   AdvanceToCycle(CurCycle + Stalls);
656 }
657
658 /// Record this SUnit in the HazardRecognizer.
659 /// Does not update CurCycle.
660 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
661   if (!HazardRec->isEnabled())
662     return;
663
664   // Check for phys reg copy.
665   if (!SU->getNode())
666     return;
667
668   switch (SU->getNode()->getOpcode()) {
669   default:
670     assert(SU->getNode()->isMachineOpcode() &&
671            "This target-independent node should not be scheduled.");
672     break;
673   case ISD::MERGE_VALUES:
674   case ISD::TokenFactor:
675   case ISD::LIFETIME_START:
676   case ISD::LIFETIME_END:
677   case ISD::CopyToReg:
678   case ISD::CopyFromReg:
679   case ISD::EH_LABEL:
680     // Noops don't affect the scoreboard state. Copies are likely to be
681     // removed.
682     return;
683   case ISD::INLINEASM:
684     // For inline asm, clear the pipeline state.
685     HazardRec->Reset();
686     return;
687   }
688   if (SU->isCall) {
689     // Calls are scheduled with their preceding instructions. For bottom-up
690     // scheduling, clear the pipeline state before emitting.
691     HazardRec->Reset();
692   }
693
694   HazardRec->EmitInstruction(SU);
695 }
696
697 static void resetVRegCycle(SUnit *SU);
698
699 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
700 /// count of its predecessors. If a predecessor pending count is zero, add it to
701 /// the Available queue.
702 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
703   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
704   DEBUG(SU->dump(this));
705
706 #ifndef NDEBUG
707   if (CurCycle < SU->getHeight())
708     DEBUG(dbgs() << "   Height [" << SU->getHeight()
709           << "] pipeline stall!\n");
710 #endif
711
712   // FIXME: Do not modify node height. It may interfere with
713   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
714   // node its ready cycle can aid heuristics, and after scheduling it can
715   // indicate the scheduled cycle.
716   SU->setHeightToAtLeast(CurCycle);
717
718   // Reserve resources for the scheduled instruction.
719   EmitNode(SU);
720
721   Sequence.push_back(SU);
722
723   AvailableQueue->scheduledNode(SU);
724
725   // If HazardRec is disabled, and each inst counts as one cycle, then
726   // advance CurCycle before ReleasePredecessors to avoid useless pushes to
727   // PendingQueue for schedulers that implement HasReadyFilter.
728   if (!HazardRec->isEnabled() && AvgIPC < 2)
729     AdvanceToCycle(CurCycle + 1);
730
731   // Update liveness of predecessors before successors to avoid treating a
732   // two-address node as a live range def.
733   ReleasePredecessors(SU);
734
735   // Release all the implicit physical register defs that are live.
736   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
737        I != E; ++I) {
738     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
739     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
740       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
741       --NumLiveRegs;
742       LiveRegDefs[I->getReg()] = nullptr;
743       LiveRegGens[I->getReg()] = nullptr;
744       releaseInterferences(I->getReg());
745     }
746   }
747   // Release the special call resource dependence, if this is the beginning
748   // of a call.
749   unsigned CallResource = TRI->getNumRegs();
750   if (LiveRegDefs[CallResource] == SU)
751     for (const SDNode *SUNode = SU->getNode(); SUNode;
752          SUNode = SUNode->getGluedNode()) {
753       if (SUNode->isMachineOpcode() &&
754           SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
755         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
756         --NumLiveRegs;
757         LiveRegDefs[CallResource] = nullptr;
758         LiveRegGens[CallResource] = nullptr;
759         releaseInterferences(CallResource);
760       }
761     }
762
763   resetVRegCycle(SU);
764
765   SU->isScheduled = true;
766
767   // Conditions under which the scheduler should eagerly advance the cycle:
768   // (1) No available instructions
769   // (2) All pipelines full, so available instructions must have hazards.
770   //
771   // If HazardRec is disabled, the cycle was pre-advanced before calling
772   // ReleasePredecessors. In that case, IssueCount should remain 0.
773   //
774   // Check AvailableQueue after ReleasePredecessors in case of zero latency.
775   if (HazardRec->isEnabled() || AvgIPC > 1) {
776     if (SU->getNode() && SU->getNode()->isMachineOpcode())
777       ++IssueCount;
778     if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
779         || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
780       AdvanceToCycle(CurCycle + 1);
781   }
782 }
783
784 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
785 /// unscheduled, incrcease the succ left count of its predecessors. Remove
786 /// them from AvailableQueue if necessary.
787 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
788   SUnit *PredSU = PredEdge->getSUnit();
789   if (PredSU->isAvailable) {
790     PredSU->isAvailable = false;
791     if (!PredSU->isPending)
792       AvailableQueue->remove(PredSU);
793   }
794
795   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
796   ++PredSU->NumSuccsLeft;
797 }
798
799 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
800 /// its predecessor states to reflect the change.
801 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
802   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
803   DEBUG(SU->dump(this));
804
805   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
806        I != E; ++I) {
807     CapturePred(&*I);
808     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
809       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
810       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
811              "Physical register dependency violated?");
812       --NumLiveRegs;
813       LiveRegDefs[I->getReg()] = nullptr;
814       LiveRegGens[I->getReg()] = nullptr;
815       releaseInterferences(I->getReg());
816     }
817   }
818
819   // Reclaim the special call resource dependence, if this is the beginning
820   // of a call.
821   unsigned CallResource = TRI->getNumRegs();
822   for (const SDNode *SUNode = SU->getNode(); SUNode;
823        SUNode = SUNode->getGluedNode()) {
824     if (SUNode->isMachineOpcode() &&
825         SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
826       ++NumLiveRegs;
827       LiveRegDefs[CallResource] = SU;
828       LiveRegGens[CallResource] = CallSeqEndForStart[SU];
829     }
830   }
831
832   // Release the special call resource dependence, if this is the end
833   // of a call.
834   if (LiveRegGens[CallResource] == SU)
835     for (const SDNode *SUNode = SU->getNode(); SUNode;
836          SUNode = SUNode->getGluedNode()) {
837       if (SUNode->isMachineOpcode() &&
838           SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
839         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
840         --NumLiveRegs;
841         LiveRegDefs[CallResource] = nullptr;
842         LiveRegGens[CallResource] = nullptr;
843         releaseInterferences(CallResource);
844       }
845     }
846
847   for (auto &Succ : SU->Succs) {
848     if (Succ.isAssignedRegDep()) {
849       auto Reg = Succ.getReg();
850       if (!LiveRegDefs[Reg])
851         ++NumLiveRegs;
852       // This becomes the nearest def. Note that an earlier def may still be
853       // pending if this is a two-address node.
854       LiveRegDefs[Reg] = SU;
855
856       // Update LiveRegGen only if was empty before this unscheduling.
857       // This is to avoid incorrect updating LiveRegGen set in previous run.
858       if (!LiveRegGens[Reg]) {
859         // Find the successor with the lowest height.
860         LiveRegGens[Reg] = Succ.getSUnit();
861         for (auto &Succ2 : SU->Succs) {
862           if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
863               Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
864             LiveRegGens[Reg] = Succ2.getSUnit();
865         }
866       }
867     }
868   }
869   if (SU->getHeight() < MinAvailableCycle)
870     MinAvailableCycle = SU->getHeight();
871
872   SU->setHeightDirty();
873   SU->isScheduled = false;
874   SU->isAvailable = true;
875   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
876     // Don't make available until backtracking is complete.
877     SU->isPending = true;
878     PendingQueue.push_back(SU);
879   }
880   else {
881     AvailableQueue->push(SU);
882   }
883   AvailableQueue->unscheduledNode(SU);
884 }
885
886 /// After backtracking, the hazard checker needs to be restored to a state
887 /// corresponding the current cycle.
888 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
889   HazardRec->Reset();
890
891   unsigned LookAhead = std::min((unsigned)Sequence.size(),
892                                 HazardRec->getMaxLookAhead());
893   if (LookAhead == 0)
894     return;
895
896   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
897   unsigned HazardCycle = (*I)->getHeight();
898   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
899     SUnit *SU = *I;
900     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
901       HazardRec->RecedeCycle();
902     }
903     EmitNode(SU);
904   }
905 }
906
907 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
908 /// BTCycle in order to schedule a specific node.
909 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
910   SUnit *OldSU = Sequence.back();
911   while (true) {
912     Sequence.pop_back();
913     // FIXME: use ready cycle instead of height
914     CurCycle = OldSU->getHeight();
915     UnscheduleNodeBottomUp(OldSU);
916     AvailableQueue->setCurCycle(CurCycle);
917     if (OldSU == BtSU)
918       break;
919     OldSU = Sequence.back();
920   }
921
922   assert(!SU->isSucc(OldSU) && "Something is wrong!");
923
924   RestoreHazardCheckerBottomUp();
925
926   ReleasePending();
927
928   ++NumBacktracks;
929 }
930
931 static bool isOperandOf(const SUnit *SU, SDNode *N) {
932   for (const SDNode *SUNode = SU->getNode(); SUNode;
933        SUNode = SUNode->getGluedNode()) {
934     if (SUNode->isOperandOf(N))
935       return true;
936   }
937   return false;
938 }
939
940 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
941 /// successors to the newly created node.
942 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
943   SDNode *N = SU->getNode();
944   if (!N)
945     return nullptr;
946
947   if (SU->getNode()->getGluedNode())
948     return nullptr;
949
950   SUnit *NewSU;
951   bool TryUnfold = false;
952   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
953     MVT VT = N->getSimpleValueType(i);
954     if (VT == MVT::Glue)
955       return nullptr;
956     else if (VT == MVT::Other)
957       TryUnfold = true;
958   }
959   for (const SDValue &Op : N->op_values()) {
960     MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
961     if (VT == MVT::Glue)
962       return nullptr;
963   }
964
965   if (TryUnfold) {
966     SmallVector<SDNode*, 2> NewNodes;
967     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
968       return nullptr;
969
970     // unfolding an x86 DEC64m operation results in store, dec, load which
971     // can't be handled here so quit
972     if (NewNodes.size() == 3)
973       return nullptr;
974
975     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
976     assert(NewNodes.size() == 2 && "Expected a load folding node!");
977
978     N = NewNodes[1];
979     SDNode *LoadNode = NewNodes[0];
980     unsigned NumVals = N->getNumValues();
981     unsigned OldNumVals = SU->getNode()->getNumValues();
982     for (unsigned i = 0; i != NumVals; ++i)
983       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
984     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
985                                    SDValue(LoadNode, 1));
986
987     // LoadNode may already exist. This can happen when there is another
988     // load from the same location and producing the same type of value
989     // but it has different alignment or volatileness.
990     bool isNewLoad = true;
991     SUnit *LoadSU;
992     if (LoadNode->getNodeId() != -1) {
993       LoadSU = &SUnits[LoadNode->getNodeId()];
994       isNewLoad = false;
995     } else {
996       LoadSU = CreateNewSUnit(LoadNode);
997       LoadNode->setNodeId(LoadSU->NodeNum);
998
999       InitNumRegDefsLeft(LoadSU);
1000       computeLatency(LoadSU);
1001     }
1002
1003     SUnit *NewSU = CreateNewSUnit(N);
1004     assert(N->getNodeId() == -1 && "Node already inserted!");
1005     N->setNodeId(NewSU->NodeNum);
1006
1007     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1008     for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1009       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
1010         NewSU->isTwoAddress = true;
1011         break;
1012       }
1013     }
1014     if (MCID.isCommutable())
1015       NewSU->isCommutable = true;
1016
1017     InitNumRegDefsLeft(NewSU);
1018     computeLatency(NewSU);
1019
1020     // Record all the edges to and from the old SU, by category.
1021     SmallVector<SDep, 4> ChainPreds;
1022     SmallVector<SDep, 4> ChainSuccs;
1023     SmallVector<SDep, 4> LoadPreds;
1024     SmallVector<SDep, 4> NodePreds;
1025     SmallVector<SDep, 4> NodeSuccs;
1026     for (SDep &Pred : SU->Preds) {
1027       if (Pred.isCtrl())
1028         ChainPreds.push_back(Pred);
1029       else if (isOperandOf(Pred.getSUnit(), LoadNode))
1030         LoadPreds.push_back(Pred);
1031       else
1032         NodePreds.push_back(Pred);
1033     }
1034     for (SDep &Succ : SU->Succs) {
1035       if (Succ.isCtrl())
1036         ChainSuccs.push_back(Succ);
1037       else
1038         NodeSuccs.push_back(Succ);
1039     }
1040
1041     // Now assign edges to the newly-created nodes.
1042     for (const SDep &Pred : ChainPreds) {
1043       RemovePred(SU, Pred);
1044       if (isNewLoad)
1045         AddPred(LoadSU, Pred);
1046     }
1047     for (const SDep &Pred : LoadPreds) {
1048       RemovePred(SU, Pred);
1049       if (isNewLoad)
1050         AddPred(LoadSU, Pred);
1051     }
1052     for (const SDep &Pred : NodePreds) {
1053       RemovePred(SU, Pred);
1054       AddPred(NewSU, Pred);
1055     }
1056     for (SDep D : NodeSuccs) {
1057       SUnit *SuccDep = D.getSUnit();
1058       D.setSUnit(SU);
1059       RemovePred(SuccDep, D);
1060       D.setSUnit(NewSU);
1061       AddPred(SuccDep, D);
1062       // Balance register pressure.
1063       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1064           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1065         --NewSU->NumRegDefsLeft;
1066     }
1067     for (SDep D : ChainSuccs) {
1068       SUnit *SuccDep = D.getSUnit();
1069       D.setSUnit(SU);
1070       RemovePred(SuccDep, D);
1071       if (isNewLoad) {
1072         D.setSUnit(LoadSU);
1073         AddPred(SuccDep, D);
1074       }
1075     }
1076
1077     // Add a data dependency to reflect that NewSU reads the value defined
1078     // by LoadSU.
1079     SDep D(LoadSU, SDep::Data, 0);
1080     D.setLatency(LoadSU->Latency);
1081     AddPred(NewSU, D);
1082
1083     if (isNewLoad)
1084       AvailableQueue->addNode(LoadSU);
1085     AvailableQueue->addNode(NewSU);
1086
1087     ++NumUnfolds;
1088
1089     if (NewSU->NumSuccsLeft == 0) {
1090       NewSU->isAvailable = true;
1091       return NewSU;
1092     }
1093     SU = NewSU;
1094   }
1095
1096   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
1097   NewSU = CreateClone(SU);
1098
1099   // New SUnit has the exact same predecessors.
1100   for (SDep &Pred : SU->Preds)
1101     if (!Pred.isArtificial())
1102       AddPred(NewSU, Pred);
1103
1104   // Only copy scheduled successors. Cut them from old node's successor
1105   // list and move them over.
1106   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1107   for (SDep &Succ : SU->Succs) {
1108     if (Succ.isArtificial())
1109       continue;
1110     SUnit *SuccSU = Succ.getSUnit();
1111     if (SuccSU->isScheduled) {
1112       SDep D = Succ;
1113       D.setSUnit(NewSU);
1114       AddPred(SuccSU, D);
1115       D.setSUnit(SU);
1116       DelDeps.push_back(std::make_pair(SuccSU, D));
1117     }
1118   }
1119   for (auto &DelDep : DelDeps)
1120     RemovePred(DelDep.first, DelDep.second);
1121
1122   AvailableQueue->updateNode(SU);
1123   AvailableQueue->addNode(NewSU);
1124
1125   ++NumDups;
1126   return NewSU;
1127 }
1128
1129 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1130 /// scheduled successors of the given SUnit to the last copy.
1131 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1132                                               const TargetRegisterClass *DestRC,
1133                                               const TargetRegisterClass *SrcRC,
1134                                               SmallVectorImpl<SUnit*> &Copies) {
1135   SUnit *CopyFromSU = CreateNewSUnit(nullptr);
1136   CopyFromSU->CopySrcRC = SrcRC;
1137   CopyFromSU->CopyDstRC = DestRC;
1138
1139   SUnit *CopyToSU = CreateNewSUnit(nullptr);
1140   CopyToSU->CopySrcRC = DestRC;
1141   CopyToSU->CopyDstRC = SrcRC;
1142
1143   // Only copy scheduled successors. Cut them from old node's successor
1144   // list and move them over.
1145   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1146   for (SDep &Succ : SU->Succs) {
1147     if (Succ.isArtificial())
1148       continue;
1149     SUnit *SuccSU = Succ.getSUnit();
1150     if (SuccSU->isScheduled) {
1151       SDep D = Succ;
1152       D.setSUnit(CopyToSU);
1153       AddPred(SuccSU, D);
1154       DelDeps.push_back(std::make_pair(SuccSU, Succ));
1155     }
1156     else {
1157       // Avoid scheduling the def-side copy before other successors. Otherwise
1158       // we could introduce another physreg interference on the copy and
1159       // continue inserting copies indefinitely.
1160       AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
1161     }
1162   }
1163   for (auto &DelDep : DelDeps)
1164     RemovePred(DelDep.first, DelDep.second);
1165
1166   SDep FromDep(SU, SDep::Data, Reg);
1167   FromDep.setLatency(SU->Latency);
1168   AddPred(CopyFromSU, FromDep);
1169   SDep ToDep(CopyFromSU, SDep::Data, 0);
1170   ToDep.setLatency(CopyFromSU->Latency);
1171   AddPred(CopyToSU, ToDep);
1172
1173   AvailableQueue->updateNode(SU);
1174   AvailableQueue->addNode(CopyFromSU);
1175   AvailableQueue->addNode(CopyToSU);
1176   Copies.push_back(CopyFromSU);
1177   Copies.push_back(CopyToSU);
1178
1179   ++NumPRCopies;
1180 }
1181
1182 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1183 /// definition of the specified node.
1184 /// FIXME: Move to SelectionDAG?
1185 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1186                                  const TargetInstrInfo *TII) {
1187   unsigned NumRes;
1188   if (N->getOpcode() == ISD::CopyFromReg) {
1189     // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
1190     NumRes = 1;
1191   } else {
1192     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1193     assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1194     NumRes = MCID.getNumDefs();
1195     for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1196       if (Reg == *ImpDef)
1197         break;
1198       ++NumRes;
1199     }
1200   }
1201   return N->getSimpleValueType(NumRes);
1202 }
1203
1204 /// CheckForLiveRegDef - Return true and update live register vector if the
1205 /// specified register def of the specified SUnit clobbers any "live" registers.
1206 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1207                                SUnit **LiveRegDefs,
1208                                SmallSet<unsigned, 4> &RegAdded,
1209                                SmallVectorImpl<unsigned> &LRegs,
1210                                const TargetRegisterInfo *TRI) {
1211   for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
1212
1213     // Check if Ref is live.
1214     if (!LiveRegDefs[*AliasI]) continue;
1215
1216     // Allow multiple uses of the same def.
1217     if (LiveRegDefs[*AliasI] == SU) continue;
1218
1219     // Add Reg to the set of interfering live regs.
1220     if (RegAdded.insert(*AliasI).second) {
1221       LRegs.push_back(*AliasI);
1222     }
1223   }
1224 }
1225
1226 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1227 /// by RegMask, and add them to LRegs.
1228 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1229                                      ArrayRef<SUnit*> LiveRegDefs,
1230                                      SmallSet<unsigned, 4> &RegAdded,
1231                                      SmallVectorImpl<unsigned> &LRegs) {
1232   // Look at all live registers. Skip Reg0 and the special CallResource.
1233   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1234     if (!LiveRegDefs[i]) continue;
1235     if (LiveRegDefs[i] == SU) continue;
1236     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1237     if (RegAdded.insert(i).second)
1238       LRegs.push_back(i);
1239   }
1240 }
1241
1242 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1243 static const uint32_t *getNodeRegMask(const SDNode *N) {
1244   for (const SDValue &Op : N->op_values())
1245     if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
1246       return RegOp->getRegMask();
1247   return nullptr;
1248 }
1249
1250 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1251 /// scheduling of the given node to satisfy live physical register dependencies.
1252 /// If the specific node is the last one that's available to schedule, do
1253 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1254 bool ScheduleDAGRRList::
1255 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
1256   if (NumLiveRegs == 0)
1257     return false;
1258
1259   SmallSet<unsigned, 4> RegAdded;
1260   // If this node would clobber any "live" register, then it's not ready.
1261   //
1262   // If SU is the currently live definition of the same register that it uses,
1263   // then we are free to schedule it.
1264   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1265        I != E; ++I) {
1266     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1267       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs.get(),
1268                          RegAdded, LRegs, TRI);
1269   }
1270
1271   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1272     if (Node->getOpcode() == ISD::INLINEASM) {
1273       // Inline asm can clobber physical defs.
1274       unsigned NumOps = Node->getNumOperands();
1275       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1276         --NumOps;  // Ignore the glue operand.
1277
1278       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1279         unsigned Flags =
1280           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1281         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1282
1283         ++i; // Skip the ID value.
1284         if (InlineAsm::isRegDefKind(Flags) ||
1285             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1286             InlineAsm::isClobberKind(Flags)) {
1287           // Check for def of register or earlyclobber register.
1288           for (; NumVals; --NumVals, ++i) {
1289             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1290             if (TargetRegisterInfo::isPhysicalRegister(Reg))
1291               CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
1292           }
1293         } else
1294           i += NumVals;
1295       }
1296       continue;
1297     }
1298
1299     if (!Node->isMachineOpcode())
1300       continue;
1301     // If we're in the middle of scheduling a call, don't begin scheduling
1302     // another call. Also, don't allow any physical registers to be live across
1303     // the call.
1304     if ((Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) ||
1305         (Node->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
1306       // Check the special calling-sequence resource.
1307       unsigned CallResource = TRI->getNumRegs();
1308       if (LiveRegDefs[CallResource]) {
1309         SDNode *Gen = LiveRegGens[CallResource]->getNode();
1310         while (SDNode *Glued = Gen->getGluedNode())
1311           Gen = Glued;
1312         if (!IsChainDependent(Gen, Node, 0, TII) &&
1313             RegAdded.insert(CallResource).second)
1314           LRegs.push_back(CallResource);
1315       }
1316     }
1317     if (const uint32_t *RegMask = getNodeRegMask(Node))
1318       CheckForLiveRegDefMasked(SU, RegMask,
1319                                makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
1320                                RegAdded, LRegs);
1321
1322     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1323     if (!MCID.ImplicitDefs)
1324       continue;
1325     for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1326       CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
1327   }
1328
1329   return !LRegs.empty();
1330 }
1331
1332 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1333   // Add the nodes that aren't ready back onto the available list.
1334   for (unsigned i = Interferences.size(); i > 0; --i) {
1335     SUnit *SU = Interferences[i-1];
1336     LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1337     if (Reg) {
1338       SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
1339       if (!is_contained(LRegs, Reg))
1340         continue;
1341     }
1342     SU->isPending = false;
1343     // The interfering node may no longer be available due to backtracking.
1344     // Furthermore, it may have been made available again, in which case it is
1345     // now already in the AvailableQueue.
1346     if (SU->isAvailable && !SU->NodeQueueId) {
1347       DEBUG(dbgs() << "    Repushing SU #" << SU->NodeNum << '\n');
1348       AvailableQueue->push(SU);
1349     }
1350     if (i < Interferences.size())
1351       Interferences[i-1] = Interferences.back();
1352     Interferences.pop_back();
1353     LRegsMap.erase(LRegsPos);
1354   }
1355 }
1356
1357 /// Return a node that can be scheduled in this cycle. Requirements:
1358 /// (1) Ready: latency has been satisfied
1359 /// (2) No Hazards: resources are available
1360 /// (3) No Interferences: may unschedule to break register interferences.
1361 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1362   SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
1363   while (CurSU) {
1364     SmallVector<unsigned, 4> LRegs;
1365     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1366       break;
1367     DEBUG(dbgs() << "    Interfering reg " <<
1368           (LRegs[0] == TRI->getNumRegs() ? "CallResource"
1369            : TRI->getName(LRegs[0]))
1370            << " SU #" << CurSU->NodeNum << '\n');
1371     std::pair<LRegsMapT::iterator, bool> LRegsPair =
1372       LRegsMap.insert(std::make_pair(CurSU, LRegs));
1373     if (LRegsPair.second) {
1374       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
1375       Interferences.push_back(CurSU);
1376     }
1377     else {
1378       assert(CurSU->isPending && "Interferences are pending");
1379       // Update the interference with current live regs.
1380       LRegsPair.first->second = LRegs;
1381     }
1382     CurSU = AvailableQueue->pop();
1383   }
1384   if (CurSU)
1385     return CurSU;
1386
1387   // All candidates are delayed due to live physical reg dependencies.
1388   // Try backtracking, code duplication, or inserting cross class copies
1389   // to resolve it.
1390   for (SUnit *TrySU : Interferences) {
1391     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1392
1393     // Try unscheduling up to the point where it's safe to schedule
1394     // this node.
1395     SUnit *BtSU = nullptr;
1396     unsigned LiveCycle = UINT_MAX;
1397     for (unsigned Reg : LRegs) {
1398       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1399         BtSU = LiveRegGens[Reg];
1400         LiveCycle = BtSU->getHeight();
1401       }
1402     }
1403     if (!WillCreateCycle(TrySU, BtSU))  {
1404       // BacktrackBottomUp mutates Interferences!
1405       BacktrackBottomUp(TrySU, BtSU);
1406
1407       // Force the current node to be scheduled before the node that
1408       // requires the physical reg dep.
1409       if (BtSU->isAvailable) {
1410         BtSU->isAvailable = false;
1411         if (!BtSU->isPending)
1412           AvailableQueue->remove(BtSU);
1413       }
1414       DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
1415             << TrySU->NodeNum << ")\n");
1416       AddPred(TrySU, SDep(BtSU, SDep::Artificial));
1417
1418       // If one or more successors has been unscheduled, then the current
1419       // node is no longer available.
1420       if (!TrySU->isAvailable || !TrySU->NodeQueueId)
1421         CurSU = AvailableQueue->pop();
1422       else {
1423         // Available and in AvailableQueue
1424         AvailableQueue->remove(TrySU);
1425         CurSU = TrySU;
1426       }
1427       // Interferences has been mutated. We must break.
1428       break;
1429     }
1430   }
1431
1432   if (!CurSU) {
1433     // Can't backtrack. If it's too expensive to copy the value, then try
1434     // duplicate the nodes that produces these "too expensive to copy"
1435     // values to break the dependency. In case even that doesn't work,
1436     // insert cross class copies.
1437     // If it's not too expensive, i.e. cost != -1, issue copies.
1438     SUnit *TrySU = Interferences[0];
1439     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1440     assert(LRegs.size() == 1 && "Can't handle this yet!");
1441     unsigned Reg = LRegs[0];
1442     SUnit *LRDef = LiveRegDefs[Reg];
1443     MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1444     const TargetRegisterClass *RC =
1445       TRI->getMinimalPhysRegClass(Reg, VT);
1446     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1447
1448     // If cross copy register class is the same as RC, then it must be possible
1449     // copy the value directly. Do not try duplicate the def.
1450     // If cross copy register class is not the same as RC, then it's possible to
1451     // copy the value but it require cross register class copies and it is
1452     // expensive.
1453     // If cross copy register class is null, then it's not possible to copy
1454     // the value at all.
1455     SUnit *NewDef = nullptr;
1456     if (DestRC != RC) {
1457       NewDef = CopyAndMoveSuccessors(LRDef);
1458       if (!DestRC && !NewDef)
1459         report_fatal_error("Can't handle live physical register dependency!");
1460     }
1461     if (!NewDef) {
1462       // Issue copies, these can be expensive cross register class copies.
1463       SmallVector<SUnit*, 2> Copies;
1464       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1465       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
1466             << " to SU #" << Copies.front()->NodeNum << "\n");
1467       AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
1468       NewDef = Copies.back();
1469     }
1470
1471     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
1472           << " to SU #" << TrySU->NodeNum << "\n");
1473     LiveRegDefs[Reg] = NewDef;
1474     AddPred(NewDef, SDep(TrySU, SDep::Artificial));
1475     TrySU->isAvailable = false;
1476     CurSU = NewDef;
1477   }
1478   assert(CurSU && "Unable to resolve live physical register dependencies!");
1479   return CurSU;
1480 }
1481
1482 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1483 /// schedulers.
1484 void ScheduleDAGRRList::ListScheduleBottomUp() {
1485   // Release any predecessors of the special Exit node.
1486   ReleasePredecessors(&ExitSU);
1487
1488   // Add root to Available queue.
1489   if (!SUnits.empty()) {
1490     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1491     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1492     RootSU->isAvailable = true;
1493     AvailableQueue->push(RootSU);
1494   }
1495
1496   // While Available queue is not empty, grab the node with the highest
1497   // priority. If it is not ready put it back.  Schedule the node.
1498   Sequence.reserve(SUnits.size());
1499   while (!AvailableQueue->empty() || !Interferences.empty()) {
1500     DEBUG(dbgs() << "\nExamining Available:\n";
1501           AvailableQueue->dump(this));
1502
1503     // Pick the best node to schedule taking all constraints into
1504     // consideration.
1505     SUnit *SU = PickNodeToScheduleBottomUp();
1506
1507     AdvancePastStalls(SU);
1508
1509     ScheduleNodeBottomUp(SU);
1510
1511     while (AvailableQueue->empty() && !PendingQueue.empty()) {
1512       // Advance the cycle to free resources. Skip ahead to the next ready SU.
1513       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1514       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1515     }
1516   }
1517
1518   // Reverse the order if it is bottom up.
1519   std::reverse(Sequence.begin(), Sequence.end());
1520
1521 #ifndef NDEBUG
1522   VerifyScheduledSequence(/*isBottomUp=*/true);
1523 #endif
1524 }
1525
1526 //===----------------------------------------------------------------------===//
1527 //                RegReductionPriorityQueue Definition
1528 //===----------------------------------------------------------------------===//
1529 //
1530 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1531 // to reduce register pressure.
1532 //
1533 namespace {
1534 class RegReductionPQBase;
1535
1536 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1537   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1538 };
1539
1540 #ifndef NDEBUG
1541 template<class SF>
1542 struct reverse_sort : public queue_sort {
1543   SF &SortFunc;
1544   reverse_sort(SF &sf) : SortFunc(sf) {}
1545
1546   bool operator()(SUnit* left, SUnit* right) const {
1547     // reverse left/right rather than simply !SortFunc(left, right)
1548     // to expose different paths in the comparison logic.
1549     return SortFunc(right, left);
1550   }
1551 };
1552 #endif // NDEBUG
1553
1554 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1555 // reduction scheduler.
1556 struct bu_ls_rr_sort : public queue_sort {
1557   enum {
1558     IsBottomUp = true,
1559     HasReadyFilter = false
1560   };
1561
1562   RegReductionPQBase *SPQ;
1563   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1564
1565   bool operator()(SUnit* left, SUnit* right) const;
1566 };
1567
1568 // src_ls_rr_sort - Priority function for source order scheduler.
1569 struct src_ls_rr_sort : public queue_sort {
1570   enum {
1571     IsBottomUp = true,
1572     HasReadyFilter = false
1573   };
1574
1575   RegReductionPQBase *SPQ;
1576   src_ls_rr_sort(RegReductionPQBase *spq)
1577     : SPQ(spq) {}
1578
1579   bool operator()(SUnit* left, SUnit* right) const;
1580 };
1581
1582 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1583 struct hybrid_ls_rr_sort : public queue_sort {
1584   enum {
1585     IsBottomUp = true,
1586     HasReadyFilter = false
1587   };
1588
1589   RegReductionPQBase *SPQ;
1590   hybrid_ls_rr_sort(RegReductionPQBase *spq)
1591     : SPQ(spq) {}
1592
1593   bool isReady(SUnit *SU, unsigned CurCycle) const;
1594
1595   bool operator()(SUnit* left, SUnit* right) const;
1596 };
1597
1598 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1599 // scheduler.
1600 struct ilp_ls_rr_sort : public queue_sort {
1601   enum {
1602     IsBottomUp = true,
1603     HasReadyFilter = false
1604   };
1605
1606   RegReductionPQBase *SPQ;
1607   ilp_ls_rr_sort(RegReductionPQBase *spq)
1608     : SPQ(spq) {}
1609
1610   bool isReady(SUnit *SU, unsigned CurCycle) const;
1611
1612   bool operator()(SUnit* left, SUnit* right) const;
1613 };
1614
1615 class RegReductionPQBase : public SchedulingPriorityQueue {
1616 protected:
1617   std::vector<SUnit*> Queue;
1618   unsigned CurQueueId;
1619   bool TracksRegPressure;
1620   bool SrcOrder;
1621
1622   // SUnits - The SUnits for the current graph.
1623   std::vector<SUnit> *SUnits;
1624
1625   MachineFunction &MF;
1626   const TargetInstrInfo *TII;
1627   const TargetRegisterInfo *TRI;
1628   const TargetLowering *TLI;
1629   ScheduleDAGRRList *scheduleDAG;
1630
1631   // SethiUllmanNumbers - The SethiUllman number for each node.
1632   std::vector<unsigned> SethiUllmanNumbers;
1633
1634   /// RegPressure - Tracking current reg pressure per register class.
1635   ///
1636   std::vector<unsigned> RegPressure;
1637
1638   /// RegLimit - Tracking the number of allocatable registers per register
1639   /// class.
1640   std::vector<unsigned> RegLimit;
1641
1642 public:
1643   RegReductionPQBase(MachineFunction &mf,
1644                      bool hasReadyFilter,
1645                      bool tracksrp,
1646                      bool srcorder,
1647                      const TargetInstrInfo *tii,
1648                      const TargetRegisterInfo *tri,
1649                      const TargetLowering *tli)
1650     : SchedulingPriorityQueue(hasReadyFilter),
1651       CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
1652       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
1653     if (TracksRegPressure) {
1654       unsigned NumRC = TRI->getNumRegClasses();
1655       RegLimit.resize(NumRC);
1656       RegPressure.resize(NumRC);
1657       std::fill(RegLimit.begin(), RegLimit.end(), 0);
1658       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1659       for (const TargetRegisterClass *RC : TRI->regclasses())
1660         RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
1661     }
1662   }
1663
1664   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1665     scheduleDAG = scheduleDag;
1666   }
1667
1668   ScheduleHazardRecognizer* getHazardRec() {
1669     return scheduleDAG->getHazardRec();
1670   }
1671
1672   void initNodes(std::vector<SUnit> &sunits) override;
1673
1674   void addNode(const SUnit *SU) override;
1675
1676   void updateNode(const SUnit *SU) override;
1677
1678   void releaseState() override {
1679     SUnits = nullptr;
1680     SethiUllmanNumbers.clear();
1681     std::fill(RegPressure.begin(), RegPressure.end(), 0);
1682   }
1683
1684   unsigned getNodePriority(const SUnit *SU) const;
1685
1686   unsigned getNodeOrdering(const SUnit *SU) const {
1687     if (!SU->getNode()) return 0;
1688
1689     return SU->getNode()->getIROrder();
1690   }
1691
1692   bool empty() const override { return Queue.empty(); }
1693
1694   void push(SUnit *U) override {
1695     assert(!U->NodeQueueId && "Node in the queue already");
1696     U->NodeQueueId = ++CurQueueId;
1697     Queue.push_back(U);
1698   }
1699
1700   void remove(SUnit *SU) override {
1701     assert(!Queue.empty() && "Queue is empty!");
1702     assert(SU->NodeQueueId != 0 && "Not in queue!");
1703     std::vector<SUnit *>::iterator I = find(Queue, SU);
1704     if (I != std::prev(Queue.end()))
1705       std::swap(*I, Queue.back());
1706     Queue.pop_back();
1707     SU->NodeQueueId = 0;
1708   }
1709
1710   bool tracksRegPressure() const override { return TracksRegPressure; }
1711
1712   void dumpRegPressure() const;
1713
1714   bool HighRegPressure(const SUnit *SU) const;
1715
1716   bool MayReduceRegPressure(SUnit *SU) const;
1717
1718   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1719
1720   void scheduledNode(SUnit *SU) override;
1721
1722   void unscheduledNode(SUnit *SU) override;
1723
1724 protected:
1725   bool canClobber(const SUnit *SU, const SUnit *Op);
1726   void AddPseudoTwoAddrDeps();
1727   void PrescheduleNodesWithMultipleUses();
1728   void CalculateSethiUllmanNumbers();
1729 };
1730
1731 template<class SF>
1732 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1733   std::vector<SUnit *>::iterator Best = Q.begin();
1734   for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
1735          E = Q.end(); I != E; ++I)
1736     if (Picker(*Best, *I))
1737       Best = I;
1738   SUnit *V = *Best;
1739   if (Best != std::prev(Q.end()))
1740     std::swap(*Best, Q.back());
1741   Q.pop_back();
1742   return V;
1743 }
1744
1745 template<class SF>
1746 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1747 #ifndef NDEBUG
1748   if (DAG->StressSched) {
1749     reverse_sort<SF> RPicker(Picker);
1750     return popFromQueueImpl(Q, RPicker);
1751   }
1752 #endif
1753   (void)DAG;
1754   return popFromQueueImpl(Q, Picker);
1755 }
1756
1757 template<class SF>
1758 class RegReductionPriorityQueue : public RegReductionPQBase {
1759   SF Picker;
1760
1761 public:
1762   RegReductionPriorityQueue(MachineFunction &mf,
1763                             bool tracksrp,
1764                             bool srcorder,
1765                             const TargetInstrInfo *tii,
1766                             const TargetRegisterInfo *tri,
1767                             const TargetLowering *tli)
1768     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1769                          tii, tri, tli),
1770       Picker(this) {}
1771
1772   bool isBottomUp() const override { return SF::IsBottomUp; }
1773
1774   bool isReady(SUnit *U) const override {
1775     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1776   }
1777
1778   SUnit *pop() override {
1779     if (Queue.empty()) return nullptr;
1780
1781     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1782     V->NodeQueueId = 0;
1783     return V;
1784   }
1785
1786 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1787   LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
1788     // Emulate pop() without clobbering NodeQueueIds.
1789     std::vector<SUnit*> DumpQueue = Queue;
1790     SF DumpPicker = Picker;
1791     while (!DumpQueue.empty()) {
1792       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1793       dbgs() << "Height " << SU->getHeight() << ": ";
1794       SU->dump(DAG);
1795     }
1796   }
1797 #endif
1798 };
1799
1800 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1801 BURegReductionPriorityQueue;
1802
1803 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1804 SrcRegReductionPriorityQueue;
1805
1806 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1807 HybridBURRPriorityQueue;
1808
1809 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1810 ILPBURRPriorityQueue;
1811 } // end anonymous namespace
1812
1813 //===----------------------------------------------------------------------===//
1814 //           Static Node Priority for Register Pressure Reduction
1815 //===----------------------------------------------------------------------===//
1816
1817 // Check for special nodes that bypass scheduling heuristics.
1818 // Currently this pushes TokenFactor nodes down, but may be used for other
1819 // pseudo-ops as well.
1820 //
1821 // Return -1 to schedule right above left, 1 for left above right.
1822 // Return 0 if no bias exists.
1823 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1824   bool LSchedLow = left->isScheduleLow;
1825   bool RSchedLow = right->isScheduleLow;
1826   if (LSchedLow != RSchedLow)
1827     return LSchedLow < RSchedLow ? 1 : -1;
1828   return 0;
1829 }
1830
1831 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1832 /// Smaller number is the higher priority.
1833 static unsigned
1834 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1835   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1836   if (SethiUllmanNumber != 0)
1837     return SethiUllmanNumber;
1838
1839   unsigned Extra = 0;
1840   for (const SDep &Pred : SU->Preds) {
1841     if (Pred.isCtrl()) continue;  // ignore chain preds
1842     SUnit *PredSU = Pred.getSUnit();
1843     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1844     if (PredSethiUllman > SethiUllmanNumber) {
1845       SethiUllmanNumber = PredSethiUllman;
1846       Extra = 0;
1847     } else if (PredSethiUllman == SethiUllmanNumber)
1848       ++Extra;
1849   }
1850
1851   SethiUllmanNumber += Extra;
1852
1853   if (SethiUllmanNumber == 0)
1854     SethiUllmanNumber = 1;
1855
1856   return SethiUllmanNumber;
1857 }
1858
1859 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1860 /// scheduling units.
1861 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1862   SethiUllmanNumbers.assign(SUnits->size(), 0);
1863
1864   for (const SUnit &SU : *SUnits)
1865     CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
1866 }
1867
1868 void RegReductionPQBase::addNode(const SUnit *SU) {
1869   unsigned SUSize = SethiUllmanNumbers.size();
1870   if (SUnits->size() > SUSize)
1871     SethiUllmanNumbers.resize(SUSize*2, 0);
1872   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1873 }
1874
1875 void RegReductionPQBase::updateNode(const SUnit *SU) {
1876   SethiUllmanNumbers[SU->NodeNum] = 0;
1877   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1878 }
1879
1880 // Lower priority means schedule further down. For bottom-up scheduling, lower
1881 // priority SUs are scheduled before higher priority SUs.
1882 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1883   assert(SU->NodeNum < SethiUllmanNumbers.size());
1884   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1885   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1886     // CopyToReg should be close to its uses to facilitate coalescing and
1887     // avoid spilling.
1888     return 0;
1889   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1890       Opc == TargetOpcode::SUBREG_TO_REG ||
1891       Opc == TargetOpcode::INSERT_SUBREG)
1892     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1893     // close to their uses to facilitate coalescing.
1894     return 0;
1895   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1896     // If SU does not have a register use, i.e. it doesn't produce a value
1897     // that would be consumed (e.g. store), then it terminates a chain of
1898     // computation.  Give it a large SethiUllman number so it will be
1899     // scheduled right before its predecessors that it doesn't lengthen
1900     // their live ranges.
1901     return 0xffff;
1902   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1903     // If SU does not have a register def, schedule it close to its uses
1904     // because it does not lengthen any live ranges.
1905     return 0;
1906 #if 1
1907   return SethiUllmanNumbers[SU->NodeNum];
1908 #else
1909   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1910   if (SU->isCallOp) {
1911     // FIXME: This assumes all of the defs are used as call operands.
1912     int NP = (int)Priority - SU->getNode()->getNumValues();
1913     return (NP > 0) ? NP : 0;
1914   }
1915   return Priority;
1916 #endif
1917 }
1918
1919 //===----------------------------------------------------------------------===//
1920 //                     Register Pressure Tracking
1921 //===----------------------------------------------------------------------===//
1922
1923 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1924 LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
1925   for (const TargetRegisterClass *RC : TRI->regclasses()) {
1926     unsigned Id = RC->getID();
1927     unsigned RP = RegPressure[Id];
1928     if (!RP) continue;
1929     DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
1930           << RegLimit[Id] << '\n');
1931   }
1932 }
1933 #endif
1934
1935 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1936   if (!TLI)
1937     return false;
1938
1939   for (const SDep &Pred : SU->Preds) {
1940     if (Pred.isCtrl())
1941       continue;
1942     SUnit *PredSU = Pred.getSUnit();
1943     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1944     // to cover the number of registers defined (they are all live).
1945     if (PredSU->NumRegDefsLeft == 0) {
1946       continue;
1947     }
1948     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1949          RegDefPos.IsValid(); RegDefPos.Advance()) {
1950       unsigned RCId, Cost;
1951       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
1952
1953       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1954         return true;
1955     }
1956   }
1957   return false;
1958 }
1959
1960 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1961   const SDNode *N = SU->getNode();
1962
1963   if (!N->isMachineOpcode() || !SU->NumSuccs)
1964     return false;
1965
1966   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1967   for (unsigned i = 0; i != NumDefs; ++i) {
1968     MVT VT = N->getSimpleValueType(i);
1969     if (!N->hasAnyUseOfValue(i))
1970       continue;
1971     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1972     if (RegPressure[RCId] >= RegLimit[RCId])
1973       return true;
1974   }
1975   return false;
1976 }
1977
1978 // Compute the register pressure contribution by this instruction by count up
1979 // for uses that are not live and down for defs. Only count register classes
1980 // that are already under high pressure. As a side effect, compute the number of
1981 // uses of registers that are already live.
1982 //
1983 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1984 // so could probably be factored.
1985 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1986   LiveUses = 0;
1987   int PDiff = 0;
1988   for (const SDep &Pred : SU->Preds) {
1989     if (Pred.isCtrl())
1990       continue;
1991     SUnit *PredSU = Pred.getSUnit();
1992     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1993     // to cover the number of registers defined (they are all live).
1994     if (PredSU->NumRegDefsLeft == 0) {
1995       if (PredSU->getNode()->isMachineOpcode())
1996         ++LiveUses;
1997       continue;
1998     }
1999     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2000          RegDefPos.IsValid(); RegDefPos.Advance()) {
2001       MVT VT = RegDefPos.GetValue();
2002       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2003       if (RegPressure[RCId] >= RegLimit[RCId])
2004         ++PDiff;
2005     }
2006   }
2007   const SDNode *N = SU->getNode();
2008
2009   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
2010     return PDiff;
2011
2012   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2013   for (unsigned i = 0; i != NumDefs; ++i) {
2014     MVT VT = N->getSimpleValueType(i);
2015     if (!N->hasAnyUseOfValue(i))
2016       continue;
2017     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2018     if (RegPressure[RCId] >= RegLimit[RCId])
2019       --PDiff;
2020   }
2021   return PDiff;
2022 }
2023
2024 void RegReductionPQBase::scheduledNode(SUnit *SU) {
2025   if (!TracksRegPressure)
2026     return;
2027
2028   if (!SU->getNode())
2029     return;
2030
2031   for (const SDep &Pred : SU->Preds) {
2032     if (Pred.isCtrl())
2033       continue;
2034     SUnit *PredSU = Pred.getSUnit();
2035     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2036     // to cover the number of registers defined (they are all live).
2037     if (PredSU->NumRegDefsLeft == 0) {
2038       continue;
2039     }
2040     // FIXME: The ScheduleDAG currently loses information about which of a
2041     // node's values is consumed by each dependence. Consequently, if the node
2042     // defines multiple register classes, we don't know which to pressurize
2043     // here. Instead the following loop consumes the register defs in an
2044     // arbitrary order. At least it handles the common case of clustered loads
2045     // to the same class. For precise liveness, each SDep needs to indicate the
2046     // result number. But that tightly couples the ScheduleDAG with the
2047     // SelectionDAG making updates tricky. A simpler hack would be to attach a
2048     // value type or register class to SDep.
2049     //
2050     // The most important aspect of register tracking is balancing the increase
2051     // here with the reduction further below. Note that this SU may use multiple
2052     // defs in PredSU. The can't be determined here, but we've already
2053     // compensated by reducing NumRegDefsLeft in PredSU during
2054     // ScheduleDAGSDNodes::AddSchedEdges.
2055     --PredSU->NumRegDefsLeft;
2056     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2057     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2058          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2059       if (SkipRegDefs)
2060         continue;
2061
2062       unsigned RCId, Cost;
2063       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2064       RegPressure[RCId] += Cost;
2065       break;
2066     }
2067   }
2068
2069   // We should have this assert, but there may be dead SDNodes that never
2070   // materialize as SUnits, so they don't appear to generate liveness.
2071   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2072   int SkipRegDefs = (int)SU->NumRegDefsLeft;
2073   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2074        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2075     if (SkipRegDefs > 0)
2076       continue;
2077     unsigned RCId, Cost;
2078     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2079     if (RegPressure[RCId] < Cost) {
2080       // Register pressure tracking is imprecise. This can happen. But we try
2081       // hard not to let it happen because it likely results in poor scheduling.
2082       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
2083       RegPressure[RCId] = 0;
2084     }
2085     else {
2086       RegPressure[RCId] -= Cost;
2087     }
2088   }
2089   DEBUG(dumpRegPressure());
2090 }
2091
2092 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2093   if (!TracksRegPressure)
2094     return;
2095
2096   const SDNode *N = SU->getNode();
2097   if (!N) return;
2098
2099   if (!N->isMachineOpcode()) {
2100     if (N->getOpcode() != ISD::CopyToReg)
2101       return;
2102   } else {
2103     unsigned Opc = N->getMachineOpcode();
2104     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2105         Opc == TargetOpcode::INSERT_SUBREG ||
2106         Opc == TargetOpcode::SUBREG_TO_REG ||
2107         Opc == TargetOpcode::REG_SEQUENCE ||
2108         Opc == TargetOpcode::IMPLICIT_DEF)
2109       return;
2110   }
2111
2112   for (const SDep &Pred : SU->Preds) {
2113     if (Pred.isCtrl())
2114       continue;
2115     SUnit *PredSU = Pred.getSUnit();
2116     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2117     // counts data deps.
2118     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2119       continue;
2120     const SDNode *PN = PredSU->getNode();
2121     if (!PN->isMachineOpcode()) {
2122       if (PN->getOpcode() == ISD::CopyFromReg) {
2123         MVT VT = PN->getSimpleValueType(0);
2124         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2125         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2126       }
2127       continue;
2128     }
2129     unsigned POpc = PN->getMachineOpcode();
2130     if (POpc == TargetOpcode::IMPLICIT_DEF)
2131       continue;
2132     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2133         POpc == TargetOpcode::INSERT_SUBREG ||
2134         POpc == TargetOpcode::SUBREG_TO_REG) {
2135       MVT VT = PN->getSimpleValueType(0);
2136       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2137       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2138       continue;
2139     }
2140     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2141     for (unsigned i = 0; i != NumDefs; ++i) {
2142       MVT VT = PN->getSimpleValueType(i);
2143       if (!PN->hasAnyUseOfValue(i))
2144         continue;
2145       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2146       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2147         // Register pressure tracking is imprecise. This can happen.
2148         RegPressure[RCId] = 0;
2149       else
2150         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2151     }
2152   }
2153
2154   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2155   // may transfer data dependencies to CopyToReg.
2156   if (SU->NumSuccs && N->isMachineOpcode()) {
2157     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2158     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2159       MVT VT = N->getSimpleValueType(i);
2160       if (VT == MVT::Glue || VT == MVT::Other)
2161         continue;
2162       if (!N->hasAnyUseOfValue(i))
2163         continue;
2164       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2165       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2166     }
2167   }
2168
2169   DEBUG(dumpRegPressure());
2170 }
2171
2172 //===----------------------------------------------------------------------===//
2173 //           Dynamic Node Priority for Register Pressure Reduction
2174 //===----------------------------------------------------------------------===//
2175
2176 /// closestSucc - Returns the scheduled cycle of the successor which is
2177 /// closest to the current cycle.
2178 static unsigned closestSucc(const SUnit *SU) {
2179   unsigned MaxHeight = 0;
2180   for (const SDep &Succ : SU->Succs) {
2181     if (Succ.isCtrl()) continue;  // ignore chain succs
2182     unsigned Height = Succ.getSUnit()->getHeight();
2183     // If there are bunch of CopyToRegs stacked up, they should be considered
2184     // to be at the same position.
2185     if (Succ.getSUnit()->getNode() &&
2186         Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2187       Height = closestSucc(Succ.getSUnit())+1;
2188     if (Height > MaxHeight)
2189       MaxHeight = Height;
2190   }
2191   return MaxHeight;
2192 }
2193
2194 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2195 /// for scratch registers, i.e. number of data dependencies.
2196 static unsigned calcMaxScratches(const SUnit *SU) {
2197   unsigned Scratches = 0;
2198   for (const SDep &Pred : SU->Preds) {
2199     if (Pred.isCtrl()) continue;  // ignore chain preds
2200     Scratches++;
2201   }
2202   return Scratches;
2203 }
2204
2205 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2206 /// CopyFromReg from a virtual register.
2207 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2208   bool RetVal = false;
2209   for (const SDep &Pred : SU->Preds) {
2210     if (Pred.isCtrl()) continue;
2211     const SUnit *PredSU = Pred.getSUnit();
2212     if (PredSU->getNode() &&
2213         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2214       unsigned Reg =
2215         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2216       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2217         RetVal = true;
2218         continue;
2219       }
2220     }
2221     return false;
2222   }
2223   return RetVal;
2224 }
2225
2226 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2227 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2228 /// it has no other use. It should be scheduled closer to the terminator.
2229 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2230   bool RetVal = false;
2231   for (const SDep &Succ : SU->Succs) {
2232     if (Succ.isCtrl()) continue;
2233     const SUnit *SuccSU = Succ.getSUnit();
2234     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2235       unsigned Reg =
2236         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2237       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2238         RetVal = true;
2239         continue;
2240       }
2241     }
2242     return false;
2243   }
2244   return RetVal;
2245 }
2246
2247 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2248 // set isVRegCycle for its CopyFromReg operands.
2249 //
2250 // This is only relevant for single-block loops, in which case the VRegCycle
2251 // node is likely an induction variable in which the operand and target virtual
2252 // registers should be coalesced (e.g. pre/post increment values). Setting the
2253 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2254 // CopyFromReg so that this node becomes the virtual register "kill". This
2255 // avoids interference between the values live in and out of the block and
2256 // eliminates a copy inside the loop.
2257 static void initVRegCycle(SUnit *SU) {
2258   if (DisableSchedVRegCycle)
2259     return;
2260
2261   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2262     return;
2263
2264   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2265
2266   SU->isVRegCycle = true;
2267
2268   for (const SDep &Pred : SU->Preds) {
2269     if (Pred.isCtrl()) continue;
2270     Pred.getSUnit()->isVRegCycle = true;
2271   }
2272 }
2273
2274 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2275 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2276 static void resetVRegCycle(SUnit *SU) {
2277   if (!SU->isVRegCycle)
2278     return;
2279
2280   for (const SDep &Pred : SU->Preds) {
2281     if (Pred.isCtrl()) continue;  // ignore chain preds
2282     SUnit *PredSU = Pred.getSUnit();
2283     if (PredSU->isVRegCycle) {
2284       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2285              "VRegCycle def must be CopyFromReg");
2286       Pred.getSUnit()->isVRegCycle = false;
2287     }
2288   }
2289 }
2290
2291 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2292 // means a node that defines the VRegCycle has not been scheduled yet.
2293 static bool hasVRegCycleUse(const SUnit *SU) {
2294   // If this SU also defines the VReg, don't hoist it as a "use".
2295   if (SU->isVRegCycle)
2296     return false;
2297
2298   for (const SDep &Pred : SU->Preds) {
2299     if (Pred.isCtrl()) continue;  // ignore chain preds
2300     if (Pred.getSUnit()->isVRegCycle &&
2301         Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2302       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
2303       return true;
2304     }
2305   }
2306   return false;
2307 }
2308
2309 // Check for either a dependence (latency) or resource (hazard) stall.
2310 //
2311 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2312 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2313   if ((int)SPQ->getCurCycle() < Height) return true;
2314   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2315       != ScheduleHazardRecognizer::NoHazard)
2316     return true;
2317   return false;
2318 }
2319
2320 // Return -1 if left has higher priority, 1 if right has higher priority.
2321 // Return 0 if latency-based priority is equivalent.
2322 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2323                             RegReductionPQBase *SPQ) {
2324   // Scheduling an instruction that uses a VReg whose postincrement has not yet
2325   // been scheduled will induce a copy. Model this as an extra cycle of latency.
2326   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2327   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2328   int LHeight = (int)left->getHeight() + LPenalty;
2329   int RHeight = (int)right->getHeight() + RPenalty;
2330
2331   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2332     BUHasStall(left, LHeight, SPQ);
2333   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2334     BUHasStall(right, RHeight, SPQ);
2335
2336   // If scheduling one of the node will cause a pipeline stall, delay it.
2337   // If scheduling either one of the node will cause a pipeline stall, sort
2338   // them according to their height.
2339   if (LStall) {
2340     if (!RStall)
2341       return 1;
2342     if (LHeight != RHeight)
2343       return LHeight > RHeight ? 1 : -1;
2344   } else if (RStall)
2345     return -1;
2346
2347   // If either node is scheduling for latency, sort them by height/depth
2348   // and latency.
2349   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2350                      right->SchedulingPref == Sched::ILP)) {
2351     // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2352     // is enabled, grouping instructions by cycle, then its height is already
2353     // covered so only its depth matters. We also reach this point if both stall
2354     // but have the same height.
2355     if (!SPQ->getHazardRec()->isEnabled()) {
2356       if (LHeight != RHeight)
2357         return LHeight > RHeight ? 1 : -1;
2358     }
2359     int LDepth = left->getDepth() - LPenalty;
2360     int RDepth = right->getDepth() - RPenalty;
2361     if (LDepth != RDepth) {
2362       DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
2363             << ") depth " << LDepth << " vs SU (" << right->NodeNum
2364             << ") depth " << RDepth << "\n");
2365       return LDepth < RDepth ? 1 : -1;
2366     }
2367     if (left->Latency != right->Latency)
2368       return left->Latency > right->Latency ? 1 : -1;
2369   }
2370   return 0;
2371 }
2372
2373 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2374   // Schedule physical register definitions close to their use. This is
2375   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2376   // long as shortening physreg live ranges is generally good, we can defer
2377   // creating a subtarget hook.
2378   if (!DisableSchedPhysRegJoin) {
2379     bool LHasPhysReg = left->hasPhysRegDefs;
2380     bool RHasPhysReg = right->hasPhysRegDefs;
2381     if (LHasPhysReg != RHasPhysReg) {
2382       #ifndef NDEBUG
2383       static const char *const PhysRegMsg[] = { " has no physreg",
2384                                                 " defines a physreg" };
2385       #endif
2386       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
2387             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2388             << PhysRegMsg[RHasPhysReg] << "\n");
2389       return LHasPhysReg < RHasPhysReg;
2390     }
2391   }
2392
2393   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2394   unsigned LPriority = SPQ->getNodePriority(left);
2395   unsigned RPriority = SPQ->getNodePriority(right);
2396
2397   // Be really careful about hoisting call operands above previous calls.
2398   // Only allows it if it would reduce register pressure.
2399   if (left->isCall && right->isCallOp) {
2400     unsigned RNumVals = right->getNode()->getNumValues();
2401     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2402   }
2403   if (right->isCall && left->isCallOp) {
2404     unsigned LNumVals = left->getNode()->getNumValues();
2405     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2406   }
2407
2408   if (LPriority != RPriority)
2409     return LPriority > RPriority;
2410
2411   // One or both of the nodes are calls and their sethi-ullman numbers are the
2412   // same, then keep source order.
2413   if (left->isCall || right->isCall) {
2414     unsigned LOrder = SPQ->getNodeOrdering(left);
2415     unsigned ROrder = SPQ->getNodeOrdering(right);
2416
2417     // Prefer an ordering where the lower the non-zero order number, the higher
2418     // the preference.
2419     if ((LOrder || ROrder) && LOrder != ROrder)
2420       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2421   }
2422
2423   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2424   // e.g.
2425   // t1 = op t2, c1
2426   // t3 = op t4, c2
2427   //
2428   // and the following instructions are both ready.
2429   // t2 = op c3
2430   // t4 = op c4
2431   //
2432   // Then schedule t2 = op first.
2433   // i.e.
2434   // t4 = op c4
2435   // t2 = op c3
2436   // t1 = op t2, c1
2437   // t3 = op t4, c2
2438   //
2439   // This creates more short live intervals.
2440   unsigned LDist = closestSucc(left);
2441   unsigned RDist = closestSucc(right);
2442   if (LDist != RDist)
2443     return LDist < RDist;
2444
2445   // How many registers becomes live when the node is scheduled.
2446   unsigned LScratch = calcMaxScratches(left);
2447   unsigned RScratch = calcMaxScratches(right);
2448   if (LScratch != RScratch)
2449     return LScratch > RScratch;
2450
2451   // Comparing latency against a call makes little sense unless the node
2452   // is register pressure-neutral.
2453   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2454     return (left->NodeQueueId > right->NodeQueueId);
2455
2456   // Do not compare latencies when one or both of the nodes are calls.
2457   if (!DisableSchedCycles &&
2458       !(left->isCall || right->isCall)) {
2459     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2460     if (result != 0)
2461       return result > 0;
2462   }
2463   else {
2464     if (left->getHeight() != right->getHeight())
2465       return left->getHeight() > right->getHeight();
2466
2467     if (left->getDepth() != right->getDepth())
2468       return left->getDepth() < right->getDepth();
2469   }
2470
2471   assert(left->NodeQueueId && right->NodeQueueId &&
2472          "NodeQueueId cannot be zero");
2473   return (left->NodeQueueId > right->NodeQueueId);
2474 }
2475
2476 // Bottom up
2477 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2478   if (int res = checkSpecialNodes(left, right))
2479     return res > 0;
2480
2481   return BURRSort(left, right, SPQ);
2482 }
2483
2484 // Source order, otherwise bottom up.
2485 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2486   if (int res = checkSpecialNodes(left, right))
2487     return res > 0;
2488
2489   unsigned LOrder = SPQ->getNodeOrdering(left);
2490   unsigned ROrder = SPQ->getNodeOrdering(right);
2491
2492   // Prefer an ordering where the lower the non-zero order number, the higher
2493   // the preference.
2494   if ((LOrder || ROrder) && LOrder != ROrder)
2495     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2496
2497   return BURRSort(left, right, SPQ);
2498 }
2499
2500 // If the time between now and when the instruction will be ready can cover
2501 // the spill code, then avoid adding it to the ready queue. This gives long
2502 // stalls highest priority and allows hoisting across calls. It should also
2503 // speed up processing the available queue.
2504 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2505   static const unsigned ReadyDelay = 3;
2506
2507   if (SPQ->MayReduceRegPressure(SU)) return true;
2508
2509   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2510
2511   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2512       != ScheduleHazardRecognizer::NoHazard)
2513     return false;
2514
2515   return true;
2516 }
2517
2518 // Return true if right should be scheduled with higher priority than left.
2519 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2520   if (int res = checkSpecialNodes(left, right))
2521     return res > 0;
2522
2523   if (left->isCall || right->isCall)
2524     // No way to compute latency of calls.
2525     return BURRSort(left, right, SPQ);
2526
2527   bool LHigh = SPQ->HighRegPressure(left);
2528   bool RHigh = SPQ->HighRegPressure(right);
2529   // Avoid causing spills. If register pressure is high, schedule for
2530   // register pressure reduction.
2531   if (LHigh && !RHigh) {
2532     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
2533           << right->NodeNum << ")\n");
2534     return true;
2535   }
2536   else if (!LHigh && RHigh) {
2537     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
2538           << left->NodeNum << ")\n");
2539     return false;
2540   }
2541   if (!LHigh && !RHigh) {
2542     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2543     if (result != 0)
2544       return result > 0;
2545   }
2546   return BURRSort(left, right, SPQ);
2547 }
2548
2549 // Schedule as many instructions in each cycle as possible. So don't make an
2550 // instruction available unless it is ready in the current cycle.
2551 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2552   if (SU->getHeight() > CurCycle) return false;
2553
2554   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2555       != ScheduleHazardRecognizer::NoHazard)
2556     return false;
2557
2558   return true;
2559 }
2560
2561 static bool canEnableCoalescing(SUnit *SU) {
2562   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2563   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2564     // CopyToReg should be close to its uses to facilitate coalescing and
2565     // avoid spilling.
2566     return true;
2567
2568   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2569       Opc == TargetOpcode::SUBREG_TO_REG ||
2570       Opc == TargetOpcode::INSERT_SUBREG)
2571     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2572     // close to their uses to facilitate coalescing.
2573     return true;
2574
2575   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2576     // If SU does not have a register def, schedule it close to its uses
2577     // because it does not lengthen any live ranges.
2578     return true;
2579
2580   return false;
2581 }
2582
2583 // list-ilp is currently an experimental scheduler that allows various
2584 // heuristics to be enabled prior to the normal register reduction logic.
2585 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2586   if (int res = checkSpecialNodes(left, right))
2587     return res > 0;
2588
2589   if (left->isCall || right->isCall)
2590     // No way to compute latency of calls.
2591     return BURRSort(left, right, SPQ);
2592
2593   unsigned LLiveUses = 0, RLiveUses = 0;
2594   int LPDiff = 0, RPDiff = 0;
2595   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2596     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2597     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2598   }
2599   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2600     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2601           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2602     return LPDiff > RPDiff;
2603   }
2604
2605   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2606     bool LReduce = canEnableCoalescing(left);
2607     bool RReduce = canEnableCoalescing(right);
2608     if (LReduce && !RReduce) return false;
2609     if (RReduce && !LReduce) return true;
2610   }
2611
2612   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2613     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2614           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2615     return LLiveUses < RLiveUses;
2616   }
2617
2618   if (!DisableSchedStalls) {
2619     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2620     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2621     if (LStall != RStall)
2622       return left->getHeight() > right->getHeight();
2623   }
2624
2625   if (!DisableSchedCriticalPath) {
2626     int spread = (int)left->getDepth() - (int)right->getDepth();
2627     if (std::abs(spread) > MaxReorderWindow) {
2628       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2629             << left->getDepth() << " != SU(" << right->NodeNum << "): "
2630             << right->getDepth() << "\n");
2631       return left->getDepth() < right->getDepth();
2632     }
2633   }
2634
2635   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2636     int spread = (int)left->getHeight() - (int)right->getHeight();
2637     if (std::abs(spread) > MaxReorderWindow)
2638       return left->getHeight() > right->getHeight();
2639   }
2640
2641   return BURRSort(left, right, SPQ);
2642 }
2643
2644 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2645   SUnits = &sunits;
2646   // Add pseudo dependency edges for two-address nodes.
2647   if (!Disable2AddrHack)
2648     AddPseudoTwoAddrDeps();
2649   // Reroute edges to nodes with multiple uses.
2650   if (!TracksRegPressure && !SrcOrder)
2651     PrescheduleNodesWithMultipleUses();
2652   // Calculate node priorities.
2653   CalculateSethiUllmanNumbers();
2654
2655   // For single block loops, mark nodes that look like canonical IV increments.
2656   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2657     for (SUnit &SU : sunits)
2658       initVRegCycle(&SU);
2659 }
2660
2661 //===----------------------------------------------------------------------===//
2662 //                    Preschedule for Register Pressure
2663 //===----------------------------------------------------------------------===//
2664
2665 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2666   if (SU->isTwoAddress) {
2667     unsigned Opc = SU->getNode()->getMachineOpcode();
2668     const MCInstrDesc &MCID = TII->get(Opc);
2669     unsigned NumRes = MCID.getNumDefs();
2670     unsigned NumOps = MCID.getNumOperands() - NumRes;
2671     for (unsigned i = 0; i != NumOps; ++i) {
2672       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2673         SDNode *DU = SU->getNode()->getOperand(i).getNode();
2674         if (DU->getNodeId() != -1 &&
2675             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2676           return true;
2677       }
2678     }
2679   }
2680   return false;
2681 }
2682
2683 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2684 /// successor's explicit physregs whose definition can reach DepSU.
2685 /// i.e. DepSU should not be scheduled above SU.
2686 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2687                                          ScheduleDAGRRList *scheduleDAG,
2688                                          const TargetInstrInfo *TII,
2689                                          const TargetRegisterInfo *TRI) {
2690   const MCPhysReg *ImpDefs
2691     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2692   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2693   if(!ImpDefs && !RegMask)
2694     return false;
2695
2696   for (const SDep &Succ : SU->Succs) {
2697     SUnit *SuccSU = Succ.getSUnit();
2698     for (const SDep &SuccPred : SuccSU->Preds) {
2699       if (!SuccPred.isAssignedRegDep())
2700         continue;
2701
2702       if (RegMask &&
2703           MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
2704           scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2705         return true;
2706
2707       if (ImpDefs)
2708         for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2709           // Return true if SU clobbers this physical register use and the
2710           // definition of the register reaches from DepSU. IsReachable queries
2711           // a topological forward sort of the DAG (following the successors).
2712           if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
2713               scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2714             return true;
2715     }
2716   }
2717   return false;
2718 }
2719
2720 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2721 /// physical register defs.
2722 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2723                                   const TargetInstrInfo *TII,
2724                                   const TargetRegisterInfo *TRI) {
2725   SDNode *N = SuccSU->getNode();
2726   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2727   const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2728   assert(ImpDefs && "Caller should check hasPhysRegDefs");
2729   for (const SDNode *SUNode = SU->getNode(); SUNode;
2730        SUNode = SUNode->getGluedNode()) {
2731     if (!SUNode->isMachineOpcode())
2732       continue;
2733     const MCPhysReg *SUImpDefs =
2734       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2735     const uint32_t *SURegMask = getNodeRegMask(SUNode);
2736     if (!SUImpDefs && !SURegMask)
2737       continue;
2738     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2739       MVT VT = N->getSimpleValueType(i);
2740       if (VT == MVT::Glue || VT == MVT::Other)
2741         continue;
2742       if (!N->hasAnyUseOfValue(i))
2743         continue;
2744       unsigned Reg = ImpDefs[i - NumDefs];
2745       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2746         return true;
2747       if (!SUImpDefs)
2748         continue;
2749       for (;*SUImpDefs; ++SUImpDefs) {
2750         unsigned SUReg = *SUImpDefs;
2751         if (TRI->regsOverlap(Reg, SUReg))
2752           return true;
2753       }
2754     }
2755   }
2756   return false;
2757 }
2758
2759 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2760 /// are not handled well by the general register pressure reduction
2761 /// heuristics. When presented with code like this:
2762 ///
2763 ///      N
2764 ///    / |
2765 ///   /  |
2766 ///  U  store
2767 ///  |
2768 /// ...
2769 ///
2770 /// the heuristics tend to push the store up, but since the
2771 /// operand of the store has another use (U), this would increase
2772 /// the length of that other use (the U->N edge).
2773 ///
2774 /// This function transforms code like the above to route U's
2775 /// dependence through the store when possible, like this:
2776 ///
2777 ///      N
2778 ///      ||
2779 ///      ||
2780 ///     store
2781 ///       |
2782 ///       U
2783 ///       |
2784 ///      ...
2785 ///
2786 /// This results in the store being scheduled immediately
2787 /// after N, which shortens the U->N live range, reducing
2788 /// register pressure.
2789 ///
2790 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2791   // Visit all the nodes in topological order, working top-down.
2792   for (SUnit &SU : *SUnits) {
2793     // For now, only look at nodes with no data successors, such as stores.
2794     // These are especially important, due to the heuristics in
2795     // getNodePriority for nodes with no data successors.
2796     if (SU.NumSuccs != 0)
2797       continue;
2798     // For now, only look at nodes with exactly one data predecessor.
2799     if (SU.NumPreds != 1)
2800       continue;
2801     // Avoid prescheduling copies to virtual registers, which don't behave
2802     // like other nodes from the perspective of scheduling heuristics.
2803     if (SDNode *N = SU.getNode())
2804       if (N->getOpcode() == ISD::CopyToReg &&
2805           TargetRegisterInfo::isVirtualRegister
2806             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2807         continue;
2808
2809     // Locate the single data predecessor.
2810     SUnit *PredSU = nullptr;
2811     for (const SDep &Pred : SU.Preds)
2812       if (!Pred.isCtrl()) {
2813         PredSU = Pred.getSUnit();
2814         break;
2815       }
2816     assert(PredSU);
2817
2818     // Don't rewrite edges that carry physregs, because that requires additional
2819     // support infrastructure.
2820     if (PredSU->hasPhysRegDefs)
2821       continue;
2822     // Short-circuit the case where SU is PredSU's only data successor.
2823     if (PredSU->NumSuccs == 1)
2824       continue;
2825     // Avoid prescheduling to copies from virtual registers, which don't behave
2826     // like other nodes from the perspective of scheduling heuristics.
2827     if (SDNode *N = SU.getNode())
2828       if (N->getOpcode() == ISD::CopyFromReg &&
2829           TargetRegisterInfo::isVirtualRegister
2830             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2831         continue;
2832
2833     // Perform checks on the successors of PredSU.
2834     for (const SDep &PredSucc : PredSU->Succs) {
2835       SUnit *PredSuccSU = PredSucc.getSUnit();
2836       if (PredSuccSU == &SU) continue;
2837       // If PredSU has another successor with no data successors, for
2838       // now don't attempt to choose either over the other.
2839       if (PredSuccSU->NumSuccs == 0)
2840         goto outer_loop_continue;
2841       // Don't break physical register dependencies.
2842       if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2843         if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
2844           goto outer_loop_continue;
2845       // Don't introduce graph cycles.
2846       if (scheduleDAG->IsReachable(&SU, PredSuccSU))
2847         goto outer_loop_continue;
2848     }
2849
2850     // Ok, the transformation is safe and the heuristics suggest it is
2851     // profitable. Update the graph.
2852     DEBUG(dbgs() << "    Prescheduling SU #" << SU.NodeNum
2853                  << " next to PredSU #" << PredSU->NodeNum
2854                  << " to guide scheduling in the presence of multiple uses\n");
2855     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2856       SDep Edge = PredSU->Succs[i];
2857       assert(!Edge.isAssignedRegDep());
2858       SUnit *SuccSU = Edge.getSUnit();
2859       if (SuccSU != &SU) {
2860         Edge.setSUnit(PredSU);
2861         scheduleDAG->RemovePred(SuccSU, Edge);
2862         scheduleDAG->AddPred(&SU, Edge);
2863         Edge.setSUnit(&SU);
2864         scheduleDAG->AddPred(SuccSU, Edge);
2865         --i;
2866       }
2867     }
2868   outer_loop_continue:;
2869   }
2870 }
2871
2872 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2873 /// it as a def&use operand. Add a pseudo control edge from it to the other
2874 /// node (if it won't create a cycle) so the two-address one will be scheduled
2875 /// first (lower in the schedule). If both nodes are two-address, favor the
2876 /// one that has a CopyToReg use (more likely to be a loop induction update).
2877 /// If both are two-address, but one is commutable while the other is not
2878 /// commutable, favor the one that's not commutable.
2879 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2880   for (SUnit &SU : *SUnits) {
2881     if (!SU.isTwoAddress)
2882       continue;
2883
2884     SDNode *Node = SU.getNode();
2885     if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
2886       continue;
2887
2888     bool isLiveOut = hasOnlyLiveOutUses(&SU);
2889     unsigned Opc = Node->getMachineOpcode();
2890     const MCInstrDesc &MCID = TII->get(Opc);
2891     unsigned NumRes = MCID.getNumDefs();
2892     unsigned NumOps = MCID.getNumOperands() - NumRes;
2893     for (unsigned j = 0; j != NumOps; ++j) {
2894       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2895         continue;
2896       SDNode *DU = SU.getNode()->getOperand(j).getNode();
2897       if (DU->getNodeId() == -1)
2898         continue;
2899       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2900       if (!DUSU)
2901         continue;
2902       for (const SDep &Succ : DUSU->Succs) {
2903         if (Succ.isCtrl())
2904           continue;
2905         SUnit *SuccSU = Succ.getSUnit();
2906         if (SuccSU == &SU)
2907           continue;
2908         // Be conservative. Ignore if nodes aren't at roughly the same
2909         // depth and height.
2910         if (SuccSU->getHeight() < SU.getHeight() &&
2911             (SU.getHeight() - SuccSU->getHeight()) > 1)
2912           continue;
2913         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2914         // constrains whatever is using the copy, instead of the copy
2915         // itself. In the case that the copy is coalesced, this
2916         // preserves the intent of the pseudo two-address heurietics.
2917         while (SuccSU->Succs.size() == 1 &&
2918                SuccSU->getNode()->isMachineOpcode() &&
2919                SuccSU->getNode()->getMachineOpcode() ==
2920                  TargetOpcode::COPY_TO_REGCLASS)
2921           SuccSU = SuccSU->Succs.front().getSUnit();
2922         // Don't constrain non-instruction nodes.
2923         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2924           continue;
2925         // Don't constrain nodes with physical register defs if the
2926         // predecessor can clobber them.
2927         if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
2928           if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
2929             continue;
2930         }
2931         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2932         // these may be coalesced away. We want them close to their uses.
2933         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2934         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2935             SuccOpc == TargetOpcode::INSERT_SUBREG ||
2936             SuccOpc == TargetOpcode::SUBREG_TO_REG)
2937           continue;
2938         if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
2939             (!canClobber(SuccSU, DUSU) ||
2940              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2941              (!SU.isCommutable && SuccSU->isCommutable)) &&
2942             !scheduleDAG->IsReachable(SuccSU, &SU)) {
2943           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
2944                        << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2945           scheduleDAG->AddPred(&SU, SDep(SuccSU, SDep::Artificial));
2946         }
2947       }
2948     }
2949   }
2950 }
2951
2952 //===----------------------------------------------------------------------===//
2953 //                         Public Constructor Functions
2954 //===----------------------------------------------------------------------===//
2955
2956 llvm::ScheduleDAGSDNodes *
2957 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2958                                  CodeGenOpt::Level OptLevel) {
2959   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2960   const TargetInstrInfo *TII = STI.getInstrInfo();
2961   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2962
2963   BURegReductionPriorityQueue *PQ =
2964     new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
2965   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2966   PQ->setScheduleDAG(SD);
2967   return SD;
2968 }
2969
2970 llvm::ScheduleDAGSDNodes *
2971 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2972                                    CodeGenOpt::Level OptLevel) {
2973   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2974   const TargetInstrInfo *TII = STI.getInstrInfo();
2975   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2976
2977   SrcRegReductionPriorityQueue *PQ =
2978     new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
2979   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2980   PQ->setScheduleDAG(SD);
2981   return SD;
2982 }
2983
2984 llvm::ScheduleDAGSDNodes *
2985 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2986                                    CodeGenOpt::Level OptLevel) {
2987   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2988   const TargetInstrInfo *TII = STI.getInstrInfo();
2989   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
2990   const TargetLowering *TLI = IS->TLI;
2991
2992   HybridBURRPriorityQueue *PQ =
2993     new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
2994
2995   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2996   PQ->setScheduleDAG(SD);
2997   return SD;
2998 }
2999
3000 llvm::ScheduleDAGSDNodes *
3001 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
3002                                 CodeGenOpt::Level OptLevel) {
3003   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3004   const TargetInstrInfo *TII = STI.getInstrInfo();
3005   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3006   const TargetLowering *TLI = IS->TLI;
3007
3008   ILPBURRPriorityQueue *PQ =
3009     new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3010   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3011   PQ->setScheduleDAG(SD);
3012   return SD;
3013 }