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