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