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