1 //===-- MachinePipeliner.cpp - Machine Software Pipeliner Pass ------------===//
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 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
11 //
12 // Software pipelining (SWP) is an instruction scheduling technique for loops
13 // that overlap loop iterations and explioits ILP via a compiler transformation.
14 //
15 // Swing Modulo Scheduling is an implementation of software pipelining
16 // that generates schedules that are near optimal in terms of initiation
17 // interval, register requirements, and stage count. See the papers:
18 //
19 // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
20 // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996
21 // Conference on Parallel Architectures and Compilation Techiniques.
22 //
23 // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
24 // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
25 // Transactions on Computers, Vol. 50, No. 3, 2001.
26 //
27 // "An Implementation of Swing Modulo Scheduling With Extensions for
28 // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
29 // Urbana-Chambpain, 2005.
30 //
31 //
32 // The SMS algorithm consists of three main steps after computing the minimal
33 // initiation interval (MII).
34 // 1) Analyze the dependence graph and compute information about each
35 //    instruction in the graph.
36 // 2) Order the nodes (instructions) by priority based upon the heuristics
37 //    described in the algorithm.
38 // 3) Attempt to schedule the nodes in the specified order using the MII.
39 //
40 // This SMS implementation is a target-independent back-end pass. When enabled,
41 // the pass runs just prior to the register allocation pass, while the machine
42 // IR is in SSA form. If software pipelining is successful, then the original
43 // loop is replaced by the optimized loop. The optimized loop contains one or
44 // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
45 // the instructions cannot be scheduled in a given MII, we increase the MII by
46 // one and try again.
47 //
48 // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
49 // represent loop carried dependences in the DAG as order edges to the Phi
50 // nodes. We also perform several passes over the DAG to eliminate unnecessary
51 // edges that inhibit the ability to pipeline. The implementation uses the
52 // DFAPacketizer class to compute the minimum initiation interval and the check
53 // where an instruction may be inserted in the pipelined schedule.
54 //
55 // In order for the SMS pass to work, several target specific hooks need to be
56 // implemented to get information about the loop structure and to rewrite
57 // instructions.
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/MapVector.h"
63 #include "llvm/ADT/PriorityQueue.h"
64 #include "llvm/ADT/SetVector.h"
65 #include "llvm/ADT/SmallPtrSet.h"
66 #include "llvm/ADT/SmallSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AliasAnalysis.h"
69 #include "llvm/Analysis/ValueTracking.h"
70 #include "llvm/CodeGen/DFAPacketizer.h"
71 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
72 #include "llvm/CodeGen/MachineBasicBlock.h"
73 #include "llvm/CodeGen/MachineDominators.h"
74 #include "llvm/CodeGen/MachineInstrBuilder.h"
75 #include "llvm/CodeGen/MachineLoopInfo.h"
76 #include "llvm/CodeGen/MachineRegisterInfo.h"
77 #include "llvm/CodeGen/Passes.h"
78 #include "llvm/CodeGen/RegisterClassInfo.h"
79 #include "llvm/CodeGen/RegisterPressure.h"
80 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
81 #include "llvm/MC/MCInstrItineraries.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Debug.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetRegisterInfo.h"
88 #include "llvm/Target/TargetSubtargetInfo.h"
89 #include <climits>
90 #include <deque>
91 #include <map>
92 
93 using namespace llvm;
94 
95 #define DEBUG_TYPE "pipeliner"
96 
97 STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
98 STATISTIC(NumPipelined, "Number of loops software pipelined");
99 
100 /// A command line option to turn software pipelining on or off.
101 static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
102                                cl::ZeroOrMore,
103                                cl::desc("Enable Software Pipelining"));
104 
105 /// A command line option to enable SWP at -Os.
106 static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
107                                       cl::desc("Enable SWP at Os."), cl::Hidden,
108                                       cl::init(false));
109 
110 /// A command line argument to limit minimum initial interval for pipelining.
111 static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
112                               cl::desc("Size limit for the the MII."),
113                               cl::Hidden, cl::init(27));
114 
115 /// A command line argument to limit the number of stages in the pipeline.
116 static cl::opt<int>
117     SwpMaxStages("pipeliner-max-stages",
118                  cl::desc("Maximum stages allowed in the generated scheduled."),
119                  cl::Hidden, cl::init(3));
120 
121 /// A command line option to disable the pruning of chain dependences due to
122 /// an unrelated Phi.
123 static cl::opt<bool>
124     SwpPruneDeps("pipeliner-prune-deps",
125                  cl::desc("Prune dependences between unrelated Phi nodes."),
126                  cl::Hidden, cl::init(true));
127 
128 /// A command line option to disable the pruning of loop carried order
129 /// dependences.
130 static cl::opt<bool>
131     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
132                         cl::desc("Prune loop carried order dependences."),
133                         cl::Hidden, cl::init(true));
134 
135 #ifndef NDEBUG
136 static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
137 #endif
138 
139 static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
140                                      cl::ReallyHidden, cl::init(false),
141                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
142 
143 namespace {
144 
145 class NodeSet;
146 class SMSchedule;
147 class SwingSchedulerDAG;
148 
149 /// The main class in the implementation of the target independent
150 /// software pipeliner pass.
151 class MachinePipeliner : public MachineFunctionPass {
152 public:
153   MachineFunction *MF = nullptr;
154   const MachineLoopInfo *MLI = nullptr;
155   const MachineDominatorTree *MDT = nullptr;
156   const InstrItineraryData *InstrItins;
157   const TargetInstrInfo *TII = nullptr;
158   RegisterClassInfo RegClassInfo;
159 
160 #ifndef NDEBUG
161   static int NumTries;
162 #endif
163   /// Cache the target analysis information about the loop.
164   struct LoopInfo {
165     MachineBasicBlock *TBB = nullptr;
166     MachineBasicBlock *FBB = nullptr;
167     SmallVector<MachineOperand, 4> BrCond;
168     MachineInstr *LoopInductionVar = nullptr;
169     MachineInstr *LoopCompare = nullptr;
170   };
171   LoopInfo LI;
172 
173   static char ID;
174   MachinePipeliner() : MachineFunctionPass(ID) {
175     initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
176   }
177 
178   virtual bool runOnMachineFunction(MachineFunction &MF);
179 
180   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
181     AU.addRequired<AAResultsWrapperPass>();
182     AU.addPreserved<AAResultsWrapperPass>();
183     AU.addRequired<MachineLoopInfo>();
184     AU.addRequired<MachineDominatorTree>();
185     AU.addRequired<LiveIntervals>();
186     MachineFunctionPass::getAnalysisUsage(AU);
187   }
188 
189 private:
190   bool canPipelineLoop(MachineLoop &L);
191   bool scheduleLoop(MachineLoop &L);
192   bool swingModuloScheduler(MachineLoop &L);
193 };
194 
195 /// This class builds the dependence graph for the instructions in a loop,
196 /// and attempts to schedule the instructions using the SMS algorithm.
197 class SwingSchedulerDAG : public ScheduleDAGInstrs {
198   MachinePipeliner &Pass;
199   /// The minimum initiation interval between iterations for this schedule.
200   unsigned MII;
201   /// Set to true if a valid pipelined schedule is found for the loop.
202   bool Scheduled;
203   MachineLoop &Loop;
204   LiveIntervals &LIS;
205   const RegisterClassInfo &RegClassInfo;
206 
207   /// A toplogical ordering of the SUnits, which is needed for changing
208   /// dependences and iterating over the SUnits.
209   ScheduleDAGTopologicalSort Topo;
210 
211   struct NodeInfo {
212     int ASAP;
213     int ALAP;
214     NodeInfo() : ASAP(0), ALAP(0) {}
215   };
216   /// Computed properties for each node in the graph.
217   std::vector<NodeInfo> ScheduleInfo;
218 
219   enum OrderKind { BottomUp = 0, TopDown = 1 };
220   /// Computed node ordering for scheduling.
221   SetVector<SUnit *> NodeOrder;
222 
223   typedef SmallVector<NodeSet, 8> NodeSetType;
224   typedef DenseMap<unsigned, unsigned> ValueMapTy;
225   typedef SmallVectorImpl<MachineBasicBlock *> MBBVectorTy;
226   typedef DenseMap<MachineInstr *, MachineInstr *> InstrMapTy;
227 
228   /// Instructions to change when emitting the final schedule.
229   DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
230 
231   /// We may create a new instruction, so remember it because it
232   /// must be deleted when the pass is finished.
233   SmallPtrSet<MachineInstr *, 4> NewMIs;
234 
235   /// Helper class to implement Johnson's circuit finding algorithm.
236   class Circuits {
237     std::vector<SUnit> &SUnits;
238     SetVector<SUnit *> Stack;
239     BitVector Blocked;
240     SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
241     SmallVector<SmallVector<int, 4>, 16> AdjK;
242     unsigned NumPaths;
243     static unsigned MaxPaths;
244 
245   public:
246     Circuits(std::vector<SUnit> &SUs)
247         : SUnits(SUs), Stack(), Blocked(SUs.size()), B(SUs.size()),
248           AdjK(SUs.size()) {}
249     /// Reset the data structures used in the circuit algorithm.
250     void reset() {
251       Stack.clear();
252       Blocked.reset();
253       B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
254       NumPaths = 0;
255     }
256     void createAdjacencyStructure(SwingSchedulerDAG *DAG);
257     bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
258     void unblock(int U);
259   };
260 
261 public:
262   SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
263                     const RegisterClassInfo &rci)
264       : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), MII(0),
265         Scheduled(false), Loop(L), LIS(lis), RegClassInfo(rci),
266         Topo(SUnits, &ExitSU) {}
267 
268   void schedule();
269   void finishBlock();
270 
271   /// Return true if the loop kernel has been scheduled.
272   bool hasNewSchedule() { return Scheduled; }
273 
274   /// Return the earliest time an instruction may be scheduled.
275   int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
276 
277   /// Return the latest time an instruction my be scheduled.
278   int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
279 
280   /// The mobility function, which the the number of slots in which
281   /// an instruction may be scheduled.
282   int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
283 
284   /// The depth, in the dependence graph, for a node.
285   int getDepth(SUnit *Node) { return Node->getDepth(); }
286 
287   /// The height, in the dependence graph, for a node.
288   int getHeight(SUnit *Node) { return Node->getHeight(); }
289 
290   /// Return true if the dependence is a back-edge in the data dependence graph.
291   /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
292   /// using an anti dependence from a Phi to an instruction.
293   bool isBackedge(SUnit *Source, const SDep &Dep) {
294     if (Dep.getKind() != SDep::Anti)
295       return false;
296     return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
297   }
298 
299   /// Return true if the dependence is an order dependence between non-Phis.
300   static bool isOrder(SUnit *Source, const SDep &Dep) {
301     if (Dep.getKind() != SDep::Order)
302       return false;
303     return (!Source->getInstr()->isPHI() &&
304             !Dep.getSUnit()->getInstr()->isPHI());
305   }
306 
307   bool isLoopCarriedOrder(SUnit *Source, const SDep &Dep, bool isSucc = true);
308 
309   /// The latency of the dependence.
310   unsigned getLatency(SUnit *Source, const SDep &Dep) {
311     // Anti dependences represent recurrences, so use the latency of the
312     // instruction on the back-edge.
313     if (Dep.getKind() == SDep::Anti) {
314       if (Source->getInstr()->isPHI())
315         return Dep.getSUnit()->Latency;
316       if (Dep.getSUnit()->getInstr()->isPHI())
317         return Source->Latency;
318       return Dep.getLatency();
319     }
320     return Dep.getLatency();
321   }
322 
323   /// The distance function, which indicates that operation V of iteration I
324   /// depends on operations U of iteration I-distance.
325   unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
326     // Instructions that feed a Phi have a distance of 1. Computing larger
327     // values for arrays requires data dependence information.
328     if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
329       return 1;
330     return 0;
331   }
332 
333   /// Set the Minimum Initiation Interval for this schedule attempt.
334   void setMII(unsigned mii) { MII = mii; }
335 
336   MachineInstr *applyInstrChange(MachineInstr *MI, SMSchedule &Schedule,
337                                  bool UpdateDAG = false);
338 
339   /// Return the new base register that was stored away for the changed
340   /// instruction.
341   unsigned getInstrBaseReg(SUnit *SU) {
342     DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
343         InstrChanges.find(SU);
344     if (It != InstrChanges.end())
345       return It->second.first;
346     return 0;
347   }
348 
349 private:
350   void addLoopCarriedDependences(AliasAnalysis *AA);
351   void updatePhiDependences();
352   void changeDependences();
353   unsigned calculateResMII();
354   unsigned calculateRecMII(NodeSetType &RecNodeSets);
355   void findCircuits(NodeSetType &NodeSets);
356   void fuseRecs(NodeSetType &NodeSets);
357   void removeDuplicateNodes(NodeSetType &NodeSets);
358   void computeNodeFunctions(NodeSetType &NodeSets);
359   void registerPressureFilter(NodeSetType &NodeSets);
360   void colocateNodeSets(NodeSetType &NodeSets);
361   void checkNodeSets(NodeSetType &NodeSets);
362   void groupRemainingNodes(NodeSetType &NodeSets);
363   void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
364                          SetVector<SUnit *> &NodesAdded);
365   void computeNodeOrder(NodeSetType &NodeSets);
366   bool schedulePipeline(SMSchedule &Schedule);
367   void generatePipelinedLoop(SMSchedule &Schedule);
368   void generateProlog(SMSchedule &Schedule, unsigned LastStage,
369                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
370                       MBBVectorTy &PrologBBs);
371   void generateEpilog(SMSchedule &Schedule, unsigned LastStage,
372                       MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
373                       MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
374   void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
375                             MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
376                             SMSchedule &Schedule, ValueMapTy *VRMap,
377                             InstrMapTy &InstrMap, unsigned LastStageNum,
378                             unsigned CurStageNum, bool IsLast);
379   void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
380                     MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
381                     SMSchedule &Schedule, ValueMapTy *VRMap,
382                     InstrMapTy &InstrMap, unsigned LastStageNum,
383                     unsigned CurStageNum, bool IsLast);
384   void removeDeadInstructions(MachineBasicBlock *KernelBB,
385                               MBBVectorTy &EpilogBBs);
386   void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
387                       SMSchedule &Schedule);
388   void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB,
389                    MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
390                    ValueMapTy *VRMap);
391   bool computeDelta(MachineInstr &MI, unsigned &Delta);
392   void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
393                          unsigned Num);
394   MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
395                            unsigned InstStageNum);
396   MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
397                                     unsigned InstStageNum,
398                                     SMSchedule &Schedule);
399   void updateInstruction(MachineInstr *NewMI, bool LastDef,
400                          unsigned CurStageNum, unsigned InstStageNum,
401                          SMSchedule &Schedule, ValueMapTy *VRMap);
402   MachineInstr *findDefInLoop(unsigned Reg);
403   unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
404                          unsigned LoopStage, ValueMapTy *VRMap,
405                          MachineBasicBlock *BB);
406   void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
407                         SMSchedule &Schedule, ValueMapTy *VRMap,
408                         InstrMapTy &InstrMap);
409   void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule,
410                              InstrMapTy &InstrMap, unsigned CurStageNum,
411                              unsigned PhiNum, MachineInstr *Phi,
412                              unsigned OldReg, unsigned NewReg,
413                              unsigned PrevReg = 0);
414   bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
415                              unsigned &OffsetPos, unsigned &NewBase,
416                              int64_t &NewOffset);
417 };
418 
419 /// A NodeSet contains a set of SUnit DAG nodes with additional information
420 /// that assigns a priority to the set.
421 class NodeSet {
422   SetVector<SUnit *> Nodes;
423   bool HasRecurrence;
424   unsigned RecMII = 0;
425   int MaxMOV = 0;
426   int MaxDepth = 0;
427   unsigned Colocate = 0;
428   SUnit *ExceedPressure = nullptr;
429 
430 public:
431   typedef SetVector<SUnit *>::const_iterator iterator;
432 
433   NodeSet() : Nodes(), HasRecurrence(false) {}
434 
435   NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {}
436 
437   bool insert(SUnit *SU) { return Nodes.insert(SU); }
438 
439   void insert(iterator S, iterator E) { Nodes.insert(S, E); }
440 
441   template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
442     return Nodes.remove_if(P);
443   }
444 
445   unsigned count(SUnit *SU) const { return Nodes.count(SU); }
446 
447   bool hasRecurrence() { return HasRecurrence; };
448 
449   unsigned size() const { return Nodes.size(); }
450 
451   bool empty() const { return Nodes.empty(); }
452 
453   SUnit *getNode(unsigned i) const { return Nodes[i]; };
454 
455   void setRecMII(unsigned mii) { RecMII = mii; };
456 
457   void setColocate(unsigned c) { Colocate = c; };
458 
459   void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
460 
461   bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
462 
463   int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
464 
465   int getRecMII() { return RecMII; }
466 
467   /// Summarize node functions for the entire node set.
468   void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
469     for (SUnit *SU : *this) {
470       MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
471       MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
472     }
473   }
474 
475   void clear() {
476     Nodes.clear();
477     RecMII = 0;
478     HasRecurrence = false;
479     MaxMOV = 0;
480     MaxDepth = 0;
481     Colocate = 0;
482     ExceedPressure = nullptr;
483   }
484 
485   operator SetVector<SUnit *> &() { return Nodes; }
486 
487   /// Sort the node sets by importance. First, rank them by recurrence MII,
488   /// then by mobility (least mobile done first), and finally by depth.
489   /// Each node set may contain a colocate value which is used as the first
490   /// tie breaker, if it's set.
491   bool operator>(const NodeSet &RHS) const {
492     if (RecMII == RHS.RecMII) {
493       if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
494         return Colocate < RHS.Colocate;
495       if (MaxMOV == RHS.MaxMOV)
496         return MaxDepth > RHS.MaxDepth;
497       return MaxMOV < RHS.MaxMOV;
498     }
499     return RecMII > RHS.RecMII;
500   }
501 
502   bool operator==(const NodeSet &RHS) const {
503     return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
504            MaxDepth == RHS.MaxDepth;
505   }
506 
507   bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
508 
509   iterator begin() { return Nodes.begin(); }
510   iterator end() { return Nodes.end(); }
511 
512   void print(raw_ostream &os) const {
513     os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
514        << " depth " << MaxDepth << " col " << Colocate << "\n";
515     for (const auto &I : Nodes)
516       os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
517     os << "\n";
518   }
519 
520   void dump() const { print(dbgs()); }
521 };
522 
523 /// This class repesents the scheduled code.  The main data structure is a
524 /// map from scheduled cycle to instructions.  During scheduling, the
525 /// data structure explicitly represents all stages/iterations.   When
526 /// the algorithm finshes, the schedule is collapsed into a single stage,
527 /// which represents instructions from different loop iterations.
528 ///
529 /// The SMS algorithm allows negative values for cycles, so the first cycle
530 /// in the schedule is the smallest cycle value.
531 class SMSchedule {
532 private:
533   /// Map from execution cycle to instructions.
534   DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
535 
536   /// Map from instruction to execution cycle.
537   std::map<SUnit *, int> InstrToCycle;
538 
539   /// Map for each register and the max difference between its uses and def.
540   /// The first element in the pair is the max difference in stages. The
541   /// second is true if the register defines a Phi value and loop value is
542   /// scheduled before the Phi.
543   std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
544 
545   /// Keep track of the first cycle value in the schedule.  It starts
546   /// as zero, but the algorithm allows negative values.
547   int FirstCycle;
548 
549   /// Keep track of the last cycle value in the schedule.
550   int LastCycle;
551 
552   /// The initiation interval (II) for the schedule.
553   int InitiationInterval;
554 
555   /// Target machine information.
556   const TargetSubtargetInfo &ST;
557 
558   /// Virtual register information.
559   MachineRegisterInfo &MRI;
560 
561   DFAPacketizer *Resources;
562 
563 public:
564   SMSchedule(MachineFunction *mf)
565       : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
566         Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {
567     FirstCycle = 0;
568     LastCycle = 0;
569     InitiationInterval = 0;
570   }
571 
572   ~SMSchedule() {
573     ScheduledInstrs.clear();
574     InstrToCycle.clear();
575     RegToStageDiff.clear();
576     delete Resources;
577   }
578 
579   void reset() {
580     ScheduledInstrs.clear();
581     InstrToCycle.clear();
582     RegToStageDiff.clear();
583     FirstCycle = 0;
584     LastCycle = 0;
585     InitiationInterval = 0;
586   }
587 
588   /// Set the initiation interval for this schedule.
589   void setInitiationInterval(int ii) { InitiationInterval = ii; }
590 
591   /// Return the first cycle in the completed schedule.  This
592   /// can be a negative value.
593   int getFirstCycle() const { return FirstCycle; }
594 
595   /// Return the last cycle in the finalized schedule.
596   int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
597 
598   /// Return the cycle of the earliest scheduled instruction in the dependence
599   /// chain.
600   int earliestCycleInChain(const SDep &Dep);
601 
602   /// Return the cycle of the latest scheduled instruction in the dependence
603   /// chain.
604   int latestCycleInChain(const SDep &Dep);
605 
606   void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
607                     int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
608   bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
609 
610   /// Iterators for the cycle to instruction map.
611   typedef DenseMap<int, std::deque<SUnit *>>::iterator sched_iterator;
612   typedef DenseMap<int, std::deque<SUnit *>>::const_iterator
613       const_sched_iterator;
614 
615   /// Return true if the instruction is scheduled at the specified stage.
616   bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
617     return (stageScheduled(SU) == (int)StageNum);
618   }
619 
620   /// Return the stage for a scheduled instruction.  Return -1 if
621   /// the instruction has not been scheduled.
622   int stageScheduled(SUnit *SU) const {
623     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
624     if (it == InstrToCycle.end())
625       return -1;
626     return (it->second - FirstCycle) / InitiationInterval;
627   }
628 
629   /// Return the cycle for a scheduled instruction. This function normalizes
630   /// the first cycle to be 0.
631   unsigned cycleScheduled(SUnit *SU) const {
632     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
633     assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
634     return (it->second - FirstCycle) % InitiationInterval;
635   }
636 
637   /// Return the maximum stage count needed for this schedule.
638   unsigned getMaxStageCount() {
639     return (LastCycle - FirstCycle) / InitiationInterval;
640   }
641 
642   /// Return the max. number of stages/iterations that can occur between a
643   /// register definition and its uses.
644   unsigned getStagesForReg(int Reg, unsigned CurStage) {
645     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
646     if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
647       return 1;
648     return Stages.first;
649   }
650 
651   /// The number of stages for a Phi is a little different than other
652   /// instructions. The minimum value computed in RegToStageDiff is 1
653   /// because we assume the Phi is needed for at least 1 iteration.
654   /// This is not the case if the loop value is scheduled prior to the
655   /// Phi in the same stage.  This function returns the number of stages
656   /// or iterations needed between the Phi definition and any uses.
657   unsigned getStagesForPhi(int Reg) {
658     std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
659     if (Stages.second)
660       return Stages.first;
661     return Stages.first - 1;
662   }
663 
664   /// Return the instructions that are scheduled at the specified cycle.
665   std::deque<SUnit *> &getInstructions(int cycle) {
666     return ScheduledInstrs[cycle];
667   }
668 
669   bool isValidSchedule(SwingSchedulerDAG *SSD);
670   void finalizeSchedule(SwingSchedulerDAG *SSD);
671   bool orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
672                        std::deque<SUnit *> &Insts);
673   bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
674   bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst,
675                              MachineOperand &MO);
676   void print(raw_ostream &os) const;
677   void dump() const;
678 };
679 
680 } // end anonymous namespace
681 
682 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
683 char MachinePipeliner::ID = 0;
684 #ifndef NDEBUG
685 int MachinePipeliner::NumTries = 0;
686 #endif
687 char &llvm::MachinePipelinerID = MachinePipeliner::ID;
688 INITIALIZE_PASS_BEGIN(MachinePipeliner, "pipeliner",
689                       "Modulo Software Pipelining", false, false)
690 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
691 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
692 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
693 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
694 INITIALIZE_PASS_END(MachinePipeliner, "pipeliner",
695                     "Modulo Software Pipelining", false, false)
696 
697 /// The "main" function for implementing Swing Modulo Scheduling.
698 bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
699   if (skipFunction(*mf.getFunction()))
700     return false;
701 
702   if (!EnableSWP)
703     return false;
704 
705   if (mf.getFunction()->getAttributes().hasAttribute(
706           AttributeSet::FunctionIndex, Attribute::OptimizeForSize) &&
707       !EnableSWPOptSize.getPosition())
708     return false;
709 
710   MF = &mf;
711   MLI = &getAnalysis<MachineLoopInfo>();
712   MDT = &getAnalysis<MachineDominatorTree>();
713   TII = MF->getSubtarget().getInstrInfo();
714   RegClassInfo.runOnMachineFunction(*MF);
715 
716   for (auto &L : *MLI)
717     scheduleLoop(*L);
718 
719   return false;
720 }
721 
722 /// Attempt to perform the SMS algorithm on the specified loop. This function is
723 /// the main entry point for the algorithm.  The function identifies candidate
724 /// loops, calculates the minimum initiation interval, and attempts to schedule
725 /// the loop.
726 bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
727   bool Changed = false;
728   for (auto &InnerLoop : L)
729     Changed |= scheduleLoop(*InnerLoop);
730 
731 #ifndef NDEBUG
732   // Stop trying after reaching the limit (if any).
733   int Limit = SwpLoopLimit;
734   if (Limit >= 0) {
735     if (NumTries >= SwpLoopLimit)
736       return Changed;
737     NumTries++;
738   }
739 #endif
740 
741   if (!canPipelineLoop(L))
742     return Changed;
743 
744   ++NumTrytoPipeline;
745 
746   Changed = swingModuloScheduler(L);
747 
748   return Changed;
749 }
750 
751 /// Return true if the loop can be software pipelined.  The algorithm is
752 /// restricted to loops with a single basic block.  Make sure that the
753 /// branch in the loop can be analyzed.
754 bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
755   if (L.getNumBlocks() != 1)
756     return false;
757 
758   // Check if the branch can't be understood because we can't do pipelining
759   // if that's the case.
760   LI.TBB = nullptr;
761   LI.FBB = nullptr;
762   LI.BrCond.clear();
763   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
764     return false;
765 
766   LI.LoopInductionVar = nullptr;
767   LI.LoopCompare = nullptr;
768   if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
769     return false;
770 
771   if (!L.getLoopPreheader())
772     return false;
773 
774   // If any of the Phis contain subregs, then we can't pipeline
775   // because we don't know how to maintain subreg information in the
776   // VMap structure.
777   MachineBasicBlock *MBB = L.getHeader();
778   for (MachineBasicBlock::iterator BBI = MBB->instr_begin(),
779                                    BBE = MBB->getFirstNonPHI();
780        BBI != BBE; ++BBI)
781     for (unsigned i = 1; i != BBI->getNumOperands(); i += 2)
782       if (BBI->getOperand(i).getSubReg() != 0)
783         return false;
784 
785   return true;
786 }
787 
788 /// The SMS algorithm consists of the following main steps:
789 /// 1. Computation and analysis of the dependence graph.
790 /// 2. Ordering of the nodes (instructions).
791 /// 3. Attempt to Schedule the loop.
792 bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
793   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
794 
795   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
796 
797   MachineBasicBlock *MBB = L.getHeader();
798   // The kernel should not include any terminator instructions.  These
799   // will be added back later.
800   SMS.startBlock(MBB);
801 
802   // Compute the number of 'real' instructions in the basic block by
803   // ignoring terminators.
804   unsigned size = MBB->size();
805   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
806                                    E = MBB->instr_end();
807        I != E; ++I, --size)
808     ;
809 
810   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
811   SMS.schedule();
812   SMS.exitRegion();
813 
814   SMS.finishBlock();
815   return SMS.hasNewSchedule();
816 }
817 
818 /// We override the schedule function in ScheduleDAGInstrs to implement the
819 /// scheduling part of the Swing Modulo Scheduling algorithm.
820 void SwingSchedulerDAG::schedule() {
821   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
822   buildSchedGraph(AA);
823   addLoopCarriedDependences(AA);
824   updatePhiDependences();
825   Topo.InitDAGTopologicalSorting();
826   changeDependences();
827   DEBUG({
828     for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
829       SUnits[su].dumpAll(this);
830   });
831 
832   NodeSetType NodeSets;
833   findCircuits(NodeSets);
834 
835   // Calculate the MII.
836   unsigned ResMII = calculateResMII();
837   unsigned RecMII = calculateRecMII(NodeSets);
838 
839   fuseRecs(NodeSets);
840 
841   // This flag is used for testing and can cause correctness problems.
842   if (SwpIgnoreRecMII)
843     RecMII = 0;
844 
845   MII = std::max(ResMII, RecMII);
846   DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII
847                << ")\n");
848 
849   // Can't schedule a loop without a valid MII.
850   if (MII == 0)
851     return;
852 
853   // Don't pipeline large loops.
854   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
855     return;
856 
857   computeNodeFunctions(NodeSets);
858 
859   registerPressureFilter(NodeSets);
860 
861   colocateNodeSets(NodeSets);
862 
863   checkNodeSets(NodeSets);
864 
865   DEBUG({
866     for (auto &I : NodeSets) {
867       dbgs() << "  Rec NodeSet ";
868       I.dump();
869     }
870   });
871 
872   std::sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
873 
874   groupRemainingNodes(NodeSets);
875 
876   removeDuplicateNodes(NodeSets);
877 
878   DEBUG({
879     for (auto &I : NodeSets) {
880       dbgs() << "  NodeSet ";
881       I.dump();
882     }
883   });
884 
885   computeNodeOrder(NodeSets);
886 
887   SMSchedule Schedule(Pass.MF);
888   Scheduled = schedulePipeline(Schedule);
889 
890   if (!Scheduled)
891     return;
892 
893   unsigned numStages = Schedule.getMaxStageCount();
894   // No need to generate pipeline if there are no overlapped iterations.
895   if (numStages == 0)
896     return;
897 
898   // Check that the maximum stage count is less than user-defined limit.
899   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
900     return;
901 
902   generatePipelinedLoop(Schedule);
903   ++NumPipelined;
904 }
905 
906 /// Clean up after the software pipeliner runs.
907 void SwingSchedulerDAG::finishBlock() {
908   for (MachineInstr *I : NewMIs)
909     MF.DeleteMachineInstr(I);
910   NewMIs.clear();
911 
912   // Call the superclass.
913   ScheduleDAGInstrs::finishBlock();
914 }
915 
916 /// Return the register values for  the operands of a Phi instruction.
917 /// This function assume the instruction is a Phi.
918 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
919                        unsigned &InitVal, unsigned &LoopVal) {
920   assert(Phi.isPHI() && "Expecting a Phi.");
921 
922   InitVal = 0;
923   LoopVal = 0;
924   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
925     if (Phi.getOperand(i + 1).getMBB() != Loop)
926       InitVal = Phi.getOperand(i).getReg();
927     else if (Phi.getOperand(i + 1).getMBB() == Loop)
928       LoopVal = Phi.getOperand(i).getReg();
929 
930   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
931 }
932 
933 /// Return the Phi register value that comes from the incoming block.
934 static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
935   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
936     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
937       return Phi.getOperand(i).getReg();
938   return 0;
939 }
940 
941 /// Return the Phi register value that comes the the loop block.
942 static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
943   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
944     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
945       return Phi.getOperand(i).getReg();
946   return 0;
947 }
948 
949 /// Return true if SUb can be reached from SUa following the chain edges.
950 static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
951   SmallPtrSet<SUnit *, 8> Visited;
952   SmallVector<SUnit *, 8> Worklist;
953   Worklist.push_back(SUa);
954   while (!Worklist.empty()) {
955     const SUnit *SU = Worklist.pop_back_val();
956     for (auto &SI : SU->Succs) {
957       SUnit *SuccSU = SI.getSUnit();
958       if (SI.getKind() == SDep::Order) {
959         if (Visited.count(SuccSU))
960           continue;
961         if (SuccSU == SUb)
962           return true;
963         Worklist.push_back(SuccSU);
964         Visited.insert(SuccSU);
965       }
966     }
967   }
968   return false;
969 }
970 
971 /// Return true if the instruction causes a chain between memory
972 /// references before and after it.
973 static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
974   return MI.isCall() || MI.hasUnmodeledSideEffects() ||
975          (MI.hasOrderedMemoryRef() &&
976           (!MI.mayLoad() || !MI.isInvariantLoad(AA)));
977 }
978 
979 /// Return the underlying objects for the memory references of an instruction.
980 /// This function calls the code in ValueTracking, but first checks that the
981 /// instruction has a memory operand.
982 static void getUnderlyingObjects(MachineInstr *MI,
983                                  SmallVectorImpl<Value *> &Objs,
984                                  const DataLayout &DL) {
985   if (!MI->hasOneMemOperand())
986     return;
987   MachineMemOperand *MM = *MI->memoperands_begin();
988   if (!MM->getValue())
989     return;
990   GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
991 }
992 
993 /// Add a chain edge between a load and store if the store can be an
994 /// alias of the load on a subsequent iteration, i.e., a loop carried
995 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
996 /// but that code doesn't create loop carried dependences.
997 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
998   MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
999   for (auto &SU : SUnits) {
1000     MachineInstr &MI = *SU.getInstr();
1001     if (isDependenceBarrier(MI, AA))
1002       PendingLoads.clear();
1003     else if (MI.mayLoad()) {
1004       SmallVector<Value *, 4> Objs;
1005       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1006       for (auto V : Objs) {
1007         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
1008         SUs.push_back(&SU);
1009       }
1010     } else if (MI.mayStore()) {
1011       SmallVector<Value *, 4> Objs;
1012       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
1013       for (auto V : Objs) {
1014         MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
1015             PendingLoads.find(V);
1016         if (I == PendingLoads.end())
1017           continue;
1018         for (auto Load : I->second) {
1019           if (isSuccOrder(Load, &SU))
1020             continue;
1021           MachineInstr &LdMI = *Load->getInstr();
1022           // First, perform the cheaper check that compares the base register.
1023           // If they are the same and the load offset is less than the store
1024           // offset, then mark the dependence as loop carried potentially.
1025           unsigned BaseReg1, BaseReg2;
1026           int64_t Offset1, Offset2;
1027           if (!TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) ||
1028               !TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
1029             SU.addPred(SDep(Load, SDep::Barrier));
1030             continue;
1031           }
1032           if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
1033             assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
1034                    "What happened to the chain edge?");
1035             SU.addPred(SDep(Load, SDep::Barrier));
1036             continue;
1037           }
1038           // Second, the more expensive check that uses alias analysis on the
1039           // base registers. If they alias, and the load offset is less than
1040           // the store offset, the mark the dependence as loop carried.
1041           if (!AA) {
1042             SU.addPred(SDep(Load, SDep::Barrier));
1043             continue;
1044           }
1045           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
1046           MachineMemOperand *MMO2 = *MI.memoperands_begin();
1047           if (!MMO1->getValue() || !MMO2->getValue()) {
1048             SU.addPred(SDep(Load, SDep::Barrier));
1049             continue;
1050           }
1051           if (MMO1->getValue() == MMO2->getValue() &&
1052               MMO1->getOffset() <= MMO2->getOffset()) {
1053             SU.addPred(SDep(Load, SDep::Barrier));
1054             continue;
1055           }
1056           AliasResult AAResult = AA->alias(
1057               MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
1058                              MMO1->getAAInfo()),
1059               MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
1060                              MMO2->getAAInfo()));
1061 
1062           if (AAResult != NoAlias)
1063             SU.addPred(SDep(Load, SDep::Barrier));
1064         }
1065       }
1066     }
1067   }
1068 }
1069 
1070 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
1071 /// processes dependences for PHIs. This function adds true dependences
1072 /// from a PHI to a use, and a loop carried dependence from the use to the
1073 /// PHI. The loop carried dependence is represented as an anti dependence
1074 /// edge. This function also removes chain dependences between unrelated
1075 /// PHIs.
1076 void SwingSchedulerDAG::updatePhiDependences() {
1077   SmallVector<SDep, 4> RemoveDeps;
1078   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
1079 
1080   // Iterate over each DAG node.
1081   for (SUnit &I : SUnits) {
1082     RemoveDeps.clear();
1083     // Set to true if the instruction has an operand defined by a Phi.
1084     unsigned HasPhiUse = 0;
1085     unsigned HasPhiDef = 0;
1086     MachineInstr *MI = I.getInstr();
1087     // Iterate over each operand, and we process the definitions.
1088     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
1089                                     MOE = MI->operands_end();
1090          MOI != MOE; ++MOI) {
1091       if (!MOI->isReg())
1092         continue;
1093       unsigned Reg = MOI->getReg();
1094       if (MOI->isDef()) {
1095         // If the register is used by a Phi, then create an anti dependence.
1096         for (MachineRegisterInfo::use_instr_iterator
1097                  UI = MRI.use_instr_begin(Reg),
1098                  UE = MRI.use_instr_end();
1099              UI != UE; ++UI) {
1100           MachineInstr *UseMI = &*UI;
1101           SUnit *SU = getSUnit(UseMI);
1102           if (SU != 0 && UseMI->isPHI()) {
1103             if (!MI->isPHI()) {
1104               SDep Dep(SU, SDep::Anti, Reg);
1105               I.addPred(Dep);
1106             } else {
1107               HasPhiDef = Reg;
1108               // Add a chain edge to a dependent Phi that isn't an existing
1109               // predecessor.
1110               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1111                 I.addPred(SDep(SU, SDep::Barrier));
1112             }
1113           }
1114         }
1115       } else if (MOI->isUse()) {
1116         // If the register is defined by a Phi, then create a true dependence.
1117         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
1118         if (DefMI == 0)
1119           continue;
1120         SUnit *SU = getSUnit(DefMI);
1121         if (SU != 0 && DefMI->isPHI()) {
1122           if (!MI->isPHI()) {
1123             SDep Dep(SU, SDep::Data, Reg);
1124             Dep.setLatency(0);
1125             ST.adjustSchedDependency(SU, &I, Dep);
1126             I.addPred(Dep);
1127           } else {
1128             HasPhiUse = Reg;
1129             // Add a chain edge to a dependent Phi that isn't an existing
1130             // predecessor.
1131             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1132               I.addPred(SDep(SU, SDep::Barrier));
1133           }
1134         }
1135       }
1136     }
1137     // Remove order dependences from an unrelated Phi.
1138     if (!SwpPruneDeps)
1139       continue;
1140     for (auto &PI : I.Preds) {
1141       MachineInstr *PMI = PI.getSUnit()->getInstr();
1142       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1143         if (I.getInstr()->isPHI()) {
1144           if (PMI->getOperand(0).getReg() == HasPhiUse)
1145             continue;
1146           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1147             continue;
1148         }
1149         RemoveDeps.push_back(PI);
1150       }
1151     }
1152     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
1153       I.removePred(RemoveDeps[i]);
1154   }
1155 }
1156 
1157 /// Iterate over each DAG node and see if we can change any dependences
1158 /// in order to reduce the recurrence MII.
1159 void SwingSchedulerDAG::changeDependences() {
1160   // See if an instruction can use a value from the previous iteration.
1161   // If so, we update the base and offset of the instruction and change
1162   // the dependences.
1163   for (SUnit &I : SUnits) {
1164     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1165     int64_t NewOffset = 0;
1166     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1167                                NewOffset))
1168       continue;
1169 
1170     // Get the MI and SUnit for the instruction that defines the original base.
1171     unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1172     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1173     if (!DefMI)
1174       continue;
1175     SUnit *DefSU = getSUnit(DefMI);
1176     if (!DefSU)
1177       continue;
1178     // Get the MI and SUnit for the instruction that defins the new base.
1179     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1180     if (!LastMI)
1181       continue;
1182     SUnit *LastSU = getSUnit(LastMI);
1183     if (!LastSU)
1184       continue;
1185 
1186     if (Topo.IsReachable(&I, LastSU))
1187       continue;
1188 
1189     // Remove the dependence. The value now depends on a prior iteration.
1190     SmallVector<SDep, 4> Deps;
1191     for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
1192          ++P)
1193       if (P->getSUnit() == DefSU)
1194         Deps.push_back(*P);
1195     for (int i = 0, e = Deps.size(); i != e; i++) {
1196       Topo.RemovePred(&I, Deps[i].getSUnit());
1197       I.removePred(Deps[i]);
1198     }
1199     // Remove the chain dependence between the instructions.
1200     Deps.clear();
1201     for (auto &P : LastSU->Preds)
1202       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1203         Deps.push_back(P);
1204     for (int i = 0, e = Deps.size(); i != e; i++) {
1205       Topo.RemovePred(LastSU, Deps[i].getSUnit());
1206       LastSU->removePred(Deps[i]);
1207     }
1208 
1209     // Add a dependence between the new instruction and the instruction
1210     // that defines the new base.
1211     SDep Dep(&I, SDep::Anti, NewBase);
1212     LastSU->addPred(Dep);
1213 
1214     // Remember the base and offset information so that we can update the
1215     // instruction during code generation.
1216     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1217   }
1218 }
1219 
1220 namespace {
1221 // FuncUnitSorter - Comparison operator used to sort instructions by
1222 // the number of functional unit choices.
1223 struct FuncUnitSorter {
1224   const InstrItineraryData *InstrItins;
1225   DenseMap<unsigned, unsigned> Resources;
1226 
1227   // Compute the number of functional unit alternatives needed
1228   // at each stage, and take the minimum value. We prioritize the
1229   // instructions by the least number of choices first.
1230   unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
1231     unsigned schedClass = Inst->getDesc().getSchedClass();
1232     unsigned min = UINT_MAX;
1233     for (const InstrStage *IS = InstrItins->beginStage(schedClass),
1234                           *IE = InstrItins->endStage(schedClass);
1235          IS != IE; ++IS) {
1236       unsigned funcUnits = IS->getUnits();
1237       unsigned numAlternatives = countPopulation(funcUnits);
1238       if (numAlternatives < min) {
1239         min = numAlternatives;
1240         F = funcUnits;
1241       }
1242     }
1243     return min;
1244   }
1245 
1246   // Compute the critical resources needed by the instruction. This
1247   // function records the functional units needed by instructions that
1248   // must use only one functional unit. We use this as a tie breaker
1249   // for computing the resource MII. The instrutions that require
1250   // the same, highly used, functional unit have high priority.
1251   void calcCriticalResources(MachineInstr &MI) {
1252     unsigned SchedClass = MI.getDesc().getSchedClass();
1253     for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
1254                           *IE = InstrItins->endStage(SchedClass);
1255          IS != IE; ++IS) {
1256       unsigned FuncUnits = IS->getUnits();
1257       if (countPopulation(FuncUnits) == 1)
1258         Resources[FuncUnits]++;
1259     }
1260   }
1261 
1262   FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
1263   /// Return true if IS1 has less priority than IS2.
1264   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1265     unsigned F1 = 0, F2 = 0;
1266     unsigned MFUs1 = minFuncUnits(IS1, F1);
1267     unsigned MFUs2 = minFuncUnits(IS2, F2);
1268     if (MFUs1 == 1 && MFUs2 == 1)
1269       return Resources.lookup(F1) < Resources.lookup(F2);
1270     return MFUs1 > MFUs2;
1271   }
1272 };
1273 }
1274 
1275 /// Calculate the resource constrained minimum initiation interval for the
1276 /// specified loop. We use the DFA to model the resources needed for
1277 /// each instruction, and we ignore dependences. A different DFA is created
1278 /// for each cycle that is required. When adding a new instruction, we attempt
1279 /// to add it to each existing DFA, until a legal space is found. If the
1280 /// instruction cannot be reserved in an existing DFA, we create a new one.
1281 unsigned SwingSchedulerDAG::calculateResMII() {
1282   SmallVector<DFAPacketizer *, 8> Resources;
1283   MachineBasicBlock *MBB = Loop.getHeader();
1284   Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
1285 
1286   // Sort the instructions by the number of available choices for scheduling,
1287   // least to most. Use the number of critical resources as the tie breaker.
1288   FuncUnitSorter FUS =
1289       FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
1290   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1291                                    E = MBB->getFirstTerminator();
1292        I != E; ++I)
1293     FUS.calcCriticalResources(*I);
1294   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1295       FuncUnitOrder(FUS);
1296 
1297   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1298                                    E = MBB->getFirstTerminator();
1299        I != E; ++I)
1300     FuncUnitOrder.push(&*I);
1301 
1302   while (!FuncUnitOrder.empty()) {
1303     MachineInstr *MI = FuncUnitOrder.top();
1304     FuncUnitOrder.pop();
1305     if (TII->isZeroCost(MI->getOpcode()))
1306       continue;
1307     // Attempt to reserve the instruction in an existing DFA. At least one
1308     // DFA is needed for each cycle.
1309     unsigned NumCycles = getSUnit(MI)->Latency;
1310     unsigned ReservedCycles = 0;
1311     SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
1312     SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
1313     for (unsigned C = 0; C < NumCycles; ++C)
1314       while (RI != RE) {
1315         if ((*RI++)->canReserveResources(*MI)) {
1316           ++ReservedCycles;
1317           break;
1318         }
1319       }
1320     // Start reserving resources using existing DFAs.
1321     for (unsigned C = 0; C < ReservedCycles; ++C) {
1322       --RI;
1323       (*RI)->reserveResources(*MI);
1324     }
1325     // Add new DFAs, if needed, to reserve resources.
1326     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1327       DFAPacketizer *NewResource =
1328           TII->CreateTargetScheduleState(MF.getSubtarget());
1329       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1330       NewResource->reserveResources(*MI);
1331       Resources.push_back(NewResource);
1332     }
1333   }
1334   int Resmii = Resources.size();
1335   // Delete the memory for each of the DFAs that were created earlier.
1336   for (DFAPacketizer *RI : Resources) {
1337     DFAPacketizer *D = RI;
1338     delete D;
1339   }
1340   Resources.clear();
1341   return Resmii;
1342 }
1343 
1344 /// Calculate the recurrence-constrainted minimum initiation interval.
1345 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1346 /// for each circuit. The II needs to satisfy the inequality
1347 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1348 /// II that satistifies the inequality, and the RecMII is the maximum
1349 /// of those values.
1350 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1351   unsigned RecMII = 0;
1352 
1353   for (NodeSet &Nodes : NodeSets) {
1354     if (Nodes.size() == 0)
1355       continue;
1356 
1357     unsigned Delay = Nodes.size() - 1;
1358     unsigned Distance = 1;
1359 
1360     // ii = ceil(delay / distance)
1361     unsigned CurMII = (Delay + Distance - 1) / Distance;
1362     Nodes.setRecMII(CurMII);
1363     if (CurMII > RecMII)
1364       RecMII = CurMII;
1365   }
1366 
1367   return RecMII;
1368 }
1369 
1370 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1371 /// but we do this to find the circuits, and then change them back.
1372 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1373   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1374   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1375     SUnit *SU = &SUnits[i];
1376     for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1377          IP != EP; ++IP) {
1378       if (IP->getKind() != SDep::Anti)
1379         continue;
1380       DepsAdded.push_back(std::make_pair(SU, *IP));
1381     }
1382   }
1383   for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1384                                                           E = DepsAdded.end();
1385        I != E; ++I) {
1386     // Remove this anti dependency and add one in the reverse direction.
1387     SUnit *SU = I->first;
1388     SDep &D = I->second;
1389     SUnit *TargetSU = D.getSUnit();
1390     unsigned Reg = D.getReg();
1391     unsigned Lat = D.getLatency();
1392     SU->removePred(D);
1393     SDep Dep(SU, SDep::Anti, Reg);
1394     Dep.setLatency(Lat);
1395     TargetSU->addPred(Dep);
1396   }
1397 }
1398 
1399 /// Create the adjacency structure of the nodes in the graph.
1400 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1401     SwingSchedulerDAG *DAG) {
1402   BitVector Added(SUnits.size());
1403   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1404     Added.reset();
1405     // Add any successor to the adjacency matrix and exclude duplicates.
1406     for (auto &SI : SUnits[i].Succs) {
1407       // Do not process a boundary node and a back-edge is processed only
1408       // if it goes to a Phi.
1409       if (SI.getSUnit()->isBoundaryNode() ||
1410           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1411         continue;
1412       int N = SI.getSUnit()->NodeNum;
1413       if (!Added.test(N)) {
1414         AdjK[i].push_back(N);
1415         Added.set(N);
1416       }
1417     }
1418     // A chain edge between a store and a load is treated as a back-edge in the
1419     // adjacency matrix.
1420     for (auto &PI : SUnits[i].Preds) {
1421       if (!SUnits[i].getInstr()->mayStore() ||
1422           !DAG->isLoopCarriedOrder(&SUnits[i], PI, false))
1423         continue;
1424       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1425         int N = PI.getSUnit()->NodeNum;
1426         if (!Added.test(N)) {
1427           AdjK[i].push_back(N);
1428           Added.set(N);
1429         }
1430       }
1431     }
1432   }
1433 }
1434 
1435 /// Identify an elementary circuit in the dependence graph starting at the
1436 /// specified node.
1437 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1438                                           bool HasBackedge) {
1439   SUnit *SV = &SUnits[V];
1440   bool F = false;
1441   Stack.insert(SV);
1442   Blocked.set(V);
1443 
1444   for (auto W : AdjK[V]) {
1445     if (NumPaths > MaxPaths)
1446       break;
1447     if (W < S)
1448       continue;
1449     if (W == S) {
1450       if (!HasBackedge)
1451         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1452       F = true;
1453       ++NumPaths;
1454       break;
1455     } else if (!Blocked.test(W)) {
1456       if (circuit(W, S, NodeSets, W < V ? true : HasBackedge))
1457         F = true;
1458     }
1459   }
1460 
1461   if (F)
1462     unblock(V);
1463   else {
1464     for (auto W : AdjK[V]) {
1465       if (W < S)
1466         continue;
1467       if (B[W].count(SV) == 0)
1468         B[W].insert(SV);
1469     }
1470   }
1471   Stack.pop_back();
1472   return F;
1473 }
1474 
1475 /// Unblock a node in the circuit finding algorithm.
1476 void SwingSchedulerDAG::Circuits::unblock(int U) {
1477   Blocked.reset(U);
1478   SmallPtrSet<SUnit *, 4> &BU = B[U];
1479   while (!BU.empty()) {
1480     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1481     assert(SI != BU.end() && "Invalid B set.");
1482     SUnit *W = *SI;
1483     BU.erase(W);
1484     if (Blocked.test(W->NodeNum))
1485       unblock(W->NodeNum);
1486   }
1487 }
1488 
1489 /// Identify all the elementary circuits in the dependence graph using
1490 /// Johnson's circuit algorithm.
1491 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1492   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1493   // but we do this to find the circuits, and then change them back.
1494   swapAntiDependences(SUnits);
1495 
1496   Circuits Cir(SUnits);
1497   // Create the adjacency structure.
1498   Cir.createAdjacencyStructure(this);
1499   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1500     Cir.reset();
1501     Cir.circuit(i, i, NodeSets);
1502   }
1503 
1504   // Change the dependences back so that we've created a DAG again.
1505   swapAntiDependences(SUnits);
1506 }
1507 
1508 /// Return true for DAG nodes that we ignore when computing the cost functions.
1509 /// We ignore the back-edge recurrence in order to avoid unbounded recurison
1510 /// in the calculation of the ASAP, ALAP, etc functions.
1511 static bool ignoreDependence(const SDep &D, bool isPred) {
1512   if (D.isArtificial())
1513     return true;
1514   return D.getKind() == SDep::Anti && isPred;
1515 }
1516 
1517 /// Compute several functions need to order the nodes for scheduling.
1518 ///  ASAP - Earliest time to schedule a node.
1519 ///  ALAP - Latest time to schedule a node.
1520 ///  MOV - Mobility function, difference between ALAP and ASAP.
1521 ///  D - Depth of each node.
1522 ///  H - Height of each node.
1523 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1524 
1525   ScheduleInfo.resize(SUnits.size());
1526 
1527   DEBUG({
1528     for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1529                                                     E = Topo.end();
1530          I != E; ++I) {
1531       SUnit *SU = &SUnits[*I];
1532       SU->dump(this);
1533     }
1534   });
1535 
1536   int maxASAP = 0;
1537   // Compute ASAP.
1538   for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1539                                                   E = Topo.end();
1540        I != E; ++I) {
1541     int asap = 0;
1542     SUnit *SU = &SUnits[*I];
1543     for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1544                                     EP = SU->Preds.end();
1545          IP != EP; ++IP) {
1546       if (ignoreDependence(*IP, true))
1547         continue;
1548       SUnit *pred = IP->getSUnit();
1549       asap = std::max(asap, (int)(getASAP(pred) + getLatency(SU, *IP) -
1550                                   getDistance(pred, SU, *IP) * MII));
1551     }
1552     maxASAP = std::max(maxASAP, asap);
1553     ScheduleInfo[*I].ASAP = asap;
1554   }
1555 
1556   // Compute ALAP and MOV.
1557   for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1558                                                           E = Topo.rend();
1559        I != E; ++I) {
1560     int alap = maxASAP;
1561     SUnit *SU = &SUnits[*I];
1562     for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1563                                     ES = SU->Succs.end();
1564          IS != ES; ++IS) {
1565       if (ignoreDependence(*IS, true))
1566         continue;
1567       SUnit *succ = IS->getSUnit();
1568       alap = std::min(alap, (int)(getALAP(succ) - getLatency(SU, *IS) +
1569                                   getDistance(SU, succ, *IS) * MII));
1570     }
1571 
1572     ScheduleInfo[*I].ALAP = alap;
1573   }
1574 
1575   // After computing the node functions, compute the summary for each node set.
1576   for (NodeSet &I : NodeSets)
1577     I.computeNodeSetInfo(this);
1578 
1579   DEBUG({
1580     for (unsigned i = 0; i < SUnits.size(); i++) {
1581       dbgs() << "\tNode " << i << ":\n";
1582       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1583       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1584       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1585       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1586       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1587     }
1588   });
1589 }
1590 
1591 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1592 /// as the predecessors of the elements of NodeOrder that are not also in
1593 /// NodeOrder.
1594 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1595                    SmallSetVector<SUnit *, 8> &Preds,
1596                    const NodeSet *S = nullptr) {
1597   Preds.clear();
1598   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1599        I != E; ++I) {
1600     for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1601          PI != PE; ++PI) {
1602       if (S && S->count(PI->getSUnit()) == 0)
1603         continue;
1604       if (ignoreDependence(*PI, true))
1605         continue;
1606       if (NodeOrder.count(PI->getSUnit()) == 0)
1607         Preds.insert(PI->getSUnit());
1608     }
1609     // Back-edges are predecessors with an anti-dependence.
1610     for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1611                                     ES = (*I)->Succs.end();
1612          IS != ES; ++IS) {
1613       if (IS->getKind() != SDep::Anti)
1614         continue;
1615       if (S && S->count(IS->getSUnit()) == 0)
1616         continue;
1617       if (NodeOrder.count(IS->getSUnit()) == 0)
1618         Preds.insert(IS->getSUnit());
1619     }
1620   }
1621   return Preds.size() > 0;
1622 }
1623 
1624 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1625 /// as the successors of the elements of NodeOrder that are not also in
1626 /// NodeOrder.
1627 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1628                    SmallSetVector<SUnit *, 8> &Succs,
1629                    const NodeSet *S = nullptr) {
1630   Succs.clear();
1631   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1632        I != E; ++I) {
1633     for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1634          SI != SE; ++SI) {
1635       if (S && S->count(SI->getSUnit()) == 0)
1636         continue;
1637       if (ignoreDependence(*SI, false))
1638         continue;
1639       if (NodeOrder.count(SI->getSUnit()) == 0)
1640         Succs.insert(SI->getSUnit());
1641     }
1642     for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1643                                     PE = (*I)->Preds.end();
1644          PI != PE; ++PI) {
1645       if (PI->getKind() != SDep::Anti)
1646         continue;
1647       if (S && S->count(PI->getSUnit()) == 0)
1648         continue;
1649       if (NodeOrder.count(PI->getSUnit()) == 0)
1650         Succs.insert(PI->getSUnit());
1651     }
1652   }
1653   return Succs.size() > 0;
1654 }
1655 
1656 /// Return true if there is a path from the specified node to any of the nodes
1657 /// in DestNodes. Keep track and return the nodes in any path.
1658 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1659                         SetVector<SUnit *> &DestNodes,
1660                         SetVector<SUnit *> &Exclude,
1661                         SmallPtrSet<SUnit *, 8> &Visited) {
1662   if (Cur->isBoundaryNode())
1663     return false;
1664   if (Exclude.count(Cur) != 0)
1665     return false;
1666   if (DestNodes.count(Cur) != 0)
1667     return true;
1668   if (!Visited.insert(Cur).second)
1669     return Path.count(Cur) != 0;
1670   bool FoundPath = false;
1671   for (auto &SI : Cur->Succs)
1672     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1673   for (auto &PI : Cur->Preds)
1674     if (PI.getKind() == SDep::Anti)
1675       FoundPath |=
1676           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1677   if (FoundPath)
1678     Path.insert(Cur);
1679   return FoundPath;
1680 }
1681 
1682 /// Return true if Set1 is a subset of Set2.
1683 template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1684   for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1685     if (Set2.count(*I) == 0)
1686       return false;
1687   return true;
1688 }
1689 
1690 /// Compute the live-out registers for the instructions in a node-set.
1691 /// The live-out registers are those that are defined in the node-set,
1692 /// but not used. Except for use operands of Phis.
1693 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1694                             NodeSet &NS) {
1695   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1696   MachineRegisterInfo &MRI = MF.getRegInfo();
1697   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1698   SmallSet<unsigned, 4> Uses;
1699   for (SUnit *SU : NS) {
1700     const MachineInstr *MI = SU->getInstr();
1701     if (MI->isPHI())
1702       continue;
1703     for (ConstMIOperands MO(*MI); MO.isValid(); ++MO)
1704       if (MO->isReg() && MO->isUse()) {
1705         unsigned Reg = MO->getReg();
1706         if (TargetRegisterInfo::isVirtualRegister(Reg))
1707           Uses.insert(Reg);
1708         else if (MRI.isAllocatable(Reg))
1709           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1710             Uses.insert(*Units);
1711       }
1712   }
1713   for (SUnit *SU : NS)
1714     for (ConstMIOperands MO(*SU->getInstr()); MO.isValid(); ++MO)
1715       if (MO->isReg() && MO->isDef() && !MO->isDead()) {
1716         unsigned Reg = MO->getReg();
1717         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1718           if (!Uses.count(Reg))
1719             LiveOutRegs.push_back(RegisterMaskPair(Reg, 0));
1720         } else if (MRI.isAllocatable(Reg)) {
1721           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1722             if (!Uses.count(*Units))
1723               LiveOutRegs.push_back(RegisterMaskPair(*Units, 0));
1724         }
1725       }
1726   RPTracker.addLiveRegs(LiveOutRegs);
1727 }
1728 
1729 /// A heuristic to filter nodes in recurrent node-sets if the register
1730 /// pressure of a set is too high.
1731 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1732   for (auto &NS : NodeSets) {
1733     // Skip small node-sets since they won't cause register pressure problems.
1734     if (NS.size() <= 2)
1735       continue;
1736     IntervalPressure RecRegPressure;
1737     RegPressureTracker RecRPTracker(RecRegPressure);
1738     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1739     computeLiveOuts(MF, RecRPTracker, NS);
1740     RecRPTracker.closeBottom();
1741 
1742     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1743     std::sort(SUnits.begin(), SUnits.end(), [](const SUnit *A, const SUnit *B) {
1744       return A->NodeNum > B->NodeNum;
1745     });
1746 
1747     for (auto &SU : SUnits) {
1748       // Since we're computing the register pressure for a subset of the
1749       // instructions in a block, we need to set the tracker for each
1750       // instruction in the node-set. The tracker is set to the instruction
1751       // just after the one we're interested in.
1752       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1753       RecRPTracker.setPos(std::next(CurInstI));
1754 
1755       RegPressureDelta RPDelta;
1756       ArrayRef<PressureChange> CriticalPSets;
1757       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1758                                              CriticalPSets,
1759                                              RecRegPressure.MaxSetPressure);
1760       if (RPDelta.Excess.isValid()) {
1761         DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1762                      << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1763                      << ":" << RPDelta.Excess.getUnitInc());
1764         NS.setExceedPressure(SU);
1765         break;
1766       }
1767       RecRPTracker.recede();
1768     }
1769   }
1770 }
1771 
1772 /// A heuristic to colocate node sets that have the same set of
1773 /// successors.
1774 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1775   unsigned Colocate = 0;
1776   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1777     NodeSet &N1 = NodeSets[i];
1778     SmallSetVector<SUnit *, 8> S1;
1779     if (N1.empty() || !succ_L(N1, S1))
1780       continue;
1781     for (int j = i + 1; j < e; ++j) {
1782       NodeSet &N2 = NodeSets[j];
1783       if (N1.compareRecMII(N2) != 0)
1784         continue;
1785       SmallSetVector<SUnit *, 8> S2;
1786       if (N2.empty() || !succ_L(N2, S2))
1787         continue;
1788       if (isSubset(S1, S2) && S1.size() == S2.size()) {
1789         N1.setColocate(++Colocate);
1790         N2.setColocate(Colocate);
1791         break;
1792       }
1793     }
1794   }
1795 }
1796 
1797 /// Check if the existing node-sets are profitable. If not, then ignore the
1798 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1799 /// a heuristic. If the MII is large and there is a non-recurrent node with
1800 /// a large depth compared to the MII, then it's best to try and schedule
1801 /// all instruction together instead of starting with the recurrent node-sets.
1802 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1803   // Look for loops with a large MII.
1804   if (MII <= 20)
1805     return;
1806   // Check if the node-set contains only a simple add recurrence.
1807   for (auto &NS : NodeSets)
1808     if (NS.size() > 2)
1809       return;
1810   // If the depth of any instruction is significantly larger than the MII, then
1811   // ignore the recurrent node-sets and treat all instructions equally.
1812   for (auto &SU : SUnits)
1813     if (SU.getDepth() > MII * 1.5) {
1814       NodeSets.clear();
1815       DEBUG(dbgs() << "Clear recurrence node-sets\n");
1816       return;
1817     }
1818 }
1819 
1820 /// Add the nodes that do not belong to a recurrence set into groups
1821 /// based upon connected componenets.
1822 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1823   SetVector<SUnit *> NodesAdded;
1824   SmallPtrSet<SUnit *, 8> Visited;
1825   // Add the nodes that are on a path between the previous node sets and
1826   // the current node set.
1827   for (NodeSet &I : NodeSets) {
1828     SmallSetVector<SUnit *, 8> N;
1829     // Add the nodes from the current node set to the previous node set.
1830     if (succ_L(I, N)) {
1831       SetVector<SUnit *> Path;
1832       for (SUnit *NI : N) {
1833         Visited.clear();
1834         computePath(NI, Path, NodesAdded, I, Visited);
1835       }
1836       if (Path.size() > 0)
1837         I.insert(Path.begin(), Path.end());
1838     }
1839     // Add the nodes from the previous node set to the current node set.
1840     N.clear();
1841     if (succ_L(NodesAdded, N)) {
1842       SetVector<SUnit *> Path;
1843       for (SUnit *NI : N) {
1844         Visited.clear();
1845         computePath(NI, Path, I, NodesAdded, Visited);
1846       }
1847       if (Path.size() > 0)
1848         I.insert(Path.begin(), Path.end());
1849     }
1850     NodesAdded.insert(I.begin(), I.end());
1851   }
1852 
1853   // Create a new node set with the connected nodes of any successor of a node
1854   // in a recurrent set.
1855   NodeSet NewSet;
1856   SmallSetVector<SUnit *, 8> N;
1857   if (succ_L(NodesAdded, N))
1858     for (SUnit *I : N)
1859       addConnectedNodes(I, NewSet, NodesAdded);
1860   if (NewSet.size() > 0)
1861     NodeSets.push_back(NewSet);
1862 
1863   // Create a new node set with the connected nodes of any predecessor of a node
1864   // in a recurrent set.
1865   NewSet.clear();
1866   if (pred_L(NodesAdded, N))
1867     for (SUnit *I : N)
1868       addConnectedNodes(I, NewSet, NodesAdded);
1869   if (NewSet.size() > 0)
1870     NodeSets.push_back(NewSet);
1871 
1872   // Create new nodes sets with the connected nodes any any remaining node that
1873   // has no predecessor.
1874   for (unsigned i = 0; i < SUnits.size(); ++i) {
1875     SUnit *SU = &SUnits[i];
1876     if (NodesAdded.count(SU) == 0) {
1877       NewSet.clear();
1878       addConnectedNodes(SU, NewSet, NodesAdded);
1879       if (NewSet.size() > 0)
1880         NodeSets.push_back(NewSet);
1881     }
1882   }
1883 }
1884 
1885 /// Add the node to the set, and add all is its connected nodes to the set.
1886 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1887                                           SetVector<SUnit *> &NodesAdded) {
1888   NewSet.insert(SU);
1889   NodesAdded.insert(SU);
1890   for (auto &SI : SU->Succs) {
1891     SUnit *Successor = SI.getSUnit();
1892     if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1893       addConnectedNodes(Successor, NewSet, NodesAdded);
1894   }
1895   for (auto &PI : SU->Preds) {
1896     SUnit *Predecessor = PI.getSUnit();
1897     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1898       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1899   }
1900 }
1901 
1902 /// Return true if Set1 contains elements in Set2. The elements in common
1903 /// are returned in a different container.
1904 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1905                         SmallSetVector<SUnit *, 8> &Result) {
1906   Result.clear();
1907   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1908     SUnit *SU = Set1[i];
1909     if (Set2.count(SU) != 0)
1910       Result.insert(SU);
1911   }
1912   return !Result.empty();
1913 }
1914 
1915 /// Merge the recurrence node sets that have the same initial node.
1916 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1917   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1918        ++I) {
1919     NodeSet &NI = *I;
1920     for (NodeSetType::iterator J = I + 1; J != E;) {
1921       NodeSet &NJ = *J;
1922       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1923         if (NJ.compareRecMII(NI) > 0)
1924           NI.setRecMII(NJ.getRecMII());
1925         for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1926              ++NII)
1927           I->insert(*NII);
1928         NodeSets.erase(J);
1929         E = NodeSets.end();
1930       } else {
1931         ++J;
1932       }
1933     }
1934   }
1935 }
1936 
1937 /// Remove nodes that have been scheduled in previous NodeSets.
1938 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1939   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1940        ++I)
1941     for (NodeSetType::iterator J = I + 1; J != E;) {
1942       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1943 
1944       if (J->size() == 0) {
1945         NodeSets.erase(J);
1946         E = NodeSets.end();
1947       } else {
1948         ++J;
1949       }
1950     }
1951 }
1952 
1953 /// Return true if Inst1 defines a value that is used in Inst2.
1954 static bool hasDataDependence(SUnit *Inst1, SUnit *Inst2) {
1955   for (auto &SI : Inst1->Succs)
1956     if (SI.getSUnit() == Inst2 && SI.getKind() == SDep::Data)
1957       return true;
1958   return false;
1959 }
1960 
1961 /// Compute an ordered list of the dependence graph nodes, which
1962 /// indicates the order that the nodes will be scheduled.  This is a
1963 /// two-level algorithm. First, a partial order is created, which
1964 /// consists of a list of sets ordered from highest to lowest priority.
1965 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1966   SmallSetVector<SUnit *, 8> R;
1967   NodeOrder.clear();
1968 
1969   for (auto &Nodes : NodeSets) {
1970     DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1971     OrderKind Order;
1972     SmallSetVector<SUnit *, 8> N;
1973     if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1974       R.insert(N.begin(), N.end());
1975       Order = BottomUp;
1976       DEBUG(dbgs() << "  Bottom up (preds) ");
1977     } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1978       R.insert(N.begin(), N.end());
1979       Order = TopDown;
1980       DEBUG(dbgs() << "  Top down (succs) ");
1981     } else if (isIntersect(N, Nodes, R)) {
1982       // If some of the successors are in the existing node-set, then use the
1983       // top-down ordering.
1984       Order = TopDown;
1985       DEBUG(dbgs() << "  Top down (intersect) ");
1986     } else if (NodeSets.size() == 1) {
1987       for (auto &N : Nodes)
1988         if (N->Succs.size() == 0)
1989           R.insert(N);
1990       Order = BottomUp;
1991       DEBUG(dbgs() << "  Bottom up (all) ");
1992     } else {
1993       // Find the node with the highest ASAP.
1994       SUnit *maxASAP = nullptr;
1995       for (SUnit *SU : Nodes) {
1996         if (maxASAP == nullptr || getASAP(SU) >= getASAP(maxASAP))
1997           maxASAP = SU;
1998       }
1999       R.insert(maxASAP);
2000       Order = BottomUp;
2001       DEBUG(dbgs() << "  Bottom up (default) ");
2002     }
2003 
2004     while (!R.empty()) {
2005       if (Order == TopDown) {
2006         // Choose the node with the maximum height.  If more than one, choose
2007         // the node with the lowest MOV. If still more than one, check if there
2008         // is a dependence between the instructions.
2009         while (!R.empty()) {
2010           SUnit *maxHeight = nullptr;
2011           for (SUnit *I : R) {
2012             if (maxHeight == 0 || getHeight(I) > getHeight(maxHeight))
2013               maxHeight = I;
2014             else if (getHeight(I) == getHeight(maxHeight) &&
2015                      getMOV(I) < getMOV(maxHeight) &&
2016                      !hasDataDependence(maxHeight, I))
2017               maxHeight = I;
2018             else if (hasDataDependence(I, maxHeight))
2019               maxHeight = I;
2020           }
2021           NodeOrder.insert(maxHeight);
2022           DEBUG(dbgs() << maxHeight->NodeNum << " ");
2023           R.remove(maxHeight);
2024           for (const auto &I : maxHeight->Succs) {
2025             if (Nodes.count(I.getSUnit()) == 0)
2026               continue;
2027             if (NodeOrder.count(I.getSUnit()) != 0)
2028               continue;
2029             if (ignoreDependence(I, false))
2030               continue;
2031             R.insert(I.getSUnit());
2032           }
2033           // Back-edges are predecessors with an anti-dependence.
2034           for (const auto &I : maxHeight->Preds) {
2035             if (I.getKind() != SDep::Anti)
2036               continue;
2037             if (Nodes.count(I.getSUnit()) == 0)
2038               continue;
2039             if (NodeOrder.count(I.getSUnit()) != 0)
2040               continue;
2041             R.insert(I.getSUnit());
2042           }
2043         }
2044         Order = BottomUp;
2045         DEBUG(dbgs() << "\n   Switching order to bottom up ");
2046         SmallSetVector<SUnit *, 8> N;
2047         if (pred_L(NodeOrder, N, &Nodes))
2048           R.insert(N.begin(), N.end());
2049       } else {
2050         // Choose the node with the maximum depth.  If more than one, choose
2051         // the node with the lowest MOV. If there is still more than one, check
2052         // for a dependence between the instructions.
2053         while (!R.empty()) {
2054           SUnit *maxDepth = nullptr;
2055           for (SUnit *I : R) {
2056             if (maxDepth == 0 || getDepth(I) > getDepth(maxDepth))
2057               maxDepth = I;
2058             else if (getDepth(I) == getDepth(maxDepth) &&
2059                      getMOV(I) < getMOV(maxDepth) &&
2060                      !hasDataDependence(I, maxDepth))
2061               maxDepth = I;
2062             else if (hasDataDependence(maxDepth, I))
2063               maxDepth = I;
2064           }
2065           NodeOrder.insert(maxDepth);
2066           DEBUG(dbgs() << maxDepth->NodeNum << " ");
2067           R.remove(maxDepth);
2068           if (Nodes.isExceedSU(maxDepth)) {
2069             Order = TopDown;
2070             R.clear();
2071             R.insert(Nodes.getNode(0));
2072             break;
2073           }
2074           for (const auto &I : maxDepth->Preds) {
2075             if (Nodes.count(I.getSUnit()) == 0)
2076               continue;
2077             if (NodeOrder.count(I.getSUnit()) != 0)
2078               continue;
2079             if (I.getKind() == SDep::Anti)
2080               continue;
2081             R.insert(I.getSUnit());
2082           }
2083           // Back-edges are predecessors with an anti-dependence.
2084           for (const auto &I : maxDepth->Succs) {
2085             if (I.getKind() != SDep::Anti)
2086               continue;
2087             if (Nodes.count(I.getSUnit()) == 0)
2088               continue;
2089             if (NodeOrder.count(I.getSUnit()) != 0)
2090               continue;
2091             R.insert(I.getSUnit());
2092           }
2093         }
2094         Order = TopDown;
2095         DEBUG(dbgs() << "\n   Switching order to top down ");
2096         SmallSetVector<SUnit *, 8> N;
2097         if (succ_L(NodeOrder, N, &Nodes))
2098           R.insert(N.begin(), N.end());
2099       }
2100     }
2101     DEBUG(dbgs() << "\nDone with Nodeset\n");
2102   }
2103 
2104   DEBUG({
2105     dbgs() << "Node order: ";
2106     for (SUnit *I : NodeOrder)
2107       dbgs() << " " << I->NodeNum << " ";
2108     dbgs() << "\n";
2109   });
2110 }
2111 
2112 /// Process the nodes in the computed order and create the pipelined schedule
2113 /// of the instructions, if possible. Return true if a schedule is found.
2114 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2115 
2116   if (NodeOrder.size() == 0)
2117     return false;
2118 
2119   bool scheduleFound = false;
2120   // Keep increasing II until a valid schedule is found.
2121   for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
2122     Schedule.reset();
2123     Schedule.setInitiationInterval(II);
2124     DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2125 
2126     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2127     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2128     do {
2129       SUnit *SU = *NI;
2130 
2131       // Compute the schedule time for the instruction, which is based
2132       // upon the scheduled time for any predecessors/successors.
2133       int EarlyStart = INT_MIN;
2134       int LateStart = INT_MAX;
2135       // These values are set when the size of the schedule window is limited
2136       // due to chain dependences.
2137       int SchedEnd = INT_MAX;
2138       int SchedStart = INT_MIN;
2139       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2140                             II, this);
2141       DEBUG({
2142         dbgs() << "Inst (" << SU->NodeNum << ") ";
2143         SU->getInstr()->dump();
2144         dbgs() << "\n";
2145       });
2146       DEBUG({
2147         dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
2148                << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
2149       });
2150 
2151       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2152           SchedStart > LateStart)
2153         scheduleFound = false;
2154       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2155         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2156         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2157       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2158         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2159         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2160       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2161         SchedEnd =
2162             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2163         // When scheduling a Phi it is better to start at the late cycle and go
2164         // backwards. The default order may insert the Phi too far away from
2165         // its first dependence.
2166         if (SU->getInstr()->isPHI())
2167           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2168         else
2169           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2170       } else {
2171         int FirstCycle = Schedule.getFirstCycle();
2172         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2173                                         FirstCycle + getASAP(SU) + II - 1, II);
2174       }
2175       // Even if we find a schedule, make sure the schedule doesn't exceed the
2176       // allowable number of stages. We keep trying if this happens.
2177       if (scheduleFound)
2178         if (SwpMaxStages > -1 &&
2179             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2180           scheduleFound = false;
2181 
2182       DEBUG({
2183         if (!scheduleFound)
2184           dbgs() << "\tCan't schedule\n";
2185       });
2186     } while (++NI != NE && scheduleFound);
2187 
2188     // If a schedule is found, check if it is a valid schedule too.
2189     if (scheduleFound)
2190       scheduleFound = Schedule.isValidSchedule(this);
2191   }
2192 
2193   DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
2194 
2195   if (scheduleFound)
2196     Schedule.finalizeSchedule(this);
2197   else
2198     Schedule.reset();
2199 
2200   return scheduleFound && Schedule.getMaxStageCount() > 0;
2201 }
2202 
2203 /// Given a schedule for the loop, generate a new version of the loop,
2204 /// and replace the old version.  This function generates a prolog
2205 /// that contains the initial iterations in the pipeline, and kernel
2206 /// loop, and the epilogue that contains the code for the final
2207 /// iterations.
2208 void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2209   // Create a new basic block for the kernel and add it to the CFG.
2210   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2211 
2212   unsigned MaxStageCount = Schedule.getMaxStageCount();
2213 
2214   // Remember the registers that are used in different stages. The index is
2215   // the iteration, or stage, that the instruction is scheduled in.  This is
2216   // a map between register names in the orignal block and the names created
2217   // in each stage of the pipelined loop.
2218   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2219   InstrMapTy InstrMap;
2220 
2221   SmallVector<MachineBasicBlock *, 4> PrologBBs;
2222   // Generate the prolog instructions that set up the pipeline.
2223   generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2224   MF.insert(BB->getIterator(), KernelBB);
2225 
2226   // Rearrange the instructions to generate the new, pipelined loop,
2227   // and update register names as needed.
2228   for (int Cycle = Schedule.getFirstCycle(),
2229            LastCycle = Schedule.getFinalCycle();
2230        Cycle <= LastCycle; ++Cycle) {
2231     std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2232     // This inner loop schedules each instruction in the cycle.
2233     for (SUnit *CI : CycleInstrs) {
2234       if (CI->getInstr()->isPHI())
2235         continue;
2236       unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2237       MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2238       updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2239       KernelBB->push_back(NewMI);
2240       InstrMap[NewMI] = CI->getInstr();
2241     }
2242   }
2243 
2244   // Copy any terminator instructions to the new kernel, and update
2245   // names as needed.
2246   for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2247                                    E = BB->instr_end();
2248        I != E; ++I) {
2249     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2250     updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2251     KernelBB->push_back(NewMI);
2252     InstrMap[NewMI] = &*I;
2253   }
2254 
2255   KernelBB->transferSuccessors(BB);
2256   KernelBB->replaceSuccessor(BB, KernelBB);
2257 
2258   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2259                        VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2260   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2261                InstrMap, MaxStageCount, MaxStageCount, false);
2262 
2263   DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
2264 
2265   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2266   // Generate the epilog instructions to complete the pipeline.
2267   generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2268                  PrologBBs);
2269 
2270   // We need this step because the register allocation doesn't handle some
2271   // situations well, so we insert copies to help out.
2272   splitLifetimes(KernelBB, EpilogBBs, Schedule);
2273 
2274   // Remove dead instructions due to loop induction variables.
2275   removeDeadInstructions(KernelBB, EpilogBBs);
2276 
2277   // Add branches between prolog and epilog blocks.
2278   addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2279 
2280   // Remove the original loop since it's no longer referenced.
2281   BB->clear();
2282   BB->eraseFromParent();
2283 
2284   delete[] VRMap;
2285 }
2286 
2287 /// Generate the pipeline prolog code.
2288 void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2289                                        MachineBasicBlock *KernelBB,
2290                                        ValueMapTy *VRMap,
2291                                        MBBVectorTy &PrologBBs) {
2292   MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2293   assert(PreheaderBB != NULL &&
2294          "Need to add code to handle loops w/o preheader");
2295   MachineBasicBlock *PredBB = PreheaderBB;
2296   InstrMapTy InstrMap;
2297 
2298   // Generate a basic block for each stage, not including the last stage,
2299   // which will be generated in the kernel. Each basic block may contain
2300   // instructions from multiple stages/iterations.
2301   for (unsigned i = 0; i < LastStage; ++i) {
2302     // Create and insert the prolog basic block prior to the original loop
2303     // basic block.  The original loop is removed later.
2304     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2305     PrologBBs.push_back(NewBB);
2306     MF.insert(BB->getIterator(), NewBB);
2307     NewBB->transferSuccessors(PredBB);
2308     PredBB->addSuccessor(NewBB);
2309     PredBB = NewBB;
2310 
2311     // Generate instructions for each appropriate stage. Process instructions
2312     // in original program order.
2313     for (int StageNum = i; StageNum >= 0; --StageNum) {
2314       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2315                                        BBE = BB->getFirstTerminator();
2316            BBI != BBE; ++BBI) {
2317         if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2318           if (BBI->isPHI())
2319             continue;
2320           MachineInstr *NewMI =
2321               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2322           updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2323                             VRMap);
2324           NewBB->push_back(NewMI);
2325           InstrMap[NewMI] = &*BBI;
2326         }
2327       }
2328     }
2329     rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
2330     DEBUG({
2331       dbgs() << "prolog:\n";
2332       NewBB->dump();
2333     });
2334   }
2335 
2336   PredBB->replaceSuccessor(BB, KernelBB);
2337 
2338   // Check if we need to remove the branch from the preheader to the original
2339   // loop, and replace it with a branch to the new loop.
2340   unsigned numBranches = TII->RemoveBranch(*PreheaderBB);
2341   if (numBranches) {
2342     SmallVector<MachineOperand, 0> Cond;
2343     TII->InsertBranch(*PreheaderBB, PrologBBs[0], 0, Cond, DebugLoc());
2344   }
2345 }
2346 
2347 /// Generate the pipeline epilog code. The epilog code finishes the iterations
2348 /// that were started in either the prolog or the kernel.  We create a basic
2349 /// block for each stage that needs to complete.
2350 void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2351                                        MachineBasicBlock *KernelBB,
2352                                        ValueMapTy *VRMap,
2353                                        MBBVectorTy &EpilogBBs,
2354                                        MBBVectorTy &PrologBBs) {
2355   // We need to change the branch from the kernel to the first epilog block, so
2356   // this call to analyze branch uses the kernel rather than the original BB.
2357   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2358   SmallVector<MachineOperand, 4> Cond;
2359   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2360   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2361   if (checkBranch)
2362     return;
2363 
2364   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2365   if (*LoopExitI == KernelBB)
2366     ++LoopExitI;
2367   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2368   MachineBasicBlock *LoopExitBB = *LoopExitI;
2369 
2370   MachineBasicBlock *PredBB = KernelBB;
2371   MachineBasicBlock *EpilogStart = LoopExitBB;
2372   InstrMapTy InstrMap;
2373 
2374   // Generate a basic block for each stage, not including the last stage,
2375   // which was generated for the kernel.  Each basic block may contain
2376   // instructions from multiple stages/iterations.
2377   int EpilogStage = LastStage + 1;
2378   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2379     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2380     EpilogBBs.push_back(NewBB);
2381     MF.insert(BB->getIterator(), NewBB);
2382 
2383     PredBB->replaceSuccessor(LoopExitBB, NewBB);
2384     NewBB->addSuccessor(LoopExitBB);
2385 
2386     if (EpilogStart == LoopExitBB)
2387       EpilogStart = NewBB;
2388 
2389     // Add instructions to the epilog depending on the current block.
2390     // Process instructions in original program order.
2391     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2392       for (auto &BBI : *BB) {
2393         if (BBI.isPHI())
2394           continue;
2395         MachineInstr *In = &BBI;
2396         if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
2397           MachineInstr *NewMI = cloneInstr(In, EpilogStage - LastStage, 0);
2398           updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2399           NewBB->push_back(NewMI);
2400           InstrMap[NewMI] = In;
2401         }
2402       }
2403     }
2404     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2405                          VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2406     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2407                  InstrMap, LastStage, EpilogStage, i == 1);
2408     PredBB = NewBB;
2409 
2410     DEBUG({
2411       dbgs() << "epilog:\n";
2412       NewBB->dump();
2413     });
2414   }
2415 
2416   // Fix any Phi nodes in the loop exit block.
2417   for (MachineInstr &MI : *LoopExitBB) {
2418     if (!MI.isPHI())
2419       break;
2420     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2421       MachineOperand &MO = MI.getOperand(i);
2422       if (MO.getMBB() == BB)
2423         MO.setMBB(PredBB);
2424     }
2425   }
2426 
2427   // Create a branch to the new epilog from the kernel.
2428   // Remove the original branch and add a new branch to the epilog.
2429   TII->RemoveBranch(*KernelBB);
2430   TII->InsertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
2431   // Add a branch to the loop exit.
2432   if (EpilogBBs.size() > 0) {
2433     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2434     SmallVector<MachineOperand, 4> Cond1;
2435     TII->InsertBranch(*LastEpilogBB, LoopExitBB, 0, Cond1, DebugLoc());
2436   }
2437 }
2438 
2439 /// Replace all uses of FromReg that appear outside the specified
2440 /// basic block with ToReg.
2441 static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2442                                     MachineBasicBlock *MBB,
2443                                     MachineRegisterInfo &MRI,
2444                                     LiveIntervals &LIS) {
2445   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2446                                          E = MRI.use_end();
2447        I != E;) {
2448     MachineOperand &O = *I;
2449     ++I;
2450     if (O.getParent()->getParent() != MBB)
2451       O.setReg(ToReg);
2452   }
2453   if (!LIS.hasInterval(ToReg))
2454     LIS.createEmptyInterval(ToReg);
2455 }
2456 
2457 /// Return true if the register has a use that occurs outside the
2458 /// specified loop.
2459 static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2460                             MachineRegisterInfo &MRI) {
2461   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2462                                          E = MRI.use_end();
2463        I != E; ++I)
2464     if (I->getParent()->getParent() != BB)
2465       return true;
2466   return false;
2467 }
2468 
2469 /// Generate Phis for the specific block in the generated pipelined code.
2470 /// This function looks at the Phis from the original code to guide the
2471 /// creation of new Phis.
2472 void SwingSchedulerDAG::generateExistingPhis(
2473     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2474     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2475     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2476     bool IsLast) {
2477   // Compute the stage number for the inital value of the Phi, which
2478   // comes from the prolog. The prolog to use depends on to which kernel/
2479   // epilog that we're adding the Phi.
2480   unsigned PrologStage = 0;
2481   unsigned PrevStage = 0;
2482   bool InKernel = (LastStageNum == CurStageNum);
2483   if (InKernel) {
2484     PrologStage = LastStageNum - 1;
2485     PrevStage = CurStageNum;
2486   } else {
2487     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2488     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2489   }
2490 
2491   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2492                                    BBE = BB->getFirstNonPHI();
2493        BBI != BBE; ++BBI) {
2494     unsigned Def = BBI->getOperand(0).getReg();
2495 
2496     unsigned InitVal = 0;
2497     unsigned LoopVal = 0;
2498     getPhiRegs(*BBI, BB, InitVal, LoopVal);
2499 
2500     unsigned PhiOp1 = 0;
2501     // The Phi value from the loop body typically is defined in the loop, but
2502     // not always. So, we need to check if the value is defined in the loop.
2503     unsigned PhiOp2 = LoopVal;
2504     if (VRMap[LastStageNum].count(LoopVal))
2505       PhiOp2 = VRMap[LastStageNum][LoopVal];
2506 
2507     int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2508     int LoopValStage =
2509         Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2510     unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2511     if (NumStages == 0) {
2512       // We don't need to generate a Phi anymore, but we need to rename any uses
2513       // of the Phi value.
2514       unsigned NewReg = VRMap[PrevStage][LoopVal];
2515       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
2516                             Def, NewReg);
2517       if (VRMap[CurStageNum].count(LoopVal))
2518         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2519     }
2520     // Adjust the number of Phis needed depending on the number of prologs left,
2521     // and the distance from where the Phi is first scheduled.
2522     unsigned NumPhis = NumStages;
2523     if (!InKernel && (int)PrologStage < LoopValStage)
2524       // The NumPhis is the maximum number of new Phis needed during the steady
2525       // state. If the Phi has not been scheduled in current prolog, then we
2526       // need to generate less Phis.
2527       NumPhis = std::max((int)NumPhis - (int)(LoopValStage - PrologStage), 1);
2528     // The number of Phis cannot exceed the number of prolog stages. Each
2529     // stage can potentially define two values.
2530     NumPhis = std::min(NumPhis, PrologStage + 2);
2531 
2532     unsigned NewReg = 0;
2533 
2534     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2535     // In the epilog, we may need to look back one stage to get the correct
2536     // Phi name because the epilog and prolog blocks execute the same stage.
2537     // The correct name is from the previous block only when the Phi has
2538     // been completely scheduled prior to the epilog, and Phi value is not
2539     // needed in multiple stages.
2540     int StageDiff = 0;
2541     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2542         NumPhis == 1)
2543       StageDiff = 1;
2544     // Adjust the computations below when the phi and the loop definition
2545     // are scheduled in different stages.
2546     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2547       StageDiff = StageScheduled - LoopValStage;
2548     for (unsigned np = 0; np < NumPhis; ++np) {
2549       // If the Phi hasn't been scheduled, then use the initial Phi operand
2550       // value. Otherwise, use the scheduled version of the instruction. This
2551       // is a little complicated when a Phi references another Phi.
2552       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2553         PhiOp1 = InitVal;
2554       // Check if the Phi has already been scheduled in a prolog stage.
2555       else if (PrologStage >= AccessStage + StageDiff + np &&
2556                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2557         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2558       // Check if the Phi has already been scheduled, but the loop intruction
2559       // is either another Phi, or doesn't occur in the loop.
2560       else if (PrologStage >= AccessStage + StageDiff + np) {
2561         // If the Phi references another Phi, we need to examine the other
2562         // Phi to get the correct value.
2563         PhiOp1 = LoopVal;
2564         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2565         int Indirects = 1;
2566         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2567           int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2568           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2569             PhiOp1 = getInitPhiReg(*InstOp1, BB);
2570           else
2571             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2572           InstOp1 = MRI.getVRegDef(PhiOp1);
2573           int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2574           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2575           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2576               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2577             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2578             break;
2579           }
2580           ++Indirects;
2581         }
2582       } else
2583         PhiOp1 = InitVal;
2584       // If this references a generated Phi in the kernel, get the Phi operand
2585       // from the incoming block.
2586       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2587         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2588           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2589 
2590       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2591       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2592       // In the epilog, a map lookup is needed to get the value from the kernel,
2593       // or previous epilog block. How is does this depends on if the
2594       // instruction is scheduled in the previous block.
2595       if (!InKernel) {
2596         int StageDiffAdj = 0;
2597         if (LoopValStage != -1 && StageScheduled > LoopValStage)
2598           StageDiffAdj = StageScheduled - LoopValStage;
2599         // Use the loop value defined in the kernel, unless the kernel
2600         // contains the last definition of the Phi.
2601         if (np == 0 && PrevStage == LastStageNum &&
2602             (StageScheduled != 0 || LoopValStage != 0) &&
2603             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2604           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2605         // Use the value defined by the Phi. We add one because we switch
2606         // from looking at the loop value to the Phi definition.
2607         else if (np > 0 && PrevStage == LastStageNum &&
2608                  VRMap[PrevStage - np + 1].count(Def))
2609           PhiOp2 = VRMap[PrevStage - np + 1][Def];
2610         // Use the loop value defined in the kernel.
2611         else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
2612                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2613           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2614         // Use the value defined by the Phi, unless we're generating the first
2615         // epilog and the Phi refers to a Phi in a different stage.
2616         else if (VRMap[PrevStage - np].count(Def) &&
2617                  (!LoopDefIsPhi || PrevStage != LastStageNum))
2618           PhiOp2 = VRMap[PrevStage - np][Def];
2619       }
2620 
2621       // Check if we can reuse an existing Phi. This occurs when a Phi
2622       // references another Phi, and the other Phi is scheduled in an
2623       // earlier stage. We can try to reuse an existing Phi up until the last
2624       // stage of the current Phi.
2625       if (LoopDefIsPhi && VRMap[CurStageNum].count(LoopVal) &&
2626           LoopValStage >= (int)(CurStageNum - LastStageNum)) {
2627         int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2628         int StageDiff = (StageScheduled - LoopValStage);
2629         LVNumStages -= StageDiff;
2630         if (LVNumStages > (int)np) {
2631           NewReg = PhiOp2;
2632           unsigned ReuseStage = CurStageNum;
2633           if (Schedule.isLoopCarried(this, *PhiInst))
2634             ReuseStage -= LVNumStages;
2635           // Check if the Phi to reuse has been generated yet. If not, then
2636           // there is nothing to reuse.
2637           if (VRMap[ReuseStage].count(LoopVal)) {
2638             NewReg = VRMap[ReuseStage][LoopVal];
2639 
2640             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2641                                   &*BBI, Def, NewReg);
2642             // Update the map with the new Phi name.
2643             VRMap[CurStageNum - np][Def] = NewReg;
2644             PhiOp2 = NewReg;
2645             if (VRMap[LastStageNum - np - 1].count(LoopVal))
2646               PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
2647 
2648             if (IsLast && np == NumPhis - 1)
2649               replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2650             continue;
2651           }
2652         } else if (StageDiff > 0 &&
2653                    VRMap[CurStageNum - StageDiff - np].count(LoopVal))
2654           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2655       }
2656 
2657       const TargetRegisterClass *RC = MRI.getRegClass(Def);
2658       NewReg = MRI.createVirtualRegister(RC);
2659 
2660       MachineInstrBuilder NewPhi =
2661           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2662                   TII->get(TargetOpcode::PHI), NewReg);
2663       NewPhi.addReg(PhiOp1).addMBB(BB1);
2664       NewPhi.addReg(PhiOp2).addMBB(BB2);
2665       if (np == 0)
2666         InstrMap[NewPhi] = &*BBI;
2667 
2668       // We define the Phis after creating the new pipelined code, so
2669       // we need to rename the Phi values in scheduled instructions.
2670 
2671       unsigned PrevReg = 0;
2672       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2673         PrevReg = VRMap[PrevStage - np][LoopVal];
2674       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2675                             Def, NewReg, PrevReg);
2676       // If the Phi has been scheduled, use the new name for rewriting.
2677       if (VRMap[CurStageNum - np].count(Def)) {
2678         unsigned R = VRMap[CurStageNum - np][Def];
2679         rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2680                               R, NewReg);
2681       }
2682 
2683       // Check if we need to rename any uses that occurs after the loop. The
2684       // register to replace depends on whether the Phi is scheduled in the
2685       // epilog.
2686       if (IsLast && np == NumPhis - 1)
2687         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2688 
2689       // In the kernel, a dependent Phi uses the value from this Phi.
2690       if (InKernel)
2691         PhiOp2 = NewReg;
2692 
2693       // Update the map with the new Phi name.
2694       VRMap[CurStageNum - np][Def] = NewReg;
2695     }
2696 
2697     while (NumPhis++ < NumStages) {
2698       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2699                             &*BBI, Def, NewReg, 0);
2700     }
2701 
2702     // Check if we need to rename a Phi that has been eliminated due to
2703     // scheduling.
2704     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2705       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2706   }
2707 }
2708 
2709 /// Generate Phis for the specified block in the generated pipelined code.
2710 /// These are new Phis needed because the definition is scheduled after the
2711 /// use in the pipelened sequence.
2712 void SwingSchedulerDAG::generatePhis(
2713     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2714     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2715     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2716     bool IsLast) {
2717   // Compute the stage number that contains the initial Phi value, and
2718   // the Phi from the previous stage.
2719   unsigned PrologStage = 0;
2720   unsigned PrevStage = 0;
2721   unsigned StageDiff = CurStageNum - LastStageNum;
2722   bool InKernel = (StageDiff == 0);
2723   if (InKernel) {
2724     PrologStage = LastStageNum - 1;
2725     PrevStage = CurStageNum;
2726   } else {
2727     PrologStage = LastStageNum - StageDiff;
2728     PrevStage = LastStageNum + StageDiff - 1;
2729   }
2730 
2731   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2732                                    BBE = BB->instr_end();
2733        BBI != BBE; ++BBI) {
2734     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2735       MachineOperand &MO = BBI->getOperand(i);
2736       if (!MO.isReg() || !MO.isDef() ||
2737           !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2738         continue;
2739 
2740       int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2741       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2742       unsigned Def = MO.getReg();
2743       unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2744       // An instruction scheduled in stage 0 and is used after the loop
2745       // requires a phi in the epilog for the last definition from either
2746       // the kernel or prolog.
2747       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2748           hasUseAfterLoop(Def, BB, MRI))
2749         NumPhis = 1;
2750       if (!InKernel && (unsigned)StageScheduled > PrologStage)
2751         continue;
2752 
2753       unsigned PhiOp2 = VRMap[PrevStage][Def];
2754       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2755         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2756           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2757       // The number of Phis can't exceed the number of prolog stages. The
2758       // prolog stage number is zero based.
2759       if (NumPhis > PrologStage + 1 - StageScheduled)
2760         NumPhis = PrologStage + 1 - StageScheduled;
2761       for (unsigned np = 0; np < NumPhis; ++np) {
2762         unsigned PhiOp1 = VRMap[PrologStage][Def];
2763         if (np <= PrologStage)
2764           PhiOp1 = VRMap[PrologStage - np][Def];
2765         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2766           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2767             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2768           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2769             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2770         }
2771         if (!InKernel)
2772           PhiOp2 = VRMap[PrevStage - np][Def];
2773 
2774         const TargetRegisterClass *RC = MRI.getRegClass(Def);
2775         unsigned NewReg = MRI.createVirtualRegister(RC);
2776 
2777         MachineInstrBuilder NewPhi =
2778             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2779                     TII->get(TargetOpcode::PHI), NewReg);
2780         NewPhi.addReg(PhiOp1).addMBB(BB1);
2781         NewPhi.addReg(PhiOp2).addMBB(BB2);
2782         if (np == 0)
2783           InstrMap[NewPhi] = &*BBI;
2784 
2785         // Rewrite uses and update the map. The actions depend upon whether
2786         // we generating code for the kernel or epilog blocks.
2787         if (InKernel) {
2788           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2789                                 &*BBI, PhiOp1, NewReg);
2790           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2791                                 &*BBI, PhiOp2, NewReg);
2792 
2793           PhiOp2 = NewReg;
2794           VRMap[PrevStage - np - 1][Def] = NewReg;
2795         } else {
2796           VRMap[CurStageNum - np][Def] = NewReg;
2797           if (np == NumPhis - 1)
2798             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2799                                   &*BBI, Def, NewReg);
2800         }
2801         if (IsLast && np == NumPhis - 1)
2802           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2803       }
2804     }
2805   }
2806 }
2807 
2808 /// Remove instructions that generate values with no uses.
2809 /// Typically, these are induction variable operations that generate values
2810 /// used in the loop itself.  A dead instruction has a definition with
2811 /// no uses, or uses that occur in the original loop only.
2812 void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2813                                                MBBVectorTy &EpilogBBs) {
2814   // For each epilog block, check that the value defined by each instruction
2815   // is used.  If not, delete it.
2816   for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2817                                      MBE = EpilogBBs.rend();
2818        MBB != MBE; ++MBB)
2819     for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2820                                                    ME = (*MBB)->instr_rend();
2821          MI != ME;) {
2822       // From DeadMachineInstructionElem. Don't delete inline assembly.
2823       if (MI->isInlineAsm()) {
2824         ++MI;
2825         continue;
2826       }
2827       bool SawStore = false;
2828       // Check if it's safe to remove the instruction due to side effects.
2829       // We can, and want to, remove Phis here.
2830       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2831         ++MI;
2832         continue;
2833       }
2834       bool used = true;
2835       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2836                                       MOE = MI->operands_end();
2837            MOI != MOE; ++MOI) {
2838         if (!MOI->isReg() || !MOI->isDef())
2839           continue;
2840         unsigned reg = MOI->getReg();
2841         unsigned realUses = 0;
2842         for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2843                                                EI = MRI.use_end();
2844              UI != EI; ++UI) {
2845           // Check if there are any uses that occur only in the original
2846           // loop.  If so, that's not a real use.
2847           if (UI->getParent()->getParent() != BB) {
2848             realUses++;
2849             used = true;
2850             break;
2851           }
2852         }
2853         if (realUses > 0)
2854           break;
2855         used = false;
2856       }
2857       if (!used) {
2858         MI->eraseFromParent();
2859         ME = (*MBB)->instr_rend();
2860         continue;
2861       }
2862       ++MI;
2863     }
2864   // In the kernel block, check if we can remove a Phi that generates a value
2865   // used in an instruction removed in the epilog block.
2866   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2867                                    BBE = KernelBB->getFirstNonPHI();
2868        BBI != BBE;) {
2869     MachineInstr *MI = &*BBI;
2870     ++BBI;
2871     unsigned reg = MI->getOperand(0).getReg();
2872     if (MRI.use_begin(reg) == MRI.use_end()) {
2873       MI->eraseFromParent();
2874     }
2875   }
2876 }
2877 
2878 /// For loop carried definitions, we split the lifetime of a virtual register
2879 /// that has uses past the definition in the next iteration. A copy with a new
2880 /// virtual register is inserted before the definition, which helps with
2881 /// generating a better register assignment.
2882 ///
2883 ///   v1 = phi(a, v2)     v1 = phi(a, v2)
2884 ///   v2 = phi(b, v3)     v2 = phi(b, v3)
2885 ///   v3 = ..             v4 = copy v1
2886 ///   .. = V1             v3 = ..
2887 ///                       .. = v4
2888 void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2889                                        MBBVectorTy &EpilogBBs,
2890                                        SMSchedule &Schedule) {
2891   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2892   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2893                                    BBF = KernelBB->getFirstNonPHI();
2894        BBI != BBF; ++BBI) {
2895     unsigned Def = BBI->getOperand(0).getReg();
2896     // Check for any Phi definition that used as an operand of another Phi
2897     // in the same block.
2898     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2899                                                  E = MRI.use_instr_end();
2900          I != E; ++I) {
2901       if (I->isPHI() && I->getParent() == KernelBB) {
2902         // Get the loop carried definition.
2903         unsigned LCDef = getLoopPhiReg(*BBI, KernelBB);
2904         if (!LCDef)
2905           continue;
2906         MachineInstr *MI = MRI.getVRegDef(LCDef);
2907         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2908           continue;
2909         // Search through the rest of the block looking for uses of the Phi
2910         // definition. If one occurs, then split the lifetime.
2911         unsigned SplitReg = 0;
2912         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2913                                     KernelBB->instr_end()))
2914           if (BBJ.readsRegister(Def)) {
2915             // We split the lifetime when we find the first use.
2916             if (SplitReg == 0) {
2917               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2918               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2919                       TII->get(TargetOpcode::COPY), SplitReg)
2920                   .addReg(Def);
2921             }
2922             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2923           }
2924         if (!SplitReg)
2925           continue;
2926         // Search through each of the epilog blocks for any uses to be renamed.
2927         for (auto &Epilog : EpilogBBs)
2928           for (auto &I : *Epilog)
2929             if (I.readsRegister(Def))
2930               I.substituteRegister(Def, SplitReg, 0, *TRI);
2931         break;
2932       }
2933     }
2934   }
2935 }
2936 
2937 /// Remove the incoming block from the Phis in a basic block.
2938 static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2939   for (MachineInstr &MI : *BB) {
2940     if (!MI.isPHI())
2941       break;
2942     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2943       if (MI.getOperand(i + 1).getMBB() == Incoming) {
2944         MI.RemoveOperand(i + 1);
2945         MI.RemoveOperand(i);
2946         break;
2947       }
2948   }
2949 }
2950 
2951 /// Create branches from each prolog basic block to the appropriate epilog
2952 /// block.  These edges are needed if the loop ends before reaching the
2953 /// kernel.
2954 void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
2955                                     MachineBasicBlock *KernelBB,
2956                                     MBBVectorTy &EpilogBBs,
2957                                     SMSchedule &Schedule, ValueMapTy *VRMap) {
2958   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2959   MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2960   MachineInstr *Cmp = Pass.LI.LoopCompare;
2961   MachineBasicBlock *LastPro = KernelBB;
2962   MachineBasicBlock *LastEpi = KernelBB;
2963 
2964   // Start from the blocks connected to the kernel and work "out"
2965   // to the first prolog and the last epilog blocks.
2966   SmallVector<MachineInstr *, 4> PrevInsts;
2967   unsigned MaxIter = PrologBBs.size() - 1;
2968   unsigned LC = UINT_MAX;
2969   unsigned LCMin = UINT_MAX;
2970   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2971     // Add branches to the prolog that go to the corresponding
2972     // epilog, and the fall-thru prolog/kernel block.
2973     MachineBasicBlock *Prolog = PrologBBs[j];
2974     MachineBasicBlock *Epilog = EpilogBBs[i];
2975     // We've executed one iteration, so decrement the loop count and check for
2976     // the loop end.
2977     SmallVector<MachineOperand, 4> Cond;
2978     // Check if the LOOP0 has already been removed. If so, then there is no need
2979     // to reduce the trip count.
2980     if (LC != 0)
2981       LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
2982                                 MaxIter);
2983 
2984     // Record the value of the first trip count, which is used to determine if
2985     // branches and blocks can be removed for constant trip counts.
2986     if (LCMin == UINT_MAX)
2987       LCMin = LC;
2988 
2989     unsigned numAdded = 0;
2990     if (TargetRegisterInfo::isVirtualRegister(LC)) {
2991       Prolog->addSuccessor(Epilog);
2992       numAdded = TII->InsertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
2993     } else if (j >= LCMin) {
2994       Prolog->addSuccessor(Epilog);
2995       Prolog->removeSuccessor(LastPro);
2996       LastEpi->removeSuccessor(Epilog);
2997       numAdded = TII->InsertBranch(*Prolog, Epilog, 0, Cond, DebugLoc());
2998       removePhis(Epilog, LastEpi);
2999       // Remove the blocks that are no longer referenced.
3000       if (LastPro != LastEpi) {
3001         LastEpi->clear();
3002         LastEpi->eraseFromParent();
3003       }
3004       LastPro->clear();
3005       LastPro->eraseFromParent();
3006     } else {
3007       numAdded = TII->InsertBranch(*Prolog, LastPro, 0, Cond, DebugLoc());
3008       removePhis(Epilog, Prolog);
3009     }
3010     LastPro = Prolog;
3011     LastEpi = Epilog;
3012     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
3013                                                    E = Prolog->instr_rend();
3014          I != E && numAdded > 0; ++I, --numAdded)
3015       updateInstruction(&*I, false, j, 0, Schedule, VRMap);
3016   }
3017 }
3018 
3019 /// Return true if we can compute the amount the instruction changes
3020 /// during each iteration. Set Delta to the amount of the change.
3021 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
3022   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3023   unsigned BaseReg;
3024   int64_t Offset;
3025   if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
3026     return false;
3027 
3028   MachineRegisterInfo &MRI = MF.getRegInfo();
3029   // Check if there is a Phi. If so, get the definition in the loop.
3030   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
3031   if (BaseDef && BaseDef->isPHI()) {
3032     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
3033     BaseDef = MRI.getVRegDef(BaseReg);
3034   }
3035   if (!BaseDef)
3036     return false;
3037 
3038   int D = 0;
3039   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
3040     return false;
3041 
3042   Delta = D;
3043   return true;
3044 }
3045 
3046 /// Update the memory operand with a new offset when the pipeliner
3047 /// generate a new copy of the instruction that refers to a
3048 /// different memory location.
3049 void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
3050                                           MachineInstr &OldMI, unsigned Num) {
3051   if (Num == 0)
3052     return;
3053   // If the instruction has memory operands, then adjust the offset
3054   // when the instruction appears in different stages.
3055   unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin();
3056   if (NumRefs == 0)
3057     return;
3058   MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs);
3059   unsigned Refs = 0;
3060   for (MachineInstr::mmo_iterator I = NewMI.memoperands_begin(),
3061                                   E = NewMI.memoperands_end();
3062        I != E; ++I) {
3063     if ((*I)->isVolatile() || (*I)->isInvariant() || (!(*I)->getValue())) {
3064       NewMemRefs[Refs++] = *I;
3065       continue;
3066     }
3067     unsigned Delta;
3068     if (computeDelta(OldMI, Delta)) {
3069       int64_t AdjOffset = Delta * Num;
3070       NewMemRefs[Refs++] =
3071           MF.getMachineMemOperand(*I, AdjOffset, (*I)->getSize());
3072     } else
3073       NewMemRefs[Refs++] = MF.getMachineMemOperand(*I, 0, UINT64_MAX);
3074   }
3075   NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
3076 }
3077 
3078 /// Clone the instruction for the new pipelined loop and update the
3079 /// memory operands, if needed.
3080 MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
3081                                             unsigned CurStageNum,
3082                                             unsigned InstStageNum) {
3083   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3084   // Check for tied operands in inline asm instructions. This should be handled
3085   // elsewhere, but I'm not sure of the best solution.
3086   if (OldMI->isInlineAsm())
3087     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
3088       const auto &MO = OldMI->getOperand(i);
3089       if (MO.isReg() && MO.isUse())
3090         break;
3091       unsigned UseIdx;
3092       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
3093         NewMI->tieOperands(i, UseIdx);
3094     }
3095   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3096   return NewMI;
3097 }
3098 
3099 /// Clone the instruction for the new pipelined loop. If needed, this
3100 /// function updates the instruction using the values saved in the
3101 /// InstrChanges structure.
3102 MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
3103                                                      unsigned CurStageNum,
3104                                                      unsigned InstStageNum,
3105                                                      SMSchedule &Schedule) {
3106   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
3107   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3108       InstrChanges.find(getSUnit(OldMI));
3109   if (It != InstrChanges.end()) {
3110     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3111     unsigned BasePos, OffsetPos;
3112     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
3113       return nullptr;
3114     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
3115     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
3116     if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
3117       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
3118     NewMI->getOperand(OffsetPos).setImm(NewOffset);
3119   }
3120   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3121   return NewMI;
3122 }
3123 
3124 /// Update the machine instruction with new virtual registers.  This
3125 /// function may change the defintions and/or uses.
3126 void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
3127                                           unsigned CurStageNum,
3128                                           unsigned InstrStageNum,
3129                                           SMSchedule &Schedule,
3130                                           ValueMapTy *VRMap) {
3131   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
3132     MachineOperand &MO = NewMI->getOperand(i);
3133     if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3134       continue;
3135     unsigned reg = MO.getReg();
3136     if (MO.isDef()) {
3137       // Create a new virtual register for the definition.
3138       const TargetRegisterClass *RC = MRI.getRegClass(reg);
3139       unsigned NewReg = MRI.createVirtualRegister(RC);
3140       MO.setReg(NewReg);
3141       VRMap[CurStageNum][reg] = NewReg;
3142       if (LastDef)
3143         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
3144     } else if (MO.isUse()) {
3145       MachineInstr *Def = MRI.getVRegDef(reg);
3146       // Compute the stage that contains the last definition for instruction.
3147       int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
3148       unsigned StageNum = CurStageNum;
3149       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
3150         // Compute the difference in stages between the defintion and the use.
3151         unsigned StageDiff = (InstrStageNum - DefStageNum);
3152         // Make an adjustment to get the last definition.
3153         StageNum -= StageDiff;
3154       }
3155       if (VRMap[StageNum].count(reg))
3156         MO.setReg(VRMap[StageNum][reg]);
3157     }
3158   }
3159 }
3160 
3161 /// Return the instruction in the loop that defines the register.
3162 /// If the definition is a Phi, then follow the Phi operand to
3163 /// the instruction in the loop.
3164 MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
3165   SmallPtrSet<MachineInstr *, 8> Visited;
3166   MachineInstr *Def = MRI.getVRegDef(Reg);
3167   while (Def->isPHI()) {
3168     if (!Visited.insert(Def).second)
3169       break;
3170     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3171       if (Def->getOperand(i + 1).getMBB() == BB) {
3172         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3173         break;
3174       }
3175   }
3176   return Def;
3177 }
3178 
3179 /// Return the new name for the value from the previous stage.
3180 unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3181                                           unsigned LoopVal, unsigned LoopStage,
3182                                           ValueMapTy *VRMap,
3183                                           MachineBasicBlock *BB) {
3184   unsigned PrevVal = 0;
3185   if (StageNum > PhiStage) {
3186     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3187     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3188       // The name is defined in the previous stage.
3189       PrevVal = VRMap[StageNum - 1][LoopVal];
3190     else if (VRMap[StageNum].count(LoopVal))
3191       // The previous name is defined in the current stage when the instruction
3192       // order is swapped.
3193       PrevVal = VRMap[StageNum][LoopVal];
3194     else if (!LoopInst->isPHI())
3195       // The loop value hasn't yet been scheduled.
3196       PrevVal = LoopVal;
3197     else if (StageNum == PhiStage + 1)
3198       // The loop value is another phi, which has not been scheduled.
3199       PrevVal = getInitPhiReg(*LoopInst, BB);
3200     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3201       // The loop value is another phi, which has been scheduled.
3202       PrevVal =
3203           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3204                         LoopStage, VRMap, BB);
3205   }
3206   return PrevVal;
3207 }
3208 
3209 /// Rewrite the Phi values in the specified block to use the mappings
3210 /// from the initial operand. Once the Phi is scheduled, we switch
3211 /// to using the loop value instead of the Phi value, so those names
3212 /// do not need to be rewritten.
3213 void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3214                                          unsigned StageNum,
3215                                          SMSchedule &Schedule,
3216                                          ValueMapTy *VRMap,
3217                                          InstrMapTy &InstrMap) {
3218   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
3219                                    BBE = BB->getFirstNonPHI();
3220        BBI != BBE; ++BBI) {
3221     unsigned InitVal = 0;
3222     unsigned LoopVal = 0;
3223     getPhiRegs(*BBI, BB, InitVal, LoopVal);
3224     unsigned PhiDef = BBI->getOperand(0).getReg();
3225 
3226     unsigned PhiStage =
3227         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3228     unsigned LoopStage =
3229         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3230     unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3231     if (NumPhis > StageNum)
3232       NumPhis = StageNum;
3233     for (unsigned np = 0; np <= NumPhis; ++np) {
3234       unsigned NewVal =
3235           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3236       if (!NewVal)
3237         NewVal = InitVal;
3238       rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &*BBI,
3239                             PhiDef, NewVal);
3240     }
3241   }
3242 }
3243 
3244 /// Rewrite a previously scheduled instruction to use the register value
3245 /// from the new instruction. Make sure the instruction occurs in the
3246 /// basic block, and we don't change the uses in the new instruction.
3247 void SwingSchedulerDAG::rewriteScheduledInstr(
3248     MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3249     unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3250     unsigned NewReg, unsigned PrevReg) {
3251   bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3252   int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3253   // Rewrite uses that have been scheduled already to use the new
3254   // Phi register.
3255   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3256                                          EI = MRI.use_end();
3257        UI != EI;) {
3258     MachineOperand &UseOp = *UI;
3259     MachineInstr *UseMI = UseOp.getParent();
3260     ++UI;
3261     if (UseMI->getParent() != BB)
3262       continue;
3263     if (UseMI->isPHI()) {
3264       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3265         continue;
3266       if (getLoopPhiReg(*UseMI, BB) != OldReg)
3267         continue;
3268     }
3269     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3270     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3271     SUnit *OrigMISU = getSUnit(OrigInstr->second);
3272     int StageSched = Schedule.stageScheduled(OrigMISU);
3273     int CycleSched = Schedule.cycleScheduled(OrigMISU);
3274     unsigned ReplaceReg = 0;
3275     // This is the stage for the scheduled instruction.
3276     if (StagePhi == StageSched && Phi->isPHI()) {
3277       int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3278       if (PrevReg && InProlog)
3279         ReplaceReg = PrevReg;
3280       else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3281                (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3282         ReplaceReg = PrevReg;
3283       else
3284         ReplaceReg = NewReg;
3285     }
3286     // The scheduled instruction occurs before the scheduled Phi, and the
3287     // Phi is not loop carried.
3288     if (!InProlog && StagePhi + 1 == StageSched &&
3289         !Schedule.isLoopCarried(this, *Phi))
3290       ReplaceReg = NewReg;
3291     if (StagePhi > StageSched && Phi->isPHI())
3292       ReplaceReg = NewReg;
3293     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3294       ReplaceReg = NewReg;
3295     if (ReplaceReg) {
3296       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3297       UseOp.setReg(ReplaceReg);
3298     }
3299   }
3300 }
3301 
3302 /// Check if we can change the instruction to use an offset value from the
3303 /// previous iteration. If so, return true and set the base and offset values
3304 /// so that we can rewrite the load, if necessary.
3305 ///   v1 = Phi(v0, v3)
3306 ///   v2 = load v1, 0
3307 ///   v3 = post_store v1, 4, x
3308 /// This function enables the load to be rewritten as v2 = load v3, 4.
3309 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3310                                               unsigned &BasePos,
3311                                               unsigned &OffsetPos,
3312                                               unsigned &NewBase,
3313                                               int64_t &Offset) {
3314   // Get the load instruction.
3315   if (TII->isPostIncrement(*MI))
3316     return false;
3317   unsigned BasePosLd, OffsetPosLd;
3318   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
3319     return false;
3320   unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3321 
3322   // Look for the Phi instruction.
3323   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
3324   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3325   if (!Phi || !Phi->isPHI())
3326     return false;
3327   // Get the register defined in the loop block.
3328   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3329   if (!PrevReg)
3330     return false;
3331 
3332   // Check for the post-increment load/store instruction.
3333   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3334   if (!PrevDef || PrevDef == MI)
3335     return false;
3336 
3337   if (!TII->isPostIncrement(*PrevDef))
3338     return false;
3339 
3340   unsigned BasePos1 = 0, OffsetPos1 = 0;
3341   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3342     return false;
3343 
3344   // Make sure offset values are both positive or both negative.
3345   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3346   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
3347   if ((LoadOffset >= 0) != (StoreOffset >= 0))
3348     return false;
3349 
3350   // Set the return value once we determine that we return true.
3351   BasePos = BasePosLd;
3352   OffsetPos = OffsetPosLd;
3353   NewBase = PrevReg;
3354   Offset = StoreOffset;
3355   return true;
3356 }
3357 
3358 /// Apply changes to the instruction if needed. The changes are need
3359 /// to improve the scheduling and depend up on the final schedule.
3360 MachineInstr *SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
3361                                                   SMSchedule &Schedule,
3362                                                   bool UpdateDAG) {
3363   SUnit *SU = getSUnit(MI);
3364   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3365       InstrChanges.find(SU);
3366   if (It != InstrChanges.end()) {
3367     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3368     unsigned BasePos, OffsetPos;
3369     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3370       return nullptr;
3371     unsigned BaseReg = MI->getOperand(BasePos).getReg();
3372     MachineInstr *LoopDef = findDefInLoop(BaseReg);
3373     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3374     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3375     int BaseStageNum = Schedule.stageScheduled(SU);
3376     int BaseCycleNum = Schedule.cycleScheduled(SU);
3377     if (BaseStageNum < DefStageNum) {
3378       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3379       int OffsetDiff = DefStageNum - BaseStageNum;
3380       if (DefCycleNum < BaseCycleNum) {
3381         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3382         if (OffsetDiff > 0)
3383           --OffsetDiff;
3384       }
3385       int64_t NewOffset =
3386           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3387       NewMI->getOperand(OffsetPos).setImm(NewOffset);
3388       if (UpdateDAG) {
3389         SU->setInstr(NewMI);
3390         MISUnitMap[NewMI] = SU;
3391       }
3392       NewMIs.insert(NewMI);
3393       return NewMI;
3394     }
3395   }
3396   return nullptr;
3397 }
3398 
3399 /// Return true for an order dependence that is loop carried potentially.
3400 /// An order dependence is loop carried if the destination defines a value
3401 /// that may be used by the source in a subsequent iteration.
3402 bool SwingSchedulerDAG::isLoopCarriedOrder(SUnit *Source, const SDep &Dep,
3403                                            bool isSucc) {
3404   if (!isOrder(Source, Dep) || Dep.isArtificial())
3405     return false;
3406 
3407   if (!SwpPruneLoopCarried)
3408     return true;
3409 
3410   MachineInstr *SI = Source->getInstr();
3411   MachineInstr *DI = Dep.getSUnit()->getInstr();
3412   if (!isSucc)
3413     std::swap(SI, DI);
3414   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3415 
3416   // Assume ordered loads and stores may have a loop carried dependence.
3417   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
3418       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3419     return true;
3420 
3421   // Only chain dependences between a load and store can be loop carried.
3422   if (!DI->mayStore() || !SI->mayLoad())
3423     return false;
3424 
3425   unsigned DeltaS, DeltaD;
3426   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3427     return true;
3428 
3429   unsigned BaseRegS, BaseRegD;
3430   int64_t OffsetS, OffsetD;
3431   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3432   if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
3433       !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
3434     return true;
3435 
3436   if (BaseRegS != BaseRegD)
3437     return true;
3438 
3439   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3440   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3441 
3442   // This is the main test, which checks the offset values and the loop
3443   // increment value to determine if the accesses may be loop carried.
3444   if (OffsetS >= OffsetD)
3445     return OffsetS + AccessSizeS > DeltaS;
3446   else if (OffsetS < OffsetD)
3447     return OffsetD + AccessSizeD > DeltaD;
3448 
3449   return true;
3450 }
3451 
3452 /// Try to schedule the node at the specified StartCycle and continue
3453 /// until the node is schedule or the EndCycle is reached.  This function
3454 /// returns true if the node is scheduled.  This routine may search either
3455 /// forward or backward for a place to insert the instruction based upon
3456 /// the relative values of StartCycle and EndCycle.
3457 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3458   bool forward = true;
3459   if (StartCycle > EndCycle)
3460     forward = false;
3461 
3462   // The terminating condition depends on the direction.
3463   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3464   for (int curCycle = StartCycle; curCycle != termCycle;
3465        forward ? ++curCycle : --curCycle) {
3466 
3467     // Add the already scheduled instructions at the specified cycle to the DFA.
3468     Resources->clearResources();
3469     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3470          checkCycle <= LastCycle; checkCycle += II) {
3471       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3472 
3473       for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3474                                          E = cycleInstrs.end();
3475            I != E; ++I) {
3476         if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3477           continue;
3478         assert(Resources->canReserveResources(*(*I)->getInstr()) &&
3479                "These instructions have already been scheduled.");
3480         Resources->reserveResources(*(*I)->getInstr());
3481       }
3482     }
3483     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3484         Resources->canReserveResources(*SU->getInstr())) {
3485       DEBUG({
3486         dbgs() << "\tinsert at cycle " << curCycle << " ";
3487         SU->getInstr()->dump();
3488       });
3489 
3490       ScheduledInstrs[curCycle].push_back(SU);
3491       InstrToCycle.insert(std::make_pair(SU, curCycle));
3492       if (curCycle > LastCycle)
3493         LastCycle = curCycle;
3494       if (curCycle < FirstCycle)
3495         FirstCycle = curCycle;
3496       return true;
3497     }
3498     DEBUG({
3499       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3500       SU->getInstr()->dump();
3501     });
3502   }
3503   return false;
3504 }
3505 
3506 // Return the cycle of the earliest scheduled instruction in the chain.
3507 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3508   SmallPtrSet<SUnit *, 8> Visited;
3509   SmallVector<SDep, 8> Worklist;
3510   Worklist.push_back(Dep);
3511   int EarlyCycle = INT_MAX;
3512   while (!Worklist.empty()) {
3513     const SDep &Cur = Worklist.pop_back_val();
3514     SUnit *PrevSU = Cur.getSUnit();
3515     if (Visited.count(PrevSU))
3516       continue;
3517     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3518     if (it == InstrToCycle.end())
3519       continue;
3520     EarlyCycle = std::min(EarlyCycle, it->second);
3521     for (const auto &PI : PrevSU->Preds)
3522       if (SwingSchedulerDAG::isOrder(PrevSU, PI))
3523         Worklist.push_back(PI);
3524     Visited.insert(PrevSU);
3525   }
3526   return EarlyCycle;
3527 }
3528 
3529 // Return the cycle of the latest scheduled instruction in the chain.
3530 int SMSchedule::latestCycleInChain(const SDep &Dep) {
3531   SmallPtrSet<SUnit *, 8> Visited;
3532   SmallVector<SDep, 8> Worklist;
3533   Worklist.push_back(Dep);
3534   int LateCycle = INT_MIN;
3535   while (!Worklist.empty()) {
3536     const SDep &Cur = Worklist.pop_back_val();
3537     SUnit *SuccSU = Cur.getSUnit();
3538     if (Visited.count(SuccSU))
3539       continue;
3540     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3541     if (it == InstrToCycle.end())
3542       continue;
3543     LateCycle = std::max(LateCycle, it->second);
3544     for (const auto &SI : SuccSU->Succs)
3545       if (SwingSchedulerDAG::isOrder(SuccSU, SI))
3546         Worklist.push_back(SI);
3547     Visited.insert(SuccSU);
3548   }
3549   return LateCycle;
3550 }
3551 
3552 /// If an instruction has a use that spans multiple iterations, then
3553 /// return true. These instructions are characterized by having a back-ege
3554 /// to a Phi, which contains a reference to another Phi.
3555 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3556   for (auto &P : SU->Preds)
3557     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3558       for (auto &S : P.getSUnit()->Succs)
3559         if (S.getKind() == SDep::Order && S.getSUnit()->getInstr()->isPHI())
3560           return P.getSUnit();
3561   return nullptr;
3562 }
3563 
3564 /// Compute the scheduling start slot for the instruction.  The start slot
3565 /// depends on any predecessor or successor nodes scheduled already.
3566 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3567                               int *MinEnd, int *MaxStart, int II,
3568                               SwingSchedulerDAG *DAG) {
3569   // Iterate over each instruction that has been scheduled already.  The start
3570   // slot computuation depends on whether the previously scheduled instruction
3571   // is a predecessor or successor of the specified instruction.
3572   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3573 
3574     // Iterate over each instruction in the current cycle.
3575     for (SUnit *I : getInstructions(cycle)) {
3576       // Because we're processing a DAG for the dependences, we recognize
3577       // the back-edge in recurrences by anti dependences.
3578       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3579         const SDep &Dep = SU->Preds[i];
3580         if (Dep.getSUnit() == I) {
3581           if (!DAG->isBackedge(SU, Dep)) {
3582             int EarlyStart = cycle + DAG->getLatency(SU, Dep) -
3583                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3584             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3585             if (DAG->isLoopCarriedOrder(SU, Dep, false)) {
3586               int End = earliestCycleInChain(Dep) + (II - 1);
3587               *MinEnd = std::min(*MinEnd, End);
3588             }
3589           } else {
3590             int LateStart = cycle - DAG->getLatency(SU, Dep) +
3591                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3592             *MinLateStart = std::min(*MinLateStart, LateStart);
3593           }
3594         }
3595         // For instruction that requires multiple iterations, make sure that
3596         // the dependent instruction is not scheduled past the definition.
3597         SUnit *BE = multipleIterations(I, DAG);
3598         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3599             !SU->isPred(I))
3600           *MinLateStart = std::min(*MinLateStart, cycle);
3601       }
3602       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i)
3603         if (SU->Succs[i].getSUnit() == I) {
3604           const SDep &Dep = SU->Succs[i];
3605           if (!DAG->isBackedge(SU, Dep)) {
3606             int LateStart = cycle - DAG->getLatency(SU, Dep) +
3607                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3608             *MinLateStart = std::min(*MinLateStart, LateStart);
3609             if (DAG->isLoopCarriedOrder(SU, Dep)) {
3610               int Start = latestCycleInChain(Dep) + 1 - II;
3611               *MaxStart = std::max(*MaxStart, Start);
3612             }
3613           } else {
3614             int EarlyStart = cycle + DAG->getLatency(SU, Dep) -
3615                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3616             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3617           }
3618         }
3619     }
3620   }
3621 }
3622 
3623 /// Order the instructions within a cycle so that the definitions occur
3624 /// before the uses. Returns true if the instruction is added to the start
3625 /// of the list, or false if added to the end.
3626 bool SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
3627                                  std::deque<SUnit *> &Insts) {
3628   MachineInstr *MI = SU->getInstr();
3629   bool OrderBeforeUse = false;
3630   bool OrderAfterDef = false;
3631   bool OrderBeforeDef = false;
3632   unsigned MoveDef = 0;
3633   unsigned MoveUse = 0;
3634   int StageInst1 = stageScheduled(SU);
3635 
3636   unsigned Pos = 0;
3637   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3638        ++I, ++Pos) {
3639     // Relative order of Phis does not matter.
3640     if (MI->isPHI() && (*I)->getInstr()->isPHI())
3641       continue;
3642     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3643       MachineOperand &MO = MI->getOperand(i);
3644       if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3645         continue;
3646       unsigned Reg = MO.getReg();
3647       unsigned BasePos, OffsetPos;
3648       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3649         if (MI->getOperand(BasePos).getReg() == Reg)
3650           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3651             Reg = NewReg;
3652       bool Reads, Writes;
3653       std::tie(Reads, Writes) =
3654           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3655       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3656         OrderBeforeUse = true;
3657         MoveUse = Pos;
3658       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3659         // Add the instruction after the scheduled instruction.
3660         OrderAfterDef = true;
3661         MoveDef = Pos;
3662       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3663         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3664           OrderBeforeUse = true;
3665           MoveUse = Pos;
3666         } else {
3667           OrderAfterDef = true;
3668           MoveDef = Pos;
3669         }
3670       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3671         OrderBeforeUse = true;
3672         MoveUse = Pos;
3673         if (MoveUse != 0) {
3674           OrderAfterDef = true;
3675           MoveDef = Pos - 1;
3676         }
3677       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3678         // Add the instruction before the scheduled instruction.
3679         OrderBeforeUse = true;
3680         MoveUse = Pos;
3681       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3682                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3683         OrderBeforeDef = true;
3684         MoveUse = Pos;
3685       }
3686     }
3687     // Check for order dependences between instructions. Make sure the source
3688     // is ordered before the destination.
3689     for (auto &S : SU->Succs)
3690       if (S.getKind() == SDep::Order) {
3691         if (S.getSUnit() == *I && stageScheduled(*I) == StageInst1) {
3692           OrderBeforeUse = true;
3693           MoveUse = Pos;
3694         }
3695       } else if (TargetRegisterInfo::isPhysicalRegister(S.getReg())) {
3696         if (cycleScheduled(SU) != cycleScheduled(S.getSUnit())) {
3697           if (S.isAssignedRegDep()) {
3698             OrderAfterDef = true;
3699             MoveDef = Pos;
3700           }
3701         } else {
3702           OrderBeforeUse = true;
3703           MoveUse = Pos;
3704         }
3705       }
3706     for (auto &P : SU->Preds)
3707       if (P.getKind() == SDep::Order) {
3708         if (P.getSUnit() == *I && stageScheduled(*I) == StageInst1) {
3709           OrderAfterDef = true;
3710           MoveDef = Pos;
3711         }
3712       } else if (TargetRegisterInfo::isPhysicalRegister(P.getReg())) {
3713         if (cycleScheduled(SU) != cycleScheduled(P.getSUnit())) {
3714           if (P.isAssignedRegDep()) {
3715             OrderBeforeUse = true;
3716             MoveUse = Pos;
3717           }
3718         } else {
3719           OrderAfterDef = true;
3720           MoveDef = Pos;
3721         }
3722       }
3723   }
3724 
3725   // A circular dependence.
3726   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3727     OrderBeforeUse = false;
3728 
3729   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3730   // to a loop-carried dependence.
3731   if (OrderBeforeDef)
3732     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3733 
3734   // The uncommon case when the instruction order needs to be updated because
3735   // there is both a use and def.
3736   if (OrderBeforeUse && OrderAfterDef) {
3737     SUnit *UseSU = Insts.at(MoveUse);
3738     SUnit *DefSU = Insts.at(MoveDef);
3739     if (MoveUse > MoveDef) {
3740       Insts.erase(Insts.begin() + MoveUse);
3741       Insts.erase(Insts.begin() + MoveDef);
3742     } else {
3743       Insts.erase(Insts.begin() + MoveDef);
3744       Insts.erase(Insts.begin() + MoveUse);
3745     }
3746     if (orderDependence(SSD, UseSU, Insts)) {
3747       Insts.push_front(SU);
3748       orderDependence(SSD, DefSU, Insts);
3749       return true;
3750     }
3751     Insts.pop_back();
3752     Insts.push_back(SU);
3753     Insts.push_back(UseSU);
3754     orderDependence(SSD, DefSU, Insts);
3755     return false;
3756   }
3757   // Put the new instruction first if there is a use in the list. Otherwise,
3758   // put it at the end of the list.
3759   if (OrderBeforeUse)
3760     Insts.push_front(SU);
3761   else
3762     Insts.push_back(SU);
3763   return OrderBeforeUse;
3764 }
3765 
3766 /// Return true if the scheduled Phi has a loop carried operand.
3767 bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3768   if (!Phi.isPHI())
3769     return false;
3770   assert(Phi.isPHI() && "Expecing a Phi.");
3771   SUnit *DefSU = SSD->getSUnit(&Phi);
3772   unsigned DefCycle = cycleScheduled(DefSU);
3773   int DefStage = stageScheduled(DefSU);
3774 
3775   unsigned InitVal = 0;
3776   unsigned LoopVal = 0;
3777   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3778   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3779   if (!UseSU)
3780     return true;
3781   if (UseSU->getInstr()->isPHI())
3782     return true;
3783   unsigned LoopCycle = cycleScheduled(UseSU);
3784   int LoopStage = stageScheduled(UseSU);
3785   return LoopCycle > DefCycle ||
3786          (LoopCycle <= DefCycle && LoopStage <= DefStage);
3787 }
3788 
3789 /// Return true if the instruction is a definition that is loop carried
3790 /// and defines the use on the next iteration.
3791 ///        v1 = phi(v2, v3)
3792 ///  (Def) v3 = op v1
3793 ///  (MO)   = v1
3794 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
3795 /// register.
3796 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3797                                        MachineInstr *Def, MachineOperand &MO) {
3798   if (!MO.isReg())
3799     return false;
3800   if (Def->isPHI())
3801     return false;
3802   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3803   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3804     return false;
3805   if (!isLoopCarried(SSD, *Phi))
3806     return false;
3807   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3808   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3809     MachineOperand &DMO = Def->getOperand(i);
3810     if (!DMO.isReg() || !DMO.isDef())
3811       continue;
3812     if (DMO.getReg() == LoopReg)
3813       return true;
3814   }
3815   return false;
3816 }
3817 
3818 // Check if the generated schedule is valid. This function checks if
3819 // an instruction that uses a physical register is scheduled in a
3820 // different stage than the definition. The pipeliner does not handle
3821 // physical register values that may cross a basic block boundary.
3822 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3823   for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3824     SUnit &SU = SSD->SUnits[i];
3825     if (!SU.hasPhysRegDefs)
3826       continue;
3827     int StageDef = stageScheduled(&SU);
3828     assert(StageDef != -1 && "Instruction should have been scheduled.");
3829     for (auto &SI : SU.Succs)
3830       if (SI.isAssignedRegDep())
3831         if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
3832           if (stageScheduled(SI.getSUnit()) != StageDef)
3833             return false;
3834   }
3835   return true;
3836 }
3837 
3838 /// After the schedule has been formed, call this function to combine
3839 /// the instructions from the different stages/cycles.  That is, this
3840 /// function creates a schedule that represents a single iteration.
3841 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3842   // Move all instructions to the first stage from later stages.
3843   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3844     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3845          ++stage) {
3846       std::deque<SUnit *> &cycleInstrs =
3847           ScheduledInstrs[cycle + (stage * InitiationInterval)];
3848       for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3849                                                  E = cycleInstrs.rend();
3850            I != E; ++I)
3851         ScheduledInstrs[cycle].push_front(*I);
3852     }
3853   }
3854   // Iterate over the definitions in each instruction, and compute the
3855   // stage difference for each use.  Keep the maximum value.
3856   for (auto &I : InstrToCycle) {
3857     int DefStage = stageScheduled(I.first);
3858     MachineInstr *MI = I.first->getInstr();
3859     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3860       MachineOperand &Op = MI->getOperand(i);
3861       if (!Op.isReg() || !Op.isDef())
3862         continue;
3863 
3864       unsigned Reg = Op.getReg();
3865       unsigned MaxDiff = 0;
3866       bool PhiIsSwapped = false;
3867       for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3868                                              EI = MRI.use_end();
3869            UI != EI; ++UI) {
3870         MachineOperand &UseOp = *UI;
3871         MachineInstr *UseMI = UseOp.getParent();
3872         SUnit *SUnitUse = SSD->getSUnit(UseMI);
3873         int UseStage = stageScheduled(SUnitUse);
3874         unsigned Diff = 0;
3875         if (UseStage != -1 && UseStage >= DefStage)
3876           Diff = UseStage - DefStage;
3877         if (MI->isPHI()) {
3878           if (isLoopCarried(SSD, *MI))
3879             ++Diff;
3880           else
3881             PhiIsSwapped = true;
3882         }
3883         MaxDiff = std::max(Diff, MaxDiff);
3884       }
3885       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3886     }
3887   }
3888 
3889   // Erase all the elements in the later stages. Only one iteration should
3890   // remain in the scheduled list, and it contains all the instructions.
3891   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3892     ScheduledInstrs.erase(cycle);
3893 
3894   // Change the registers in instruction as specified in the InstrChanges
3895   // map. We need to use the new registers to create the correct order.
3896   for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3897     SUnit *SU = &SSD->SUnits[i];
3898     SSD->applyInstrChange(SU->getInstr(), *this, true);
3899   }
3900 
3901   // Reorder the instructions in each cycle to fix and improve the
3902   // generated code.
3903   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3904     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3905     std::deque<SUnit *> newOrderZC;
3906     // Put the zero-cost, pseudo instructions at the start of the cycle.
3907     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3908       SUnit *SU = cycleInstrs[i];
3909       if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
3910         orderDependence(SSD, SU, newOrderZC);
3911     }
3912     std::deque<SUnit *> newOrderI;
3913     // Then, add the regular instructions back.
3914     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3915       SUnit *SU = cycleInstrs[i];
3916       if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
3917         orderDependence(SSD, SU, newOrderI);
3918     }
3919     // Replace the old order with the new order.
3920     cycleInstrs.swap(newOrderZC);
3921     cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
3922   }
3923 
3924   DEBUG(dump(););
3925 }
3926 
3927 /// Print the schedule information to the given output.
3928 void SMSchedule::print(raw_ostream &os) const {
3929   // Iterate over each cycle.
3930   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3931     // Iterate over each instruction in the cycle.
3932     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3933     for (SUnit *CI : cycleInstrs->second) {
3934       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3935       os << "(" << CI->NodeNum << ") ";
3936       CI->getInstr()->print(os);
3937       os << "\n";
3938     }
3939   }
3940 }
3941 
3942 /// Utility function used for debugging to print the schedule.
3943 void SMSchedule::dump() const { print(dbgs()); }
3944