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