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