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/ModuloSchedule.h"
60 #include "llvm/CodeGen/RegisterPressure.h"
61 #include "llvm/CodeGen/ScheduleDAG.h"
62 #include "llvm/CodeGen/ScheduleDAGMutation.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/Config/llvm-config.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/DebugLoc.h"
69 #include "llvm/IR/Function.h"
70 #include "llvm/MC/LaneBitmask.h"
71 #include "llvm/MC/MCInstrDesc.h"
72 #include "llvm/MC/MCInstrItineraries.h"
73 #include "llvm/MC/MCRegisterInfo.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Debug.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include <algorithm>
81 #include <cassert>
82 #include <climits>
83 #include <cstdint>
84 #include <deque>
85 #include <functional>
86 #include <iterator>
87 #include <map>
88 #include <memory>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
92 
93 using namespace llvm;
94 
95 #define DEBUG_TYPE "pipeliner"
96 
97 STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
98 STATISTIC(NumPipelined, "Number of loops software pipelined");
99 STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
100 STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
101 STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
102 STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
103 STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
104 STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
105 STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
106 STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
107 STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
108 
109 /// A command line option to turn software pipelining on or off.
110 static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
111                                cl::ZeroOrMore,
112                                cl::desc("Enable Software Pipelining"));
113 
114 /// A command line option to enable SWP at -Os.
115 static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
116                                       cl::desc("Enable SWP at Os."), cl::Hidden,
117                                       cl::init(false));
118 
119 /// A command line argument to limit minimum initial interval for pipelining.
120 static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
121                               cl::desc("Size limit for the MII."),
122                               cl::Hidden, cl::init(27));
123 
124 /// A command line argument to limit the number of stages in the pipeline.
125 static cl::opt<int>
126     SwpMaxStages("pipeliner-max-stages",
127                  cl::desc("Maximum stages allowed in the generated scheduled."),
128                  cl::Hidden, cl::init(3));
129 
130 /// A command line option to disable the pruning of chain dependences due to
131 /// an unrelated Phi.
132 static cl::opt<bool>
133     SwpPruneDeps("pipeliner-prune-deps",
134                  cl::desc("Prune dependences between unrelated Phi nodes."),
135                  cl::Hidden, cl::init(true));
136 
137 /// A command line option to disable the pruning of loop carried order
138 /// dependences.
139 static cl::opt<bool>
140     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
141                         cl::desc("Prune loop carried order dependences."),
142                         cl::Hidden, cl::init(true));
143 
144 #ifndef NDEBUG
145 static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
146 #endif
147 
148 static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
149                                      cl::ReallyHidden, cl::init(false),
150                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
151 
152 static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
153                                     cl::init(false));
154 static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
155                                       cl::init(false));
156 
157 static cl::opt<bool> EmitTestAnnotations(
158     "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
159     cl::desc("Instead of emitting the pipelined code, annotate instructions "
160              "with the generated schedule for feeding into the "
161              "-modulo-schedule-test pass"));
162 
163 static cl::opt<bool> ExperimentalCodeGen(
164     "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
165     cl::desc(
166         "Use the experimental peeling code generator for software pipelining"));
167 
168 namespace llvm {
169 
170 // A command line option to enable the CopyToPhi DAG mutation.
171 cl::opt<bool>
172     SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
173                        cl::init(true), cl::ZeroOrMore,
174                        cl::desc("Enable CopyToPhi DAG Mutation"));
175 
176 } // end namespace llvm
177 
178 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
179 char MachinePipeliner::ID = 0;
180 #ifndef NDEBUG
181 int MachinePipeliner::NumTries = 0;
182 #endif
183 char &llvm::MachinePipelinerID = MachinePipeliner::ID;
184 
185 INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
186                       "Modulo Software Pipelining", false, false)
187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
188 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
189 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
190 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
191 INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
192                     "Modulo Software Pipelining", false, false)
193 
194 /// The "main" function for implementing Swing Modulo Scheduling.
195 bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
196   if (skipFunction(mf.getFunction()))
197     return false;
198 
199   if (!EnableSWP)
200     return false;
201 
202   if (mf.getFunction().getAttributes().hasAttribute(
203           AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
204       !EnableSWPOptSize.getPosition())
205     return false;
206 
207   if (!mf.getSubtarget().enableMachinePipeliner())
208     return false;
209 
210   // Cannot pipeline loops without instruction itineraries if we are using
211   // DFA for the pipeliner.
212   if (mf.getSubtarget().useDFAforSMS() &&
213       (!mf.getSubtarget().getInstrItineraryData() ||
214        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
215     return false;
216 
217   MF = &mf;
218   MLI = &getAnalysis<MachineLoopInfo>();
219   MDT = &getAnalysis<MachineDominatorTree>();
220   TII = MF->getSubtarget().getInstrInfo();
221   RegClassInfo.runOnMachineFunction(*MF);
222 
223   for (auto &L : *MLI)
224     scheduleLoop(*L);
225 
226   return false;
227 }
228 
229 /// Attempt to perform the SMS algorithm on the specified loop. This function is
230 /// the main entry point for the algorithm.  The function identifies candidate
231 /// loops, calculates the minimum initiation interval, and attempts to schedule
232 /// the loop.
233 bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
234   bool Changed = false;
235   for (auto &InnerLoop : L)
236     Changed |= scheduleLoop(*InnerLoop);
237 
238 #ifndef NDEBUG
239   // Stop trying after reaching the limit (if any).
240   int Limit = SwpLoopLimit;
241   if (Limit >= 0) {
242     if (NumTries >= SwpLoopLimit)
243       return Changed;
244     NumTries++;
245   }
246 #endif
247 
248   setPragmaPipelineOptions(L);
249   if (!canPipelineLoop(L)) {
250     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
251     return Changed;
252   }
253 
254   ++NumTrytoPipeline;
255 
256   Changed = swingModuloScheduler(L);
257 
258   return Changed;
259 }
260 
261 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
262   MachineBasicBlock *LBLK = L.getTopBlock();
263 
264   if (LBLK == nullptr)
265     return;
266 
267   const BasicBlock *BBLK = LBLK->getBasicBlock();
268   if (BBLK == nullptr)
269     return;
270 
271   const Instruction *TI = BBLK->getTerminator();
272   if (TI == nullptr)
273     return;
274 
275   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
276   if (LoopID == nullptr)
277     return;
278 
279   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
280   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
281 
282   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
283     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
284 
285     if (MD == nullptr)
286       continue;
287 
288     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
289 
290     if (S == nullptr)
291       continue;
292 
293     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
294       assert(MD->getNumOperands() == 2 &&
295              "Pipeline initiation interval hint metadata should have two operands.");
296       II_setByPragma =
297           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
298       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
299     } else if (S->getString() == "llvm.loop.pipeline.disable") {
300       disabledByPragma = true;
301     }
302   }
303 }
304 
305 /// Return true if the loop can be software pipelined.  The algorithm is
306 /// restricted to loops with a single basic block.  Make sure that the
307 /// branch in the loop can be analyzed.
308 bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
309   if (L.getNumBlocks() != 1)
310     return false;
311 
312   if (disabledByPragma)
313     return false;
314 
315   // Check if the branch can't be understood because we can't do pipelining
316   // if that's the case.
317   LI.TBB = nullptr;
318   LI.FBB = nullptr;
319   LI.BrCond.clear();
320   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
321     LLVM_DEBUG(
322         dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
323     NumFailBranch++;
324     return false;
325   }
326 
327   LI.LoopInductionVar = nullptr;
328   LI.LoopCompare = nullptr;
329   if (!TII->analyzeLoopForPipelining(L.getTopBlock())) {
330     LLVM_DEBUG(
331         dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
332     NumFailLoop++;
333     return false;
334   }
335 
336   if (!L.getLoopPreheader()) {
337     LLVM_DEBUG(
338         dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
339     NumFailPreheader++;
340     return false;
341   }
342 
343   // Remove any subregisters from inputs to phi nodes.
344   preprocessPhiNodes(*L.getHeader());
345   return true;
346 }
347 
348 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
349   MachineRegisterInfo &MRI = MF->getRegInfo();
350   SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
351 
352   for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
353     MachineOperand &DefOp = PI.getOperand(0);
354     assert(DefOp.getSubReg() == 0);
355     auto *RC = MRI.getRegClass(DefOp.getReg());
356 
357     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
358       MachineOperand &RegOp = PI.getOperand(i);
359       if (RegOp.getSubReg() == 0)
360         continue;
361 
362       // If the operand uses a subregister, replace it with a new register
363       // without subregisters, and generate a copy to the new register.
364       Register NewReg = MRI.createVirtualRegister(RC);
365       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
366       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
367       const DebugLoc &DL = PredB.findDebugLoc(At);
368       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
369                     .addReg(RegOp.getReg(), getRegState(RegOp),
370                             RegOp.getSubReg());
371       Slots.insertMachineInstrInMaps(*Copy);
372       RegOp.setReg(NewReg);
373       RegOp.setSubReg(0);
374     }
375   }
376 }
377 
378 /// The SMS algorithm consists of the following main steps:
379 /// 1. Computation and analysis of the dependence graph.
380 /// 2. Ordering of the nodes (instructions).
381 /// 3. Attempt to Schedule the loop.
382 bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
383   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
384 
385   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
386                         II_setByPragma);
387 
388   MachineBasicBlock *MBB = L.getHeader();
389   // The kernel should not include any terminator instructions.  These
390   // will be added back later.
391   SMS.startBlock(MBB);
392 
393   // Compute the number of 'real' instructions in the basic block by
394   // ignoring terminators.
395   unsigned size = MBB->size();
396   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
397                                    E = MBB->instr_end();
398        I != E; ++I, --size)
399     ;
400 
401   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
402   SMS.schedule();
403   SMS.exitRegion();
404 
405   SMS.finishBlock();
406   return SMS.hasNewSchedule();
407 }
408 
409 void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
410   if (II_setByPragma > 0)
411     MII = II_setByPragma;
412   else
413     MII = std::max(ResMII, RecMII);
414 }
415 
416 void SwingSchedulerDAG::setMAX_II() {
417   if (II_setByPragma > 0)
418     MAX_II = II_setByPragma;
419   else
420     MAX_II = MII + 10;
421 }
422 
423 /// We override the schedule function in ScheduleDAGInstrs to implement the
424 /// scheduling part of the Swing Modulo Scheduling algorithm.
425 void SwingSchedulerDAG::schedule() {
426   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
427   buildSchedGraph(AA);
428   addLoopCarriedDependences(AA);
429   updatePhiDependences();
430   Topo.InitDAGTopologicalSorting();
431   changeDependences();
432   postprocessDAG();
433   LLVM_DEBUG(dump());
434 
435   NodeSetType NodeSets;
436   findCircuits(NodeSets);
437   NodeSetType Circuits = NodeSets;
438 
439   // Calculate the MII.
440   unsigned ResMII = calculateResMII();
441   unsigned RecMII = calculateRecMII(NodeSets);
442 
443   fuseRecs(NodeSets);
444 
445   // This flag is used for testing and can cause correctness problems.
446   if (SwpIgnoreRecMII)
447     RecMII = 0;
448 
449   setMII(ResMII, RecMII);
450   setMAX_II();
451 
452   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
453                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
454 
455   // Can't schedule a loop without a valid MII.
456   if (MII == 0) {
457     LLVM_DEBUG(
458         dbgs()
459         << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
460     NumFailZeroMII++;
461     return;
462   }
463 
464   // Don't pipeline large loops.
465   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
466     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
467                       << ", we don't pipleline large loops\n");
468     NumFailLargeMaxMII++;
469     return;
470   }
471 
472   computeNodeFunctions(NodeSets);
473 
474   registerPressureFilter(NodeSets);
475 
476   colocateNodeSets(NodeSets);
477 
478   checkNodeSets(NodeSets);
479 
480   LLVM_DEBUG({
481     for (auto &I : NodeSets) {
482       dbgs() << "  Rec NodeSet ";
483       I.dump();
484     }
485   });
486 
487   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
488 
489   groupRemainingNodes(NodeSets);
490 
491   removeDuplicateNodes(NodeSets);
492 
493   LLVM_DEBUG({
494     for (auto &I : NodeSets) {
495       dbgs() << "  NodeSet ";
496       I.dump();
497     }
498   });
499 
500   computeNodeOrder(NodeSets);
501 
502   // check for node order issues
503   checkValidNodeOrder(Circuits);
504 
505   SMSchedule Schedule(Pass.MF);
506   Scheduled = schedulePipeline(Schedule);
507 
508   if (!Scheduled){
509     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
510     NumFailNoSchedule++;
511     return;
512   }
513 
514   unsigned numStages = Schedule.getMaxStageCount();
515   // No need to generate pipeline if there are no overlapped iterations.
516   if (numStages == 0) {
517     LLVM_DEBUG(
518         dbgs() << "No overlapped iterations, no need to generate pipeline\n");
519     NumFailZeroStage++;
520     return;
521   }
522   // Check that the maximum stage count is less than user-defined limit.
523   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
524     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
525                       << " : too many stages, abort\n");
526     NumFailLargeMaxStage++;
527     return;
528   }
529 
530   // Generate the schedule as a ModuloSchedule.
531   DenseMap<MachineInstr *, int> Cycles, Stages;
532   std::vector<MachineInstr *> OrderedInsts;
533   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
534        ++Cycle) {
535     for (SUnit *SU : Schedule.getInstructions(Cycle)) {
536       OrderedInsts.push_back(SU->getInstr());
537       Cycles[SU->getInstr()] = Cycle;
538       Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
539     }
540   }
541   DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
542   for (auto &KV : NewMIs) {
543     Cycles[KV.first] = Cycles[KV.second];
544     Stages[KV.first] = Stages[KV.second];
545     NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
546   }
547 
548   ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
549                     std::move(Stages));
550   if (EmitTestAnnotations) {
551     assert(NewInstrChanges.empty() &&
552            "Cannot serialize a schedule with InstrChanges!");
553     ModuloScheduleTestAnnotater MSTI(MF, MS);
554     MSTI.annotate();
555     return;
556   }
557   // The experimental code generator can't work if there are InstChanges.
558   if (ExperimentalCodeGen && NewInstrChanges.empty()) {
559     PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
560     MSE.expand();
561   } else {
562     ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
563     MSE.expand();
564     MSE.cleanup();
565   }
566   ++NumPipelined;
567 }
568 
569 /// Clean up after the software pipeliner runs.
570 void SwingSchedulerDAG::finishBlock() {
571   for (auto &KV : NewMIs)
572     MF.DeleteMachineInstr(KV.second);
573   NewMIs.clear();
574 
575   // Call the superclass.
576   ScheduleDAGInstrs::finishBlock();
577 }
578 
579 /// Return the register values for  the operands of a Phi instruction.
580 /// This function assume the instruction is a Phi.
581 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
582                        unsigned &InitVal, unsigned &LoopVal) {
583   assert(Phi.isPHI() && "Expecting a Phi.");
584 
585   InitVal = 0;
586   LoopVal = 0;
587   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
588     if (Phi.getOperand(i + 1).getMBB() != Loop)
589       InitVal = Phi.getOperand(i).getReg();
590     else
591       LoopVal = Phi.getOperand(i).getReg();
592 
593   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
594 }
595 
596 /// Return the Phi register value that comes the loop block.
597 static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
598   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
599     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
600       return Phi.getOperand(i).getReg();
601   return 0;
602 }
603 
604 /// Return true if SUb can be reached from SUa following the chain edges.
605 static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
606   SmallPtrSet<SUnit *, 8> Visited;
607   SmallVector<SUnit *, 8> Worklist;
608   Worklist.push_back(SUa);
609   while (!Worklist.empty()) {
610     const SUnit *SU = Worklist.pop_back_val();
611     for (auto &SI : SU->Succs) {
612       SUnit *SuccSU = SI.getSUnit();
613       if (SI.getKind() == SDep::Order) {
614         if (Visited.count(SuccSU))
615           continue;
616         if (SuccSU == SUb)
617           return true;
618         Worklist.push_back(SuccSU);
619         Visited.insert(SuccSU);
620       }
621     }
622   }
623   return false;
624 }
625 
626 /// Return true if the instruction causes a chain between memory
627 /// references before and after it.
628 static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
629   return MI.isCall() || MI.mayRaiseFPException() ||
630          MI.hasUnmodeledSideEffects() ||
631          (MI.hasOrderedMemoryRef() &&
632           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
633 }
634 
635 /// Return the underlying objects for the memory references of an instruction.
636 /// This function calls the code in ValueTracking, but first checks that the
637 /// instruction has a memory operand.
638 static void getUnderlyingObjects(const MachineInstr *MI,
639                                  SmallVectorImpl<const Value *> &Objs,
640                                  const DataLayout &DL) {
641   if (!MI->hasOneMemOperand())
642     return;
643   MachineMemOperand *MM = *MI->memoperands_begin();
644   if (!MM->getValue())
645     return;
646   GetUnderlyingObjects(MM->getValue(), Objs, DL);
647   for (const Value *V : Objs) {
648     if (!isIdentifiedObject(V)) {
649       Objs.clear();
650       return;
651     }
652     Objs.push_back(V);
653   }
654 }
655 
656 /// Add a chain edge between a load and store if the store can be an
657 /// alias of the load on a subsequent iteration, i.e., a loop carried
658 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
659 /// but that code doesn't create loop carried dependences.
660 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
661   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
662   Value *UnknownValue =
663     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
664   for (auto &SU : SUnits) {
665     MachineInstr &MI = *SU.getInstr();
666     if (isDependenceBarrier(MI, AA))
667       PendingLoads.clear();
668     else if (MI.mayLoad()) {
669       SmallVector<const Value *, 4> Objs;
670       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
671       if (Objs.empty())
672         Objs.push_back(UnknownValue);
673       for (auto V : Objs) {
674         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
675         SUs.push_back(&SU);
676       }
677     } else if (MI.mayStore()) {
678       SmallVector<const Value *, 4> Objs;
679       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
680       if (Objs.empty())
681         Objs.push_back(UnknownValue);
682       for (auto V : Objs) {
683         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
684             PendingLoads.find(V);
685         if (I == PendingLoads.end())
686           continue;
687         for (auto Load : I->second) {
688           if (isSuccOrder(Load, &SU))
689             continue;
690           MachineInstr &LdMI = *Load->getInstr();
691           // First, perform the cheaper check that compares the base register.
692           // If they are the same and the load offset is less than the store
693           // offset, then mark the dependence as loop carried potentially.
694           const MachineOperand *BaseOp1, *BaseOp2;
695           int64_t Offset1, Offset2;
696           bool Offset1IsScalable, Offset2IsScalable;
697           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
698                                            Offset1IsScalable, TRI) &&
699               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
700                                            Offset2IsScalable, TRI)) {
701             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
702                 Offset1IsScalable == Offset2IsScalable &&
703                 (int)Offset1 < (int)Offset2) {
704               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
705                      "What happened to the chain edge?");
706               SDep Dep(Load, SDep::Barrier);
707               Dep.setLatency(1);
708               SU.addPred(Dep);
709               continue;
710             }
711           }
712           // Second, the more expensive check that uses alias analysis on the
713           // base registers. If they alias, and the load offset is less than
714           // the store offset, the mark the dependence as loop carried.
715           if (!AA) {
716             SDep Dep(Load, SDep::Barrier);
717             Dep.setLatency(1);
718             SU.addPred(Dep);
719             continue;
720           }
721           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
722           MachineMemOperand *MMO2 = *MI.memoperands_begin();
723           if (!MMO1->getValue() || !MMO2->getValue()) {
724             SDep Dep(Load, SDep::Barrier);
725             Dep.setLatency(1);
726             SU.addPred(Dep);
727             continue;
728           }
729           if (MMO1->getValue() == MMO2->getValue() &&
730               MMO1->getOffset() <= MMO2->getOffset()) {
731             SDep Dep(Load, SDep::Barrier);
732             Dep.setLatency(1);
733             SU.addPred(Dep);
734             continue;
735           }
736           AliasResult AAResult = AA->alias(
737               MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
738                              MMO1->getAAInfo()),
739               MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
740                              MMO2->getAAInfo()));
741 
742           if (AAResult != NoAlias) {
743             SDep Dep(Load, SDep::Barrier);
744             Dep.setLatency(1);
745             SU.addPred(Dep);
746           }
747         }
748       }
749     }
750   }
751 }
752 
753 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
754 /// processes dependences for PHIs. This function adds true dependences
755 /// from a PHI to a use, and a loop carried dependence from the use to the
756 /// PHI. The loop carried dependence is represented as an anti dependence
757 /// edge. This function also removes chain dependences between unrelated
758 /// PHIs.
759 void SwingSchedulerDAG::updatePhiDependences() {
760   SmallVector<SDep, 4> RemoveDeps;
761   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
762 
763   // Iterate over each DAG node.
764   for (SUnit &I : SUnits) {
765     RemoveDeps.clear();
766     // Set to true if the instruction has an operand defined by a Phi.
767     unsigned HasPhiUse = 0;
768     unsigned HasPhiDef = 0;
769     MachineInstr *MI = I.getInstr();
770     // Iterate over each operand, and we process the definitions.
771     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
772                                     MOE = MI->operands_end();
773          MOI != MOE; ++MOI) {
774       if (!MOI->isReg())
775         continue;
776       Register Reg = MOI->getReg();
777       if (MOI->isDef()) {
778         // If the register is used by a Phi, then create an anti dependence.
779         for (MachineRegisterInfo::use_instr_iterator
780                  UI = MRI.use_instr_begin(Reg),
781                  UE = MRI.use_instr_end();
782              UI != UE; ++UI) {
783           MachineInstr *UseMI = &*UI;
784           SUnit *SU = getSUnit(UseMI);
785           if (SU != nullptr && UseMI->isPHI()) {
786             if (!MI->isPHI()) {
787               SDep Dep(SU, SDep::Anti, Reg);
788               Dep.setLatency(1);
789               I.addPred(Dep);
790             } else {
791               HasPhiDef = Reg;
792               // Add a chain edge to a dependent Phi that isn't an existing
793               // predecessor.
794               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
795                 I.addPred(SDep(SU, SDep::Barrier));
796             }
797           }
798         }
799       } else if (MOI->isUse()) {
800         // If the register is defined by a Phi, then create a true dependence.
801         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
802         if (DefMI == nullptr)
803           continue;
804         SUnit *SU = getSUnit(DefMI);
805         if (SU != nullptr && DefMI->isPHI()) {
806           if (!MI->isPHI()) {
807             SDep Dep(SU, SDep::Data, Reg);
808             Dep.setLatency(0);
809             ST.adjustSchedDependency(SU, &I, Dep);
810             I.addPred(Dep);
811           } else {
812             HasPhiUse = Reg;
813             // Add a chain edge to a dependent Phi that isn't an existing
814             // predecessor.
815             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
816               I.addPred(SDep(SU, SDep::Barrier));
817           }
818         }
819       }
820     }
821     // Remove order dependences from an unrelated Phi.
822     if (!SwpPruneDeps)
823       continue;
824     for (auto &PI : I.Preds) {
825       MachineInstr *PMI = PI.getSUnit()->getInstr();
826       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
827         if (I.getInstr()->isPHI()) {
828           if (PMI->getOperand(0).getReg() == HasPhiUse)
829             continue;
830           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
831             continue;
832         }
833         RemoveDeps.push_back(PI);
834       }
835     }
836     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
837       I.removePred(RemoveDeps[i]);
838   }
839 }
840 
841 /// Iterate over each DAG node and see if we can change any dependences
842 /// in order to reduce the recurrence MII.
843 void SwingSchedulerDAG::changeDependences() {
844   // See if an instruction can use a value from the previous iteration.
845   // If so, we update the base and offset of the instruction and change
846   // the dependences.
847   for (SUnit &I : SUnits) {
848     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
849     int64_t NewOffset = 0;
850     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
851                                NewOffset))
852       continue;
853 
854     // Get the MI and SUnit for the instruction that defines the original base.
855     Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
856     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
857     if (!DefMI)
858       continue;
859     SUnit *DefSU = getSUnit(DefMI);
860     if (!DefSU)
861       continue;
862     // Get the MI and SUnit for the instruction that defins the new base.
863     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
864     if (!LastMI)
865       continue;
866     SUnit *LastSU = getSUnit(LastMI);
867     if (!LastSU)
868       continue;
869 
870     if (Topo.IsReachable(&I, LastSU))
871       continue;
872 
873     // Remove the dependence. The value now depends on a prior iteration.
874     SmallVector<SDep, 4> Deps;
875     for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
876          ++P)
877       if (P->getSUnit() == DefSU)
878         Deps.push_back(*P);
879     for (int i = 0, e = Deps.size(); i != e; i++) {
880       Topo.RemovePred(&I, Deps[i].getSUnit());
881       I.removePred(Deps[i]);
882     }
883     // Remove the chain dependence between the instructions.
884     Deps.clear();
885     for (auto &P : LastSU->Preds)
886       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
887         Deps.push_back(P);
888     for (int i = 0, e = Deps.size(); i != e; i++) {
889       Topo.RemovePred(LastSU, Deps[i].getSUnit());
890       LastSU->removePred(Deps[i]);
891     }
892 
893     // Add a dependence between the new instruction and the instruction
894     // that defines the new base.
895     SDep Dep(&I, SDep::Anti, NewBase);
896     Topo.AddPred(LastSU, &I);
897     LastSU->addPred(Dep);
898 
899     // Remember the base and offset information so that we can update the
900     // instruction during code generation.
901     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
902   }
903 }
904 
905 namespace {
906 
907 // FuncUnitSorter - Comparison operator used to sort instructions by
908 // the number of functional unit choices.
909 struct FuncUnitSorter {
910   const InstrItineraryData *InstrItins;
911   const MCSubtargetInfo *STI;
912   DenseMap<unsigned, unsigned> Resources;
913 
914   FuncUnitSorter(const TargetSubtargetInfo &TSI)
915       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
916 
917   // Compute the number of functional unit alternatives needed
918   // at each stage, and take the minimum value. We prioritize the
919   // instructions by the least number of choices first.
920   unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
921     unsigned SchedClass = Inst->getDesc().getSchedClass();
922     unsigned min = UINT_MAX;
923     if (InstrItins && !InstrItins->isEmpty()) {
924       for (const InstrStage &IS :
925            make_range(InstrItins->beginStage(SchedClass),
926                       InstrItins->endStage(SchedClass))) {
927         unsigned funcUnits = IS.getUnits();
928         unsigned numAlternatives = countPopulation(funcUnits);
929         if (numAlternatives < min) {
930           min = numAlternatives;
931           F = funcUnits;
932         }
933       }
934       return min;
935     }
936     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
937       const MCSchedClassDesc *SCDesc =
938           STI->getSchedModel().getSchedClassDesc(SchedClass);
939       if (!SCDesc->isValid())
940         // No valid Schedule Class Desc for schedClass, should be
941         // Pseudo/PostRAPseudo
942         return min;
943 
944       for (const MCWriteProcResEntry &PRE :
945            make_range(STI->getWriteProcResBegin(SCDesc),
946                       STI->getWriteProcResEnd(SCDesc))) {
947         if (!PRE.Cycles)
948           continue;
949         const MCProcResourceDesc *ProcResource =
950             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
951         unsigned NumUnits = ProcResource->NumUnits;
952         if (NumUnits < min) {
953           min = NumUnits;
954           F = PRE.ProcResourceIdx;
955         }
956       }
957       return min;
958     }
959     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
960   }
961 
962   // Compute the critical resources needed by the instruction. This
963   // function records the functional units needed by instructions that
964   // must use only one functional unit. We use this as a tie breaker
965   // for computing the resource MII. The instrutions that require
966   // the same, highly used, functional unit have high priority.
967   void calcCriticalResources(MachineInstr &MI) {
968     unsigned SchedClass = MI.getDesc().getSchedClass();
969     if (InstrItins && !InstrItins->isEmpty()) {
970       for (const InstrStage &IS :
971            make_range(InstrItins->beginStage(SchedClass),
972                       InstrItins->endStage(SchedClass))) {
973         unsigned FuncUnits = IS.getUnits();
974         if (countPopulation(FuncUnits) == 1)
975           Resources[FuncUnits]++;
976       }
977       return;
978     }
979     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
980       const MCSchedClassDesc *SCDesc =
981           STI->getSchedModel().getSchedClassDesc(SchedClass);
982       if (!SCDesc->isValid())
983         // No valid Schedule Class Desc for schedClass, should be
984         // Pseudo/PostRAPseudo
985         return;
986 
987       for (const MCWriteProcResEntry &PRE :
988            make_range(STI->getWriteProcResBegin(SCDesc),
989                       STI->getWriteProcResEnd(SCDesc))) {
990         if (!PRE.Cycles)
991           continue;
992         Resources[PRE.ProcResourceIdx]++;
993       }
994       return;
995     }
996     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
997   }
998 
999   /// Return true if IS1 has less priority than IS2.
1000   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1001     unsigned F1 = 0, F2 = 0;
1002     unsigned MFUs1 = minFuncUnits(IS1, F1);
1003     unsigned MFUs2 = minFuncUnits(IS2, F2);
1004     if (MFUs1 == MFUs2)
1005       return Resources.lookup(F1) < Resources.lookup(F2);
1006     return MFUs1 > MFUs2;
1007   }
1008 };
1009 
1010 } // end anonymous namespace
1011 
1012 /// Calculate the resource constrained minimum initiation interval for the
1013 /// specified loop. We use the DFA to model the resources needed for
1014 /// each instruction, and we ignore dependences. A different DFA is created
1015 /// for each cycle that is required. When adding a new instruction, we attempt
1016 /// to add it to each existing DFA, until a legal space is found. If the
1017 /// instruction cannot be reserved in an existing DFA, we create a new one.
1018 unsigned SwingSchedulerDAG::calculateResMII() {
1019 
1020   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1021   SmallVector<ResourceManager*, 8> Resources;
1022   MachineBasicBlock *MBB = Loop.getHeader();
1023   Resources.push_back(new ResourceManager(&MF.getSubtarget()));
1024 
1025   // Sort the instructions by the number of available choices for scheduling,
1026   // least to most. Use the number of critical resources as the tie breaker.
1027   FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
1028   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1029                                    E = MBB->getFirstTerminator();
1030        I != E; ++I)
1031     FUS.calcCriticalResources(*I);
1032   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1033       FuncUnitOrder(FUS);
1034 
1035   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
1036                                    E = MBB->getFirstTerminator();
1037        I != E; ++I)
1038     FuncUnitOrder.push(&*I);
1039 
1040   while (!FuncUnitOrder.empty()) {
1041     MachineInstr *MI = FuncUnitOrder.top();
1042     FuncUnitOrder.pop();
1043     if (TII->isZeroCost(MI->getOpcode()))
1044       continue;
1045     // Attempt to reserve the instruction in an existing DFA. At least one
1046     // DFA is needed for each cycle.
1047     unsigned NumCycles = getSUnit(MI)->Latency;
1048     unsigned ReservedCycles = 0;
1049     SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1050     SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
1051     LLVM_DEBUG({
1052       dbgs() << "Trying to reserve resource for " << NumCycles
1053              << " cycles for \n";
1054       MI->dump();
1055     });
1056     for (unsigned C = 0; C < NumCycles; ++C)
1057       while (RI != RE) {
1058         if ((*RI)->canReserveResources(*MI)) {
1059           (*RI)->reserveResources(*MI);
1060           ++ReservedCycles;
1061           break;
1062         }
1063         RI++;
1064       }
1065     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
1066                       << ", NumCycles:" << NumCycles << "\n");
1067     // Add new DFAs, if needed, to reserve resources.
1068     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1069       LLVM_DEBUG(if (SwpDebugResource) dbgs()
1070                  << "NewResource created to reserve resources"
1071                  << "\n");
1072       ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
1073       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1074       NewResource->reserveResources(*MI);
1075       Resources.push_back(NewResource);
1076     }
1077   }
1078   int Resmii = Resources.size();
1079   LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
1080   // Delete the memory for each of the DFAs that were created earlier.
1081   for (ResourceManager *RI : Resources) {
1082     ResourceManager *D = RI;
1083     delete D;
1084   }
1085   Resources.clear();
1086   return Resmii;
1087 }
1088 
1089 /// Calculate the recurrence-constrainted minimum initiation interval.
1090 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1091 /// for each circuit. The II needs to satisfy the inequality
1092 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1093 /// II that satisfies the inequality, and the RecMII is the maximum
1094 /// of those values.
1095 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1096   unsigned RecMII = 0;
1097 
1098   for (NodeSet &Nodes : NodeSets) {
1099     if (Nodes.empty())
1100       continue;
1101 
1102     unsigned Delay = Nodes.getLatency();
1103     unsigned Distance = 1;
1104 
1105     // ii = ceil(delay / distance)
1106     unsigned CurMII = (Delay + Distance - 1) / Distance;
1107     Nodes.setRecMII(CurMII);
1108     if (CurMII > RecMII)
1109       RecMII = CurMII;
1110   }
1111 
1112   return RecMII;
1113 }
1114 
1115 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1116 /// but we do this to find the circuits, and then change them back.
1117 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1118   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1119   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1120     SUnit *SU = &SUnits[i];
1121     for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1122          IP != EP; ++IP) {
1123       if (IP->getKind() != SDep::Anti)
1124         continue;
1125       DepsAdded.push_back(std::make_pair(SU, *IP));
1126     }
1127   }
1128   for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1129                                                           E = DepsAdded.end();
1130        I != E; ++I) {
1131     // Remove this anti dependency and add one in the reverse direction.
1132     SUnit *SU = I->first;
1133     SDep &D = I->second;
1134     SUnit *TargetSU = D.getSUnit();
1135     unsigned Reg = D.getReg();
1136     unsigned Lat = D.getLatency();
1137     SU->removePred(D);
1138     SDep Dep(SU, SDep::Anti, Reg);
1139     Dep.setLatency(Lat);
1140     TargetSU->addPred(Dep);
1141   }
1142 }
1143 
1144 /// Create the adjacency structure of the nodes in the graph.
1145 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1146     SwingSchedulerDAG *DAG) {
1147   BitVector Added(SUnits.size());
1148   DenseMap<int, int> OutputDeps;
1149   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1150     Added.reset();
1151     // Add any successor to the adjacency matrix and exclude duplicates.
1152     for (auto &SI : SUnits[i].Succs) {
1153       // Only create a back-edge on the first and last nodes of a dependence
1154       // chain. This records any chains and adds them later.
1155       if (SI.getKind() == SDep::Output) {
1156         int N = SI.getSUnit()->NodeNum;
1157         int BackEdge = i;
1158         auto Dep = OutputDeps.find(BackEdge);
1159         if (Dep != OutputDeps.end()) {
1160           BackEdge = Dep->second;
1161           OutputDeps.erase(Dep);
1162         }
1163         OutputDeps[N] = BackEdge;
1164       }
1165       // Do not process a boundary node, an artificial node.
1166       // A back-edge is processed only if it goes to a Phi.
1167       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1168           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1169         continue;
1170       int N = SI.getSUnit()->NodeNum;
1171       if (!Added.test(N)) {
1172         AdjK[i].push_back(N);
1173         Added.set(N);
1174       }
1175     }
1176     // A chain edge between a store and a load is treated as a back-edge in the
1177     // adjacency matrix.
1178     for (auto &PI : SUnits[i].Preds) {
1179       if (!SUnits[i].getInstr()->mayStore() ||
1180           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1181         continue;
1182       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1183         int N = PI.getSUnit()->NodeNum;
1184         if (!Added.test(N)) {
1185           AdjK[i].push_back(N);
1186           Added.set(N);
1187         }
1188       }
1189     }
1190   }
1191   // Add back-edges in the adjacency matrix for the output dependences.
1192   for (auto &OD : OutputDeps)
1193     if (!Added.test(OD.second)) {
1194       AdjK[OD.first].push_back(OD.second);
1195       Added.set(OD.second);
1196     }
1197 }
1198 
1199 /// Identify an elementary circuit in the dependence graph starting at the
1200 /// specified node.
1201 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1202                                           bool HasBackedge) {
1203   SUnit *SV = &SUnits[V];
1204   bool F = false;
1205   Stack.insert(SV);
1206   Blocked.set(V);
1207 
1208   for (auto W : AdjK[V]) {
1209     if (NumPaths > MaxPaths)
1210       break;
1211     if (W < S)
1212       continue;
1213     if (W == S) {
1214       if (!HasBackedge)
1215         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1216       F = true;
1217       ++NumPaths;
1218       break;
1219     } else if (!Blocked.test(W)) {
1220       if (circuit(W, S, NodeSets,
1221                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1222         F = true;
1223     }
1224   }
1225 
1226   if (F)
1227     unblock(V);
1228   else {
1229     for (auto W : AdjK[V]) {
1230       if (W < S)
1231         continue;
1232       if (B[W].count(SV) == 0)
1233         B[W].insert(SV);
1234     }
1235   }
1236   Stack.pop_back();
1237   return F;
1238 }
1239 
1240 /// Unblock a node in the circuit finding algorithm.
1241 void SwingSchedulerDAG::Circuits::unblock(int U) {
1242   Blocked.reset(U);
1243   SmallPtrSet<SUnit *, 4> &BU = B[U];
1244   while (!BU.empty()) {
1245     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1246     assert(SI != BU.end() && "Invalid B set.");
1247     SUnit *W = *SI;
1248     BU.erase(W);
1249     if (Blocked.test(W->NodeNum))
1250       unblock(W->NodeNum);
1251   }
1252 }
1253 
1254 /// Identify all the elementary circuits in the dependence graph using
1255 /// Johnson's circuit algorithm.
1256 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1257   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1258   // but we do this to find the circuits, and then change them back.
1259   swapAntiDependences(SUnits);
1260 
1261   Circuits Cir(SUnits, Topo);
1262   // Create the adjacency structure.
1263   Cir.createAdjacencyStructure(this);
1264   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1265     Cir.reset();
1266     Cir.circuit(i, i, NodeSets);
1267   }
1268 
1269   // Change the dependences back so that we've created a DAG again.
1270   swapAntiDependences(SUnits);
1271 }
1272 
1273 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1274 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1275 // additional copies that are needed across iterations. An artificial dependence
1276 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1277 
1278 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1279 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1280 // PHI-------True-Dep------> USEOfPhi
1281 
1282 // The mutation creates
1283 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1284 
1285 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1286 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1287 // late  to avoid additional copies across iterations. The possible scheduling
1288 // order would be
1289 // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
1290 
1291 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1292   for (SUnit &SU : DAG->SUnits) {
1293     // Find the COPY/REG_SEQUENCE instruction.
1294     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1295       continue;
1296 
1297     // Record the loop carried PHIs.
1298     SmallVector<SUnit *, 4> PHISUs;
1299     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1300     SmallVector<SUnit *, 4> SrcSUs;
1301 
1302     for (auto &Dep : SU.Preds) {
1303       SUnit *TmpSU = Dep.getSUnit();
1304       MachineInstr *TmpMI = TmpSU->getInstr();
1305       SDep::Kind DepKind = Dep.getKind();
1306       // Save the loop carried PHI.
1307       if (DepKind == SDep::Anti && TmpMI->isPHI())
1308         PHISUs.push_back(TmpSU);
1309       // Save the source of COPY/REG_SEQUENCE.
1310       // If the source has no pre-decessors, we will end up creating cycles.
1311       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1312         SrcSUs.push_back(TmpSU);
1313     }
1314 
1315     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1316       continue;
1317 
1318     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1319     // SUnit to the container.
1320     SmallVector<SUnit *, 8> UseSUs;
1321     // Do not use iterator based loop here as we are updating the container.
1322     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1323       for (auto &Dep : PHISUs[Index]->Succs) {
1324         if (Dep.getKind() != SDep::Data)
1325           continue;
1326 
1327         SUnit *TmpSU = Dep.getSUnit();
1328         MachineInstr *TmpMI = TmpSU->getInstr();
1329         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1330           PHISUs.push_back(TmpSU);
1331           continue;
1332         }
1333         UseSUs.push_back(TmpSU);
1334       }
1335     }
1336 
1337     if (UseSUs.size() == 0)
1338       continue;
1339 
1340     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1341     // Add the artificial dependencies if it does not form a cycle.
1342     for (auto I : UseSUs) {
1343       for (auto Src : SrcSUs) {
1344         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1345           Src->addPred(SDep(I, SDep::Artificial));
1346           SDAG->Topo.AddPred(Src, I);
1347         }
1348       }
1349     }
1350   }
1351 }
1352 
1353 /// Return true for DAG nodes that we ignore when computing the cost functions.
1354 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1355 /// in the calculation of the ASAP, ALAP, etc functions.
1356 static bool ignoreDependence(const SDep &D, bool isPred) {
1357   if (D.isArtificial())
1358     return true;
1359   return D.getKind() == SDep::Anti && isPred;
1360 }
1361 
1362 /// Compute several functions need to order the nodes for scheduling.
1363 ///  ASAP - Earliest time to schedule a node.
1364 ///  ALAP - Latest time to schedule a node.
1365 ///  MOV - Mobility function, difference between ALAP and ASAP.
1366 ///  D - Depth of each node.
1367 ///  H - Height of each node.
1368 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1369   ScheduleInfo.resize(SUnits.size());
1370 
1371   LLVM_DEBUG({
1372     for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1373                                                     E = Topo.end();
1374          I != E; ++I) {
1375       const SUnit &SU = SUnits[*I];
1376       dumpNode(SU);
1377     }
1378   });
1379 
1380   int maxASAP = 0;
1381   // Compute ASAP and ZeroLatencyDepth.
1382   for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1383                                                   E = Topo.end();
1384        I != E; ++I) {
1385     int asap = 0;
1386     int zeroLatencyDepth = 0;
1387     SUnit *SU = &SUnits[*I];
1388     for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1389                                     EP = SU->Preds.end();
1390          IP != EP; ++IP) {
1391       SUnit *pred = IP->getSUnit();
1392       if (IP->getLatency() == 0)
1393         zeroLatencyDepth =
1394             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1395       if (ignoreDependence(*IP, true))
1396         continue;
1397       asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
1398                                   getDistance(pred, SU, *IP) * MII));
1399     }
1400     maxASAP = std::max(maxASAP, asap);
1401     ScheduleInfo[*I].ASAP = asap;
1402     ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
1403   }
1404 
1405   // Compute ALAP, ZeroLatencyHeight, and MOV.
1406   for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1407                                                           E = Topo.rend();
1408        I != E; ++I) {
1409     int alap = maxASAP;
1410     int zeroLatencyHeight = 0;
1411     SUnit *SU = &SUnits[*I];
1412     for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1413                                     ES = SU->Succs.end();
1414          IS != ES; ++IS) {
1415       SUnit *succ = IS->getSUnit();
1416       if (IS->getLatency() == 0)
1417         zeroLatencyHeight =
1418             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1419       if (ignoreDependence(*IS, true))
1420         continue;
1421       alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
1422                                   getDistance(SU, succ, *IS) * MII));
1423     }
1424 
1425     ScheduleInfo[*I].ALAP = alap;
1426     ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
1427   }
1428 
1429   // After computing the node functions, compute the summary for each node set.
1430   for (NodeSet &I : NodeSets)
1431     I.computeNodeSetInfo(this);
1432 
1433   LLVM_DEBUG({
1434     for (unsigned i = 0; i < SUnits.size(); i++) {
1435       dbgs() << "\tNode " << i << ":\n";
1436       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1437       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1438       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1439       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1440       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1441       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1442       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1443     }
1444   });
1445 }
1446 
1447 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1448 /// as the predecessors of the elements of NodeOrder that are not also in
1449 /// NodeOrder.
1450 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1451                    SmallSetVector<SUnit *, 8> &Preds,
1452                    const NodeSet *S = nullptr) {
1453   Preds.clear();
1454   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1455        I != E; ++I) {
1456     for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1457          PI != PE; ++PI) {
1458       if (S && S->count(PI->getSUnit()) == 0)
1459         continue;
1460       if (ignoreDependence(*PI, true))
1461         continue;
1462       if (NodeOrder.count(PI->getSUnit()) == 0)
1463         Preds.insert(PI->getSUnit());
1464     }
1465     // Back-edges are predecessors with an anti-dependence.
1466     for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1467                                     ES = (*I)->Succs.end();
1468          IS != ES; ++IS) {
1469       if (IS->getKind() != SDep::Anti)
1470         continue;
1471       if (S && S->count(IS->getSUnit()) == 0)
1472         continue;
1473       if (NodeOrder.count(IS->getSUnit()) == 0)
1474         Preds.insert(IS->getSUnit());
1475     }
1476   }
1477   return !Preds.empty();
1478 }
1479 
1480 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1481 /// as the successors of the elements of NodeOrder that are not also in
1482 /// NodeOrder.
1483 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1484                    SmallSetVector<SUnit *, 8> &Succs,
1485                    const NodeSet *S = nullptr) {
1486   Succs.clear();
1487   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1488        I != E; ++I) {
1489     for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1490          SI != SE; ++SI) {
1491       if (S && S->count(SI->getSUnit()) == 0)
1492         continue;
1493       if (ignoreDependence(*SI, false))
1494         continue;
1495       if (NodeOrder.count(SI->getSUnit()) == 0)
1496         Succs.insert(SI->getSUnit());
1497     }
1498     for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1499                                     PE = (*I)->Preds.end();
1500          PI != PE; ++PI) {
1501       if (PI->getKind() != SDep::Anti)
1502         continue;
1503       if (S && S->count(PI->getSUnit()) == 0)
1504         continue;
1505       if (NodeOrder.count(PI->getSUnit()) == 0)
1506         Succs.insert(PI->getSUnit());
1507     }
1508   }
1509   return !Succs.empty();
1510 }
1511 
1512 /// Return true if there is a path from the specified node to any of the nodes
1513 /// in DestNodes. Keep track and return the nodes in any path.
1514 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1515                         SetVector<SUnit *> &DestNodes,
1516                         SetVector<SUnit *> &Exclude,
1517                         SmallPtrSet<SUnit *, 8> &Visited) {
1518   if (Cur->isBoundaryNode())
1519     return false;
1520   if (Exclude.count(Cur) != 0)
1521     return false;
1522   if (DestNodes.count(Cur) != 0)
1523     return true;
1524   if (!Visited.insert(Cur).second)
1525     return Path.count(Cur) != 0;
1526   bool FoundPath = false;
1527   for (auto &SI : Cur->Succs)
1528     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1529   for (auto &PI : Cur->Preds)
1530     if (PI.getKind() == SDep::Anti)
1531       FoundPath |=
1532           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1533   if (FoundPath)
1534     Path.insert(Cur);
1535   return FoundPath;
1536 }
1537 
1538 /// Return true if Set1 is a subset of Set2.
1539 template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1540   for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1541     if (Set2.count(*I) == 0)
1542       return false;
1543   return true;
1544 }
1545 
1546 /// Compute the live-out registers for the instructions in a node-set.
1547 /// The live-out registers are those that are defined in the node-set,
1548 /// but not used. Except for use operands of Phis.
1549 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1550                             NodeSet &NS) {
1551   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1552   MachineRegisterInfo &MRI = MF.getRegInfo();
1553   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1554   SmallSet<unsigned, 4> Uses;
1555   for (SUnit *SU : NS) {
1556     const MachineInstr *MI = SU->getInstr();
1557     if (MI->isPHI())
1558       continue;
1559     for (const MachineOperand &MO : MI->operands())
1560       if (MO.isReg() && MO.isUse()) {
1561         Register Reg = MO.getReg();
1562         if (Register::isVirtualRegister(Reg))
1563           Uses.insert(Reg);
1564         else if (MRI.isAllocatable(Reg))
1565           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1566             Uses.insert(*Units);
1567       }
1568   }
1569   for (SUnit *SU : NS)
1570     for (const MachineOperand &MO : SU->getInstr()->operands())
1571       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1572         Register Reg = MO.getReg();
1573         if (Register::isVirtualRegister(Reg)) {
1574           if (!Uses.count(Reg))
1575             LiveOutRegs.push_back(RegisterMaskPair(Reg,
1576                                                    LaneBitmask::getNone()));
1577         } else if (MRI.isAllocatable(Reg)) {
1578           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1579             if (!Uses.count(*Units))
1580               LiveOutRegs.push_back(RegisterMaskPair(*Units,
1581                                                      LaneBitmask::getNone()));
1582         }
1583       }
1584   RPTracker.addLiveRegs(LiveOutRegs);
1585 }
1586 
1587 /// A heuristic to filter nodes in recurrent node-sets if the register
1588 /// pressure of a set is too high.
1589 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1590   for (auto &NS : NodeSets) {
1591     // Skip small node-sets since they won't cause register pressure problems.
1592     if (NS.size() <= 2)
1593       continue;
1594     IntervalPressure RecRegPressure;
1595     RegPressureTracker RecRPTracker(RecRegPressure);
1596     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1597     computeLiveOuts(MF, RecRPTracker, NS);
1598     RecRPTracker.closeBottom();
1599 
1600     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1601     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
1602       return A->NodeNum > B->NodeNum;
1603     });
1604 
1605     for (auto &SU : SUnits) {
1606       // Since we're computing the register pressure for a subset of the
1607       // instructions in a block, we need to set the tracker for each
1608       // instruction in the node-set. The tracker is set to the instruction
1609       // just after the one we're interested in.
1610       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1611       RecRPTracker.setPos(std::next(CurInstI));
1612 
1613       RegPressureDelta RPDelta;
1614       ArrayRef<PressureChange> CriticalPSets;
1615       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1616                                              CriticalPSets,
1617                                              RecRegPressure.MaxSetPressure);
1618       if (RPDelta.Excess.isValid()) {
1619         LLVM_DEBUG(
1620             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1621                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1622                    << ":" << RPDelta.Excess.getUnitInc());
1623         NS.setExceedPressure(SU);
1624         break;
1625       }
1626       RecRPTracker.recede();
1627     }
1628   }
1629 }
1630 
1631 /// A heuristic to colocate node sets that have the same set of
1632 /// successors.
1633 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1634   unsigned Colocate = 0;
1635   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1636     NodeSet &N1 = NodeSets[i];
1637     SmallSetVector<SUnit *, 8> S1;
1638     if (N1.empty() || !succ_L(N1, S1))
1639       continue;
1640     for (int j = i + 1; j < e; ++j) {
1641       NodeSet &N2 = NodeSets[j];
1642       if (N1.compareRecMII(N2) != 0)
1643         continue;
1644       SmallSetVector<SUnit *, 8> S2;
1645       if (N2.empty() || !succ_L(N2, S2))
1646         continue;
1647       if (isSubset(S1, S2) && S1.size() == S2.size()) {
1648         N1.setColocate(++Colocate);
1649         N2.setColocate(Colocate);
1650         break;
1651       }
1652     }
1653   }
1654 }
1655 
1656 /// Check if the existing node-sets are profitable. If not, then ignore the
1657 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1658 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1659 /// then it's best to try to schedule all instructions together instead of
1660 /// starting with the recurrent node-sets.
1661 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1662   // Look for loops with a large MII.
1663   if (MII < 17)
1664     return;
1665   // Check if the node-set contains only a simple add recurrence.
1666   for (auto &NS : NodeSets) {
1667     if (NS.getRecMII() > 2)
1668       return;
1669     if (NS.getMaxDepth() > MII)
1670       return;
1671   }
1672   NodeSets.clear();
1673   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1674   return;
1675 }
1676 
1677 /// Add the nodes that do not belong to a recurrence set into groups
1678 /// based upon connected componenets.
1679 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1680   SetVector<SUnit *> NodesAdded;
1681   SmallPtrSet<SUnit *, 8> Visited;
1682   // Add the nodes that are on a path between the previous node sets and
1683   // the current node set.
1684   for (NodeSet &I : NodeSets) {
1685     SmallSetVector<SUnit *, 8> N;
1686     // Add the nodes from the current node set to the previous node set.
1687     if (succ_L(I, N)) {
1688       SetVector<SUnit *> Path;
1689       for (SUnit *NI : N) {
1690         Visited.clear();
1691         computePath(NI, Path, NodesAdded, I, Visited);
1692       }
1693       if (!Path.empty())
1694         I.insert(Path.begin(), Path.end());
1695     }
1696     // Add the nodes from the previous node set to the current node set.
1697     N.clear();
1698     if (succ_L(NodesAdded, N)) {
1699       SetVector<SUnit *> Path;
1700       for (SUnit *NI : N) {
1701         Visited.clear();
1702         computePath(NI, Path, I, NodesAdded, Visited);
1703       }
1704       if (!Path.empty())
1705         I.insert(Path.begin(), Path.end());
1706     }
1707     NodesAdded.insert(I.begin(), I.end());
1708   }
1709 
1710   // Create a new node set with the connected nodes of any successor of a node
1711   // in a recurrent set.
1712   NodeSet NewSet;
1713   SmallSetVector<SUnit *, 8> N;
1714   if (succ_L(NodesAdded, N))
1715     for (SUnit *I : N)
1716       addConnectedNodes(I, NewSet, NodesAdded);
1717   if (!NewSet.empty())
1718     NodeSets.push_back(NewSet);
1719 
1720   // Create a new node set with the connected nodes of any predecessor of a node
1721   // in a recurrent set.
1722   NewSet.clear();
1723   if (pred_L(NodesAdded, N))
1724     for (SUnit *I : N)
1725       addConnectedNodes(I, NewSet, NodesAdded);
1726   if (!NewSet.empty())
1727     NodeSets.push_back(NewSet);
1728 
1729   // Create new nodes sets with the connected nodes any remaining node that
1730   // has no predecessor.
1731   for (unsigned i = 0; i < SUnits.size(); ++i) {
1732     SUnit *SU = &SUnits[i];
1733     if (NodesAdded.count(SU) == 0) {
1734       NewSet.clear();
1735       addConnectedNodes(SU, NewSet, NodesAdded);
1736       if (!NewSet.empty())
1737         NodeSets.push_back(NewSet);
1738     }
1739   }
1740 }
1741 
1742 /// Add the node to the set, and add all of its connected nodes to the set.
1743 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1744                                           SetVector<SUnit *> &NodesAdded) {
1745   NewSet.insert(SU);
1746   NodesAdded.insert(SU);
1747   for (auto &SI : SU->Succs) {
1748     SUnit *Successor = SI.getSUnit();
1749     if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1750       addConnectedNodes(Successor, NewSet, NodesAdded);
1751   }
1752   for (auto &PI : SU->Preds) {
1753     SUnit *Predecessor = PI.getSUnit();
1754     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1755       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1756   }
1757 }
1758 
1759 /// Return true if Set1 contains elements in Set2. The elements in common
1760 /// are returned in a different container.
1761 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1762                         SmallSetVector<SUnit *, 8> &Result) {
1763   Result.clear();
1764   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1765     SUnit *SU = Set1[i];
1766     if (Set2.count(SU) != 0)
1767       Result.insert(SU);
1768   }
1769   return !Result.empty();
1770 }
1771 
1772 /// Merge the recurrence node sets that have the same initial node.
1773 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1774   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1775        ++I) {
1776     NodeSet &NI = *I;
1777     for (NodeSetType::iterator J = I + 1; J != E;) {
1778       NodeSet &NJ = *J;
1779       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1780         if (NJ.compareRecMII(NI) > 0)
1781           NI.setRecMII(NJ.getRecMII());
1782         for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1783              ++NII)
1784           I->insert(*NII);
1785         NodeSets.erase(J);
1786         E = NodeSets.end();
1787       } else {
1788         ++J;
1789       }
1790     }
1791   }
1792 }
1793 
1794 /// Remove nodes that have been scheduled in previous NodeSets.
1795 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1796   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1797        ++I)
1798     for (NodeSetType::iterator J = I + 1; J != E;) {
1799       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1800 
1801       if (J->empty()) {
1802         NodeSets.erase(J);
1803         E = NodeSets.end();
1804       } else {
1805         ++J;
1806       }
1807     }
1808 }
1809 
1810 /// Compute an ordered list of the dependence graph nodes, which
1811 /// indicates the order that the nodes will be scheduled.  This is a
1812 /// two-level algorithm. First, a partial order is created, which
1813 /// consists of a list of sets ordered from highest to lowest priority.
1814 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1815   SmallSetVector<SUnit *, 8> R;
1816   NodeOrder.clear();
1817 
1818   for (auto &Nodes : NodeSets) {
1819     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1820     OrderKind Order;
1821     SmallSetVector<SUnit *, 8> N;
1822     if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1823       R.insert(N.begin(), N.end());
1824       Order = BottomUp;
1825       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
1826     } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1827       R.insert(N.begin(), N.end());
1828       Order = TopDown;
1829       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
1830     } else if (isIntersect(N, Nodes, R)) {
1831       // If some of the successors are in the existing node-set, then use the
1832       // top-down ordering.
1833       Order = TopDown;
1834       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
1835     } else if (NodeSets.size() == 1) {
1836       for (auto &N : Nodes)
1837         if (N->Succs.size() == 0)
1838           R.insert(N);
1839       Order = BottomUp;
1840       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
1841     } else {
1842       // Find the node with the highest ASAP.
1843       SUnit *maxASAP = nullptr;
1844       for (SUnit *SU : Nodes) {
1845         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1846             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
1847           maxASAP = SU;
1848       }
1849       R.insert(maxASAP);
1850       Order = BottomUp;
1851       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
1852     }
1853 
1854     while (!R.empty()) {
1855       if (Order == TopDown) {
1856         // Choose the node with the maximum height.  If more than one, choose
1857         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
1858         // choose the node with the lowest MOV.
1859         while (!R.empty()) {
1860           SUnit *maxHeight = nullptr;
1861           for (SUnit *I : R) {
1862             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
1863               maxHeight = I;
1864             else if (getHeight(I) == getHeight(maxHeight) &&
1865                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
1866               maxHeight = I;
1867             else if (getHeight(I) == getHeight(maxHeight) &&
1868                      getZeroLatencyHeight(I) ==
1869                          getZeroLatencyHeight(maxHeight) &&
1870                      getMOV(I) < getMOV(maxHeight))
1871               maxHeight = I;
1872           }
1873           NodeOrder.insert(maxHeight);
1874           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
1875           R.remove(maxHeight);
1876           for (const auto &I : maxHeight->Succs) {
1877             if (Nodes.count(I.getSUnit()) == 0)
1878               continue;
1879             if (NodeOrder.count(I.getSUnit()) != 0)
1880               continue;
1881             if (ignoreDependence(I, false))
1882               continue;
1883             R.insert(I.getSUnit());
1884           }
1885           // Back-edges are predecessors with an anti-dependence.
1886           for (const auto &I : maxHeight->Preds) {
1887             if (I.getKind() != SDep::Anti)
1888               continue;
1889             if (Nodes.count(I.getSUnit()) == 0)
1890               continue;
1891             if (NodeOrder.count(I.getSUnit()) != 0)
1892               continue;
1893             R.insert(I.getSUnit());
1894           }
1895         }
1896         Order = BottomUp;
1897         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
1898         SmallSetVector<SUnit *, 8> N;
1899         if (pred_L(NodeOrder, N, &Nodes))
1900           R.insert(N.begin(), N.end());
1901       } else {
1902         // Choose the node with the maximum depth.  If more than one, choose
1903         // the node with the maximum ZeroLatencyDepth. If still more than one,
1904         // choose the node with the lowest MOV.
1905         while (!R.empty()) {
1906           SUnit *maxDepth = nullptr;
1907           for (SUnit *I : R) {
1908             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
1909               maxDepth = I;
1910             else if (getDepth(I) == getDepth(maxDepth) &&
1911                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
1912               maxDepth = I;
1913             else if (getDepth(I) == getDepth(maxDepth) &&
1914                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
1915                      getMOV(I) < getMOV(maxDepth))
1916               maxDepth = I;
1917           }
1918           NodeOrder.insert(maxDepth);
1919           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
1920           R.remove(maxDepth);
1921           if (Nodes.isExceedSU(maxDepth)) {
1922             Order = TopDown;
1923             R.clear();
1924             R.insert(Nodes.getNode(0));
1925             break;
1926           }
1927           for (const auto &I : maxDepth->Preds) {
1928             if (Nodes.count(I.getSUnit()) == 0)
1929               continue;
1930             if (NodeOrder.count(I.getSUnit()) != 0)
1931               continue;
1932             R.insert(I.getSUnit());
1933           }
1934           // Back-edges are predecessors with an anti-dependence.
1935           for (const auto &I : maxDepth->Succs) {
1936             if (I.getKind() != SDep::Anti)
1937               continue;
1938             if (Nodes.count(I.getSUnit()) == 0)
1939               continue;
1940             if (NodeOrder.count(I.getSUnit()) != 0)
1941               continue;
1942             R.insert(I.getSUnit());
1943           }
1944         }
1945         Order = TopDown;
1946         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
1947         SmallSetVector<SUnit *, 8> N;
1948         if (succ_L(NodeOrder, N, &Nodes))
1949           R.insert(N.begin(), N.end());
1950       }
1951     }
1952     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
1953   }
1954 
1955   LLVM_DEBUG({
1956     dbgs() << "Node order: ";
1957     for (SUnit *I : NodeOrder)
1958       dbgs() << " " << I->NodeNum << " ";
1959     dbgs() << "\n";
1960   });
1961 }
1962 
1963 /// Process the nodes in the computed order and create the pipelined schedule
1964 /// of the instructions, if possible. Return true if a schedule is found.
1965 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
1966 
1967   if (NodeOrder.empty()){
1968     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
1969     return false;
1970   }
1971 
1972   bool scheduleFound = false;
1973   unsigned II = 0;
1974   // Keep increasing II until a valid schedule is found.
1975   for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
1976     Schedule.reset();
1977     Schedule.setInitiationInterval(II);
1978     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
1979 
1980     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1981     SetVector<SUnit *>::iterator NE = NodeOrder.end();
1982     do {
1983       SUnit *SU = *NI;
1984 
1985       // Compute the schedule time for the instruction, which is based
1986       // upon the scheduled time for any predecessors/successors.
1987       int EarlyStart = INT_MIN;
1988       int LateStart = INT_MAX;
1989       // These values are set when the size of the schedule window is limited
1990       // due to chain dependences.
1991       int SchedEnd = INT_MAX;
1992       int SchedStart = INT_MIN;
1993       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1994                             II, this);
1995       LLVM_DEBUG({
1996         dbgs() << "\n";
1997         dbgs() << "Inst (" << SU->NodeNum << ") ";
1998         SU->getInstr()->dump();
1999         dbgs() << "\n";
2000       });
2001       LLVM_DEBUG({
2002         dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
2003                          LateStart, SchedEnd, SchedStart);
2004       });
2005 
2006       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2007           SchedStart > LateStart)
2008         scheduleFound = false;
2009       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2010         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2011         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2012       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2013         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2014         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2015       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2016         SchedEnd =
2017             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2018         // When scheduling a Phi it is better to start at the late cycle and go
2019         // backwards. The default order may insert the Phi too far away from
2020         // its first dependence.
2021         if (SU->getInstr()->isPHI())
2022           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2023         else
2024           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2025       } else {
2026         int FirstCycle = Schedule.getFirstCycle();
2027         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2028                                         FirstCycle + getASAP(SU) + II - 1, II);
2029       }
2030       // Even if we find a schedule, make sure the schedule doesn't exceed the
2031       // allowable number of stages. We keep trying if this happens.
2032       if (scheduleFound)
2033         if (SwpMaxStages > -1 &&
2034             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2035           scheduleFound = false;
2036 
2037       LLVM_DEBUG({
2038         if (!scheduleFound)
2039           dbgs() << "\tCan't schedule\n";
2040       });
2041     } while (++NI != NE && scheduleFound);
2042 
2043     // If a schedule is found, check if it is a valid schedule too.
2044     if (scheduleFound)
2045       scheduleFound = Schedule.isValidSchedule(this);
2046   }
2047 
2048   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
2049                     << ")\n");
2050 
2051   if (scheduleFound)
2052     Schedule.finalizeSchedule(this);
2053   else
2054     Schedule.reset();
2055 
2056   return scheduleFound && Schedule.getMaxStageCount() > 0;
2057 }
2058 
2059 /// Return true if we can compute the amount the instruction changes
2060 /// during each iteration. Set Delta to the amount of the change.
2061 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2062   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2063   const MachineOperand *BaseOp;
2064   int64_t Offset;
2065   bool OffsetIsScalable;
2066   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
2067     return false;
2068 
2069   // FIXME: This algorithm assumes instructions have fixed-size offsets.
2070   if (OffsetIsScalable)
2071     return false;
2072 
2073   if (!BaseOp->isReg())
2074     return false;
2075 
2076   Register BaseReg = BaseOp->getReg();
2077 
2078   MachineRegisterInfo &MRI = MF.getRegInfo();
2079   // Check if there is a Phi. If so, get the definition in the loop.
2080   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2081   if (BaseDef && BaseDef->isPHI()) {
2082     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2083     BaseDef = MRI.getVRegDef(BaseReg);
2084   }
2085   if (!BaseDef)
2086     return false;
2087 
2088   int D = 0;
2089   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2090     return false;
2091 
2092   Delta = D;
2093   return true;
2094 }
2095 
2096 /// Check if we can change the instruction to use an offset value from the
2097 /// previous iteration. If so, return true and set the base and offset values
2098 /// so that we can rewrite the load, if necessary.
2099 ///   v1 = Phi(v0, v3)
2100 ///   v2 = load v1, 0
2101 ///   v3 = post_store v1, 4, x
2102 /// This function enables the load to be rewritten as v2 = load v3, 4.
2103 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2104                                               unsigned &BasePos,
2105                                               unsigned &OffsetPos,
2106                                               unsigned &NewBase,
2107                                               int64_t &Offset) {
2108   // Get the load instruction.
2109   if (TII->isPostIncrement(*MI))
2110     return false;
2111   unsigned BasePosLd, OffsetPosLd;
2112   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2113     return false;
2114   Register BaseReg = MI->getOperand(BasePosLd).getReg();
2115 
2116   // Look for the Phi instruction.
2117   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2118   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2119   if (!Phi || !Phi->isPHI())
2120     return false;
2121   // Get the register defined in the loop block.
2122   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2123   if (!PrevReg)
2124     return false;
2125 
2126   // Check for the post-increment load/store instruction.
2127   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2128   if (!PrevDef || PrevDef == MI)
2129     return false;
2130 
2131   if (!TII->isPostIncrement(*PrevDef))
2132     return false;
2133 
2134   unsigned BasePos1 = 0, OffsetPos1 = 0;
2135   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2136     return false;
2137 
2138   // Make sure that the instructions do not access the same memory location in
2139   // the next iteration.
2140   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2141   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
2142   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2143   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2144   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2145   MF.DeleteMachineInstr(NewMI);
2146   if (!Disjoint)
2147     return false;
2148 
2149   // Set the return value once we determine that we return true.
2150   BasePos = BasePosLd;
2151   OffsetPos = OffsetPosLd;
2152   NewBase = PrevReg;
2153   Offset = StoreOffset;
2154   return true;
2155 }
2156 
2157 /// Apply changes to the instruction if needed. The changes are need
2158 /// to improve the scheduling and depend up on the final schedule.
2159 void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2160                                          SMSchedule &Schedule) {
2161   SUnit *SU = getSUnit(MI);
2162   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2163       InstrChanges.find(SU);
2164   if (It != InstrChanges.end()) {
2165     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2166     unsigned BasePos, OffsetPos;
2167     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2168       return;
2169     Register BaseReg = MI->getOperand(BasePos).getReg();
2170     MachineInstr *LoopDef = findDefInLoop(BaseReg);
2171     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2172     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2173     int BaseStageNum = Schedule.stageScheduled(SU);
2174     int BaseCycleNum = Schedule.cycleScheduled(SU);
2175     if (BaseStageNum < DefStageNum) {
2176       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2177       int OffsetDiff = DefStageNum - BaseStageNum;
2178       if (DefCycleNum < BaseCycleNum) {
2179         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2180         if (OffsetDiff > 0)
2181           --OffsetDiff;
2182       }
2183       int64_t NewOffset =
2184           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2185       NewMI->getOperand(OffsetPos).setImm(NewOffset);
2186       SU->setInstr(NewMI);
2187       MISUnitMap[NewMI] = SU;
2188       NewMIs[MI] = NewMI;
2189     }
2190   }
2191 }
2192 
2193 /// Return the instruction in the loop that defines the register.
2194 /// If the definition is a Phi, then follow the Phi operand to
2195 /// the instruction in the loop.
2196 MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2197   SmallPtrSet<MachineInstr *, 8> Visited;
2198   MachineInstr *Def = MRI.getVRegDef(Reg);
2199   while (Def->isPHI()) {
2200     if (!Visited.insert(Def).second)
2201       break;
2202     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2203       if (Def->getOperand(i + 1).getMBB() == BB) {
2204         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2205         break;
2206       }
2207   }
2208   return Def;
2209 }
2210 
2211 /// Return true for an order or output dependence that is loop carried
2212 /// potentially. A dependence is loop carried if the destination defines a valu
2213 /// that may be used or defined by the source in a subsequent iteration.
2214 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2215                                          bool isSucc) {
2216   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2217       Dep.isArtificial())
2218     return false;
2219 
2220   if (!SwpPruneLoopCarried)
2221     return true;
2222 
2223   if (Dep.getKind() == SDep::Output)
2224     return true;
2225 
2226   MachineInstr *SI = Source->getInstr();
2227   MachineInstr *DI = Dep.getSUnit()->getInstr();
2228   if (!isSucc)
2229     std::swap(SI, DI);
2230   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2231 
2232   // Assume ordered loads and stores may have a loop carried dependence.
2233   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
2234       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2235       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2236     return true;
2237 
2238   // Only chain dependences between a load and store can be loop carried.
2239   if (!DI->mayStore() || !SI->mayLoad())
2240     return false;
2241 
2242   unsigned DeltaS, DeltaD;
2243   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2244     return true;
2245 
2246   const MachineOperand *BaseOpS, *BaseOpD;
2247   int64_t OffsetS, OffsetD;
2248   bool OffsetSIsScalable, OffsetDIsScalable;
2249   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2250   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
2251                                     TRI) ||
2252       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
2253                                     TRI))
2254     return true;
2255 
2256   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
2257          "Expected offsets to be byte offsets");
2258 
2259   if (!BaseOpS->isIdenticalTo(*BaseOpD))
2260     return true;
2261 
2262   // Check that the base register is incremented by a constant value for each
2263   // iteration.
2264   MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
2265   if (!Def || !Def->isPHI())
2266     return true;
2267   unsigned InitVal = 0;
2268   unsigned LoopVal = 0;
2269   getPhiRegs(*Def, BB, InitVal, LoopVal);
2270   MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
2271   int D = 0;
2272   if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
2273     return true;
2274 
2275   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
2276   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
2277 
2278   // This is the main test, which checks the offset values and the loop
2279   // increment value to determine if the accesses may be loop carried.
2280   if (AccessSizeS == MemoryLocation::UnknownSize ||
2281       AccessSizeD == MemoryLocation::UnknownSize)
2282     return true;
2283 
2284   if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
2285     return true;
2286 
2287   return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
2288 }
2289 
2290 void SwingSchedulerDAG::postprocessDAG() {
2291   for (auto &M : Mutations)
2292     M->apply(this);
2293 }
2294 
2295 /// Try to schedule the node at the specified StartCycle and continue
2296 /// until the node is schedule or the EndCycle is reached.  This function
2297 /// returns true if the node is scheduled.  This routine may search either
2298 /// forward or backward for a place to insert the instruction based upon
2299 /// the relative values of StartCycle and EndCycle.
2300 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2301   bool forward = true;
2302   LLVM_DEBUG({
2303     dbgs() << "Trying to insert node between " << StartCycle << " and "
2304            << EndCycle << " II: " << II << "\n";
2305   });
2306   if (StartCycle > EndCycle)
2307     forward = false;
2308 
2309   // The terminating condition depends on the direction.
2310   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2311   for (int curCycle = StartCycle; curCycle != termCycle;
2312        forward ? ++curCycle : --curCycle) {
2313 
2314     // Add the already scheduled instructions at the specified cycle to the
2315     // DFA.
2316     ProcItinResources.clearResources();
2317     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
2318          checkCycle <= LastCycle; checkCycle += II) {
2319       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
2320 
2321       for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
2322                                          E = cycleInstrs.end();
2323            I != E; ++I) {
2324         if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
2325           continue;
2326         assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
2327                "These instructions have already been scheduled.");
2328         ProcItinResources.reserveResources(*(*I)->getInstr());
2329       }
2330     }
2331     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2332         ProcItinResources.canReserveResources(*SU->getInstr())) {
2333       LLVM_DEBUG({
2334         dbgs() << "\tinsert at cycle " << curCycle << " ";
2335         SU->getInstr()->dump();
2336       });
2337 
2338       ScheduledInstrs[curCycle].push_back(SU);
2339       InstrToCycle.insert(std::make_pair(SU, curCycle));
2340       if (curCycle > LastCycle)
2341         LastCycle = curCycle;
2342       if (curCycle < FirstCycle)
2343         FirstCycle = curCycle;
2344       return true;
2345     }
2346     LLVM_DEBUG({
2347       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2348       SU->getInstr()->dump();
2349     });
2350   }
2351   return false;
2352 }
2353 
2354 // Return the cycle of the earliest scheduled instruction in the chain.
2355 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2356   SmallPtrSet<SUnit *, 8> Visited;
2357   SmallVector<SDep, 8> Worklist;
2358   Worklist.push_back(Dep);
2359   int EarlyCycle = INT_MAX;
2360   while (!Worklist.empty()) {
2361     const SDep &Cur = Worklist.pop_back_val();
2362     SUnit *PrevSU = Cur.getSUnit();
2363     if (Visited.count(PrevSU))
2364       continue;
2365     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2366     if (it == InstrToCycle.end())
2367       continue;
2368     EarlyCycle = std::min(EarlyCycle, it->second);
2369     for (const auto &PI : PrevSU->Preds)
2370       if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
2371         Worklist.push_back(PI);
2372     Visited.insert(PrevSU);
2373   }
2374   return EarlyCycle;
2375 }
2376 
2377 // Return the cycle of the latest scheduled instruction in the chain.
2378 int SMSchedule::latestCycleInChain(const SDep &Dep) {
2379   SmallPtrSet<SUnit *, 8> Visited;
2380   SmallVector<SDep, 8> Worklist;
2381   Worklist.push_back(Dep);
2382   int LateCycle = INT_MIN;
2383   while (!Worklist.empty()) {
2384     const SDep &Cur = Worklist.pop_back_val();
2385     SUnit *SuccSU = Cur.getSUnit();
2386     if (Visited.count(SuccSU))
2387       continue;
2388     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2389     if (it == InstrToCycle.end())
2390       continue;
2391     LateCycle = std::max(LateCycle, it->second);
2392     for (const auto &SI : SuccSU->Succs)
2393       if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
2394         Worklist.push_back(SI);
2395     Visited.insert(SuccSU);
2396   }
2397   return LateCycle;
2398 }
2399 
2400 /// If an instruction has a use that spans multiple iterations, then
2401 /// return true. These instructions are characterized by having a back-ege
2402 /// to a Phi, which contains a reference to another Phi.
2403 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2404   for (auto &P : SU->Preds)
2405     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2406       for (auto &S : P.getSUnit()->Succs)
2407         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2408           return P.getSUnit();
2409   return nullptr;
2410 }
2411 
2412 /// Compute the scheduling start slot for the instruction.  The start slot
2413 /// depends on any predecessor or successor nodes scheduled already.
2414 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2415                               int *MinEnd, int *MaxStart, int II,
2416                               SwingSchedulerDAG *DAG) {
2417   // Iterate over each instruction that has been scheduled already.  The start
2418   // slot computation depends on whether the previously scheduled instruction
2419   // is a predecessor or successor of the specified instruction.
2420   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2421 
2422     // Iterate over each instruction in the current cycle.
2423     for (SUnit *I : getInstructions(cycle)) {
2424       // Because we're processing a DAG for the dependences, we recognize
2425       // the back-edge in recurrences by anti dependences.
2426       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2427         const SDep &Dep = SU->Preds[i];
2428         if (Dep.getSUnit() == I) {
2429           if (!DAG->isBackedge(SU, Dep)) {
2430             int EarlyStart = cycle + Dep.getLatency() -
2431                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2432             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2433             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2434               int End = earliestCycleInChain(Dep) + (II - 1);
2435               *MinEnd = std::min(*MinEnd, End);
2436             }
2437           } else {
2438             int LateStart = cycle - Dep.getLatency() +
2439                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2440             *MinLateStart = std::min(*MinLateStart, LateStart);
2441           }
2442         }
2443         // For instruction that requires multiple iterations, make sure that
2444         // the dependent instruction is not scheduled past the definition.
2445         SUnit *BE = multipleIterations(I, DAG);
2446         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2447             !SU->isPred(I))
2448           *MinLateStart = std::min(*MinLateStart, cycle);
2449       }
2450       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2451         if (SU->Succs[i].getSUnit() == I) {
2452           const SDep &Dep = SU->Succs[i];
2453           if (!DAG->isBackedge(SU, Dep)) {
2454             int LateStart = cycle - Dep.getLatency() +
2455                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2456             *MinLateStart = std::min(*MinLateStart, LateStart);
2457             if (DAG->isLoopCarriedDep(SU, Dep)) {
2458               int Start = latestCycleInChain(Dep) + 1 - II;
2459               *MaxStart = std::max(*MaxStart, Start);
2460             }
2461           } else {
2462             int EarlyStart = cycle + Dep.getLatency() -
2463                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2464             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2465           }
2466         }
2467       }
2468     }
2469   }
2470 }
2471 
2472 /// Order the instructions within a cycle so that the definitions occur
2473 /// before the uses. Returns true if the instruction is added to the start
2474 /// of the list, or false if added to the end.
2475 void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
2476                                  std::deque<SUnit *> &Insts) {
2477   MachineInstr *MI = SU->getInstr();
2478   bool OrderBeforeUse = false;
2479   bool OrderAfterDef = false;
2480   bool OrderBeforeDef = false;
2481   unsigned MoveDef = 0;
2482   unsigned MoveUse = 0;
2483   int StageInst1 = stageScheduled(SU);
2484 
2485   unsigned Pos = 0;
2486   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2487        ++I, ++Pos) {
2488     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
2489       MachineOperand &MO = MI->getOperand(i);
2490       if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
2491         continue;
2492 
2493       Register Reg = MO.getReg();
2494       unsigned BasePos, OffsetPos;
2495       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2496         if (MI->getOperand(BasePos).getReg() == Reg)
2497           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
2498             Reg = NewReg;
2499       bool Reads, Writes;
2500       std::tie(Reads, Writes) =
2501           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
2502       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
2503         OrderBeforeUse = true;
2504         if (MoveUse == 0)
2505           MoveUse = Pos;
2506       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
2507         // Add the instruction after the scheduled instruction.
2508         OrderAfterDef = true;
2509         MoveDef = Pos;
2510       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
2511         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
2512           OrderBeforeUse = true;
2513           if (MoveUse == 0)
2514             MoveUse = Pos;
2515         } else {
2516           OrderAfterDef = true;
2517           MoveDef = Pos;
2518         }
2519       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
2520         OrderBeforeUse = true;
2521         if (MoveUse == 0)
2522           MoveUse = Pos;
2523         if (MoveUse != 0) {
2524           OrderAfterDef = true;
2525           MoveDef = Pos - 1;
2526         }
2527       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
2528         // Add the instruction before the scheduled instruction.
2529         OrderBeforeUse = true;
2530         if (MoveUse == 0)
2531           MoveUse = Pos;
2532       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
2533                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
2534         if (MoveUse == 0) {
2535           OrderBeforeDef = true;
2536           MoveUse = Pos;
2537         }
2538       }
2539     }
2540     // Check for order dependences between instructions. Make sure the source
2541     // is ordered before the destination.
2542     for (auto &S : SU->Succs) {
2543       if (S.getSUnit() != *I)
2544         continue;
2545       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2546         OrderBeforeUse = true;
2547         if (Pos < MoveUse)
2548           MoveUse = Pos;
2549       }
2550       // We did not handle HW dependences in previous for loop,
2551       // and we normally set Latency = 0 for Anti deps,
2552       // so may have nodes in same cycle with Anti denpendent on HW regs.
2553       else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
2554         OrderBeforeUse = true;
2555         if ((MoveUse == 0) || (Pos < MoveUse))
2556           MoveUse = Pos;
2557       }
2558     }
2559     for (auto &P : SU->Preds) {
2560       if (P.getSUnit() != *I)
2561         continue;
2562       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2563         OrderAfterDef = true;
2564         MoveDef = Pos;
2565       }
2566     }
2567   }
2568 
2569   // A circular dependence.
2570   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
2571     OrderBeforeUse = false;
2572 
2573   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2574   // to a loop-carried dependence.
2575   if (OrderBeforeDef)
2576     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
2577 
2578   // The uncommon case when the instruction order needs to be updated because
2579   // there is both a use and def.
2580   if (OrderBeforeUse && OrderAfterDef) {
2581     SUnit *UseSU = Insts.at(MoveUse);
2582     SUnit *DefSU = Insts.at(MoveDef);
2583     if (MoveUse > MoveDef) {
2584       Insts.erase(Insts.begin() + MoveUse);
2585       Insts.erase(Insts.begin() + MoveDef);
2586     } else {
2587       Insts.erase(Insts.begin() + MoveDef);
2588       Insts.erase(Insts.begin() + MoveUse);
2589     }
2590     orderDependence(SSD, UseSU, Insts);
2591     orderDependence(SSD, SU, Insts);
2592     orderDependence(SSD, DefSU, Insts);
2593     return;
2594   }
2595   // Put the new instruction first if there is a use in the list. Otherwise,
2596   // put it at the end of the list.
2597   if (OrderBeforeUse)
2598     Insts.push_front(SU);
2599   else
2600     Insts.push_back(SU);
2601 }
2602 
2603 /// Return true if the scheduled Phi has a loop carried operand.
2604 bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
2605   if (!Phi.isPHI())
2606     return false;
2607   assert(Phi.isPHI() && "Expecting a Phi.");
2608   SUnit *DefSU = SSD->getSUnit(&Phi);
2609   unsigned DefCycle = cycleScheduled(DefSU);
2610   int DefStage = stageScheduled(DefSU);
2611 
2612   unsigned InitVal = 0;
2613   unsigned LoopVal = 0;
2614   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
2615   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
2616   if (!UseSU)
2617     return true;
2618   if (UseSU->getInstr()->isPHI())
2619     return true;
2620   unsigned LoopCycle = cycleScheduled(UseSU);
2621   int LoopStage = stageScheduled(UseSU);
2622   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
2623 }
2624 
2625 /// Return true if the instruction is a definition that is loop carried
2626 /// and defines the use on the next iteration.
2627 ///        v1 = phi(v2, v3)
2628 ///  (Def) v3 = op v1
2629 ///  (MO)   = v1
2630 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2631 /// register.
2632 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
2633                                        MachineInstr *Def, MachineOperand &MO) {
2634   if (!MO.isReg())
2635     return false;
2636   if (Def->isPHI())
2637     return false;
2638   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
2639   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
2640     return false;
2641   if (!isLoopCarried(SSD, *Phi))
2642     return false;
2643   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
2644   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
2645     MachineOperand &DMO = Def->getOperand(i);
2646     if (!DMO.isReg() || !DMO.isDef())
2647       continue;
2648     if (DMO.getReg() == LoopReg)
2649       return true;
2650   }
2651   return false;
2652 }
2653 
2654 // Check if the generated schedule is valid. This function checks if
2655 // an instruction that uses a physical register is scheduled in a
2656 // different stage than the definition. The pipeliner does not handle
2657 // physical register values that may cross a basic block boundary.
2658 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
2659   for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
2660     SUnit &SU = SSD->SUnits[i];
2661     if (!SU.hasPhysRegDefs)
2662       continue;
2663     int StageDef = stageScheduled(&SU);
2664     assert(StageDef != -1 && "Instruction should have been scheduled.");
2665     for (auto &SI : SU.Succs)
2666       if (SI.isAssignedRegDep())
2667         if (Register::isPhysicalRegister(SI.getReg()))
2668           if (stageScheduled(SI.getSUnit()) != StageDef)
2669             return false;
2670   }
2671   return true;
2672 }
2673 
2674 /// A property of the node order in swing-modulo-scheduling is
2675 /// that for nodes outside circuits the following holds:
2676 /// none of them is scheduled after both a successor and a
2677 /// predecessor.
2678 /// The method below checks whether the property is met.
2679 /// If not, debug information is printed and statistics information updated.
2680 /// Note that we do not use an assert statement.
2681 /// The reason is that although an invalid node oder may prevent
2682 /// the pipeliner from finding a pipelined schedule for arbitrary II,
2683 /// it does not lead to the generation of incorrect code.
2684 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
2685 
2686   // a sorted vector that maps each SUnit to its index in the NodeOrder
2687   typedef std::pair<SUnit *, unsigned> UnitIndex;
2688   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
2689 
2690   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
2691     Indices.push_back(std::make_pair(NodeOrder[i], i));
2692 
2693   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
2694     return std::get<0>(i1) < std::get<0>(i2);
2695   };
2696 
2697   // sort, so that we can perform a binary search
2698   llvm::sort(Indices, CompareKey);
2699 
2700   bool Valid = true;
2701   (void)Valid;
2702   // for each SUnit in the NodeOrder, check whether
2703   // it appears after both a successor and a predecessor
2704   // of the SUnit. If this is the case, and the SUnit
2705   // is not part of circuit, then the NodeOrder is not
2706   // valid.
2707   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
2708     SUnit *SU = NodeOrder[i];
2709     unsigned Index = i;
2710 
2711     bool PredBefore = false;
2712     bool SuccBefore = false;
2713 
2714     SUnit *Succ;
2715     SUnit *Pred;
2716     (void)Succ;
2717     (void)Pred;
2718 
2719     for (SDep &PredEdge : SU->Preds) {
2720       SUnit *PredSU = PredEdge.getSUnit();
2721       unsigned PredIndex = std::get<1>(
2722           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
2723       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
2724         PredBefore = true;
2725         Pred = PredSU;
2726         break;
2727       }
2728     }
2729 
2730     for (SDep &SuccEdge : SU->Succs) {
2731       SUnit *SuccSU = SuccEdge.getSUnit();
2732       // Do not process a boundary node, it was not included in NodeOrder,
2733       // hence not in Indices either, call to std::lower_bound() below will
2734       // return Indices.end().
2735       if (SuccSU->isBoundaryNode())
2736         continue;
2737       unsigned SuccIndex = std::get<1>(
2738           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
2739       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
2740         SuccBefore = true;
2741         Succ = SuccSU;
2742         break;
2743       }
2744     }
2745 
2746     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
2747       // instructions in circuits are allowed to be scheduled
2748       // after both a successor and predecessor.
2749       bool InCircuit = llvm::any_of(
2750           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
2751       if (InCircuit)
2752         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
2753       else {
2754         Valid = false;
2755         NumNodeOrderIssues++;
2756         LLVM_DEBUG(dbgs() << "Predecessor ";);
2757       }
2758       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
2759                         << " are scheduled before node " << SU->NodeNum
2760                         << "\n";);
2761     }
2762   }
2763 
2764   LLVM_DEBUG({
2765     if (!Valid)
2766       dbgs() << "Invalid node order found!\n";
2767   });
2768 }
2769 
2770 /// Attempt to fix the degenerate cases when the instruction serialization
2771 /// causes the register lifetimes to overlap. For example,
2772 ///   p' = store_pi(p, b)
2773 ///      = load p, offset
2774 /// In this case p and p' overlap, which means that two registers are needed.
2775 /// Instead, this function changes the load to use p' and updates the offset.
2776 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
2777   unsigned OverlapReg = 0;
2778   unsigned NewBaseReg = 0;
2779   for (SUnit *SU : Instrs) {
2780     MachineInstr *MI = SU->getInstr();
2781     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
2782       const MachineOperand &MO = MI->getOperand(i);
2783       // Look for an instruction that uses p. The instruction occurs in the
2784       // same cycle but occurs later in the serialized order.
2785       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
2786         // Check that the instruction appears in the InstrChanges structure,
2787         // which contains instructions that can have the offset updated.
2788         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2789           InstrChanges.find(SU);
2790         if (It != InstrChanges.end()) {
2791           unsigned BasePos, OffsetPos;
2792           // Update the base register and adjust the offset.
2793           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
2794             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2795             NewMI->getOperand(BasePos).setReg(NewBaseReg);
2796             int64_t NewOffset =
2797                 MI->getOperand(OffsetPos).getImm() - It->second.second;
2798             NewMI->getOperand(OffsetPos).setImm(NewOffset);
2799             SU->setInstr(NewMI);
2800             MISUnitMap[NewMI] = SU;
2801             NewMIs[MI] = NewMI;
2802           }
2803         }
2804         OverlapReg = 0;
2805         NewBaseReg = 0;
2806         break;
2807       }
2808       // Look for an instruction of the form p' = op(p), which uses and defines
2809       // two virtual registers that get allocated to the same physical register.
2810       unsigned TiedUseIdx = 0;
2811       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
2812         // OverlapReg is p in the example above.
2813         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
2814         // NewBaseReg is p' in the example above.
2815         NewBaseReg = MI->getOperand(i).getReg();
2816         break;
2817       }
2818     }
2819   }
2820 }
2821 
2822 /// After the schedule has been formed, call this function to combine
2823 /// the instructions from the different stages/cycles.  That is, this
2824 /// function creates a schedule that represents a single iteration.
2825 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
2826   // Move all instructions to the first stage from later stages.
2827   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2828     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
2829          ++stage) {
2830       std::deque<SUnit *> &cycleInstrs =
2831           ScheduledInstrs[cycle + (stage * InitiationInterval)];
2832       for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
2833                                                  E = cycleInstrs.rend();
2834            I != E; ++I)
2835         ScheduledInstrs[cycle].push_front(*I);
2836     }
2837   }
2838 
2839   // Erase all the elements in the later stages. Only one iteration should
2840   // remain in the scheduled list, and it contains all the instructions.
2841   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
2842     ScheduledInstrs.erase(cycle);
2843 
2844   // Change the registers in instruction as specified in the InstrChanges
2845   // map. We need to use the new registers to create the correct order.
2846   for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
2847     SUnit *SU = &SSD->SUnits[i];
2848     SSD->applyInstrChange(SU->getInstr(), *this);
2849   }
2850 
2851   // Reorder the instructions in each cycle to fix and improve the
2852   // generated code.
2853   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
2854     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
2855     std::deque<SUnit *> newOrderPhi;
2856     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
2857       SUnit *SU = cycleInstrs[i];
2858       if (SU->getInstr()->isPHI())
2859         newOrderPhi.push_back(SU);
2860     }
2861     std::deque<SUnit *> newOrderI;
2862     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
2863       SUnit *SU = cycleInstrs[i];
2864       if (!SU->getInstr()->isPHI())
2865         orderDependence(SSD, SU, newOrderI);
2866     }
2867     // Replace the old order with the new order.
2868     cycleInstrs.swap(newOrderPhi);
2869     cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
2870     SSD->fixupRegisterOverlaps(cycleInstrs);
2871   }
2872 
2873   LLVM_DEBUG(dump(););
2874 }
2875 
2876 void NodeSet::print(raw_ostream &os) const {
2877   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
2878      << " depth " << MaxDepth << " col " << Colocate << "\n";
2879   for (const auto &I : Nodes)
2880     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
2881   os << "\n";
2882 }
2883 
2884 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2885 /// Print the schedule information to the given output.
2886 void SMSchedule::print(raw_ostream &os) const {
2887   // Iterate over each cycle.
2888   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2889     // Iterate over each instruction in the cycle.
2890     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
2891     for (SUnit *CI : cycleInstrs->second) {
2892       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
2893       os << "(" << CI->NodeNum << ") ";
2894       CI->getInstr()->print(os);
2895       os << "\n";
2896     }
2897   }
2898 }
2899 
2900 /// Utility function used for debugging to print the schedule.
2901 LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
2902 LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
2903 
2904 #endif
2905 
2906 void ResourceManager::initProcResourceVectors(
2907     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
2908   unsigned ProcResourceID = 0;
2909 
2910   // We currently limit the resource kinds to 64 and below so that we can use
2911   // uint64_t for Masks
2912   assert(SM.getNumProcResourceKinds() < 64 &&
2913          "Too many kinds of resources, unsupported");
2914   // Create a unique bitmask for every processor resource unit.
2915   // Skip resource at index 0, since it always references 'InvalidUnit'.
2916   Masks.resize(SM.getNumProcResourceKinds());
2917   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2918     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
2919     if (Desc.SubUnitsIdxBegin)
2920       continue;
2921     Masks[I] = 1ULL << ProcResourceID;
2922     ProcResourceID++;
2923   }
2924   // Create a unique bitmask for every processor resource group.
2925   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2926     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
2927     if (!Desc.SubUnitsIdxBegin)
2928       continue;
2929     Masks[I] = 1ULL << ProcResourceID;
2930     for (unsigned U = 0; U < Desc.NumUnits; ++U)
2931       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
2932     ProcResourceID++;
2933   }
2934   LLVM_DEBUG({
2935     if (SwpShowResMask) {
2936       dbgs() << "ProcResourceDesc:\n";
2937       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
2938         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
2939         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
2940                          ProcResource->Name, I, Masks[I],
2941                          ProcResource->NumUnits);
2942       }
2943       dbgs() << " -----------------\n";
2944     }
2945   });
2946 }
2947 
2948 bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
2949 
2950   LLVM_DEBUG({
2951     if (SwpDebugResource)
2952       dbgs() << "canReserveResources:\n";
2953   });
2954   if (UseDFA)
2955     return DFAResources->canReserveResources(MID);
2956 
2957   unsigned InsnClass = MID->getSchedClass();
2958   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
2959   if (!SCDesc->isValid()) {
2960     LLVM_DEBUG({
2961       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
2962       dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
2963     });
2964     return true;
2965   }
2966 
2967   const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
2968   const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
2969   for (; I != E; ++I) {
2970     if (!I->Cycles)
2971       continue;
2972     const MCProcResourceDesc *ProcResource =
2973         SM.getProcResource(I->ProcResourceIdx);
2974     unsigned NumUnits = ProcResource->NumUnits;
2975     LLVM_DEBUG({
2976       if (SwpDebugResource)
2977         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
2978                          ProcResource->Name, I->ProcResourceIdx,
2979                          ProcResourceCount[I->ProcResourceIdx], NumUnits,
2980                          I->Cycles);
2981     });
2982     if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
2983       return false;
2984   }
2985   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
2986   return true;
2987 }
2988 
2989 void ResourceManager::reserveResources(const MCInstrDesc *MID) {
2990   LLVM_DEBUG({
2991     if (SwpDebugResource)
2992       dbgs() << "reserveResources:\n";
2993   });
2994   if (UseDFA)
2995     return DFAResources->reserveResources(MID);
2996 
2997   unsigned InsnClass = MID->getSchedClass();
2998   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
2999   if (!SCDesc->isValid()) {
3000     LLVM_DEBUG({
3001       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3002       dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
3003     });
3004     return;
3005   }
3006   for (const MCWriteProcResEntry &PRE :
3007        make_range(STI->getWriteProcResBegin(SCDesc),
3008                   STI->getWriteProcResEnd(SCDesc))) {
3009     if (!PRE.Cycles)
3010       continue;
3011     ++ProcResourceCount[PRE.ProcResourceIdx];
3012     LLVM_DEBUG({
3013       if (SwpDebugResource) {
3014         const MCProcResourceDesc *ProcResource =
3015             SM.getProcResource(PRE.ProcResourceIdx);
3016         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3017                          ProcResource->Name, PRE.ProcResourceIdx,
3018                          ProcResourceCount[PRE.ProcResourceIdx],
3019                          ProcResource->NumUnits, PRE.Cycles);
3020       }
3021     });
3022   }
3023   LLVM_DEBUG({
3024     if (SwpDebugResource)
3025       dbgs() << "reserveResources: done!\n\n";
3026   });
3027 }
3028 
3029 bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
3030   return canReserveResources(&MI.getDesc());
3031 }
3032 
3033 void ResourceManager::reserveResources(const MachineInstr &MI) {
3034   return reserveResources(&MI.getDesc());
3035 }
3036 
3037 void ResourceManager::clearResources() {
3038   if (UseDFA)
3039     return DFAResources->clearResources();
3040   std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
3041 }
3042