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