xref: /llvm-project/llvm/lib/CodeGen/MachinePipeliner.cpp (revision 735ab61ac828bd61398e6847d60e308fdf2b54ec)
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 fixed one, for example, stack pointer
1287   bool isFixedRegister(Register Reg) const {
1288     return Reg.isPhysical() && TRI->isFixedRegister(MF, 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 (isFixedRegister(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] = TRI->getRegPressureSetLimit(MF, PSet);
1330 
1331     // We assume fixed registers, such as stack pointer, are already in use.
1332     // Therefore subtracting the weight of the fixed registers from the limit of
1333     // each pressure set in advance.
1334     SmallDenseSet<Register, 8> FixedRegs;
1335     for (const TargetRegisterClass *TRC : TRI->regclasses()) {
1336       for (const MCPhysReg Reg : *TRC)
1337         if (isFixedRegister(Reg))
1338           FixedRegs.insert(Reg);
1339     }
1340 
1341     LLVM_DEBUG({
1342       for (auto Reg : FixedRegs) {
1343         dbgs() << printReg(Reg, TRI, 0, &MRI) << ": [";
1344         for (MCRegUnit Unit : TRI->regunits(Reg)) {
1345           const int *Sets = TRI->getRegUnitPressureSets(Unit);
1346           for (; *Sets != -1; Sets++) {
1347             dbgs() << TRI->getRegPressureSetName(*Sets) << ", ";
1348           }
1349         }
1350         dbgs() << "]\n";
1351       }
1352     });
1353 
1354     for (auto Reg : FixedRegs) {
1355       LLVM_DEBUG(dbgs() << "fixed register: " << printReg(Reg, TRI, 0, &MRI)
1356                         << "\n");
1357       for (MCRegUnit Unit : TRI->regunits(Reg)) {
1358         auto PSetIter = MRI.getPressureSets(Unit);
1359         unsigned Weight = PSetIter.getWeight();
1360         for (; PSetIter.isValid(); ++PSetIter) {
1361           unsigned &Limit = PressureSetLimit[*PSetIter];
1362           assert(
1363               Limit >= Weight &&
1364               "register pressure limit must be greater than or equal weight");
1365           Limit -= Weight;
1366           LLVM_DEBUG(dbgs() << "PSet=" << *PSetIter << " Limit=" << Limit
1367                             << " (decreased by " << Weight << ")\n");
1368         }
1369       }
1370     }
1371   }
1372 
1373   // There are two patterns of last-use.
1374   //   - by an instruction of the current iteration
1375   //   - by a phi instruction of the next iteration (loop carried value)
1376   //
1377   // Furthermore, following two groups of instructions are executed
1378   // simultaneously
1379   //   - next iteration's phi instructions in i-th stage
1380   //   - current iteration's instructions in i+1-th stage
1381   //
1382   // This function calculates the last-use of each register while taking into
1383   // account the above two patterns.
1384   Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
1385                                    Instr2StageTy &Stages) const {
1386     // We treat virtual registers that are defined and used in this loop.
1387     // Following virtual register will be ignored
1388     //   - live-in one
1389     //   - defined but not used in the loop (potentially live-out)
1390     DenseSet<Register> TargetRegs;
1391     const auto UpdateTargetRegs = [this, &TargetRegs](Register Reg) {
1392       if (isDefinedInThisLoop(Reg))
1393         TargetRegs.insert(Reg);
1394     };
1395     for (MachineInstr *MI : OrderedInsts) {
1396       if (MI->isPHI()) {
1397         Register Reg = getLoopPhiReg(*MI, OrigMBB);
1398         UpdateTargetRegs(Reg);
1399       } else {
1400         for (auto &Use : ROMap.find(MI)->getSecond().Uses)
1401           UpdateTargetRegs(Use.RegUnit);
1402       }
1403     }
1404 
1405     const auto InstrScore = [&Stages](MachineInstr *MI) {
1406       return Stages[MI] + MI->isPHI();
1407     };
1408 
1409     DenseMap<Register, MachineInstr *> LastUseMI;
1410     for (MachineInstr *MI : llvm::reverse(OrderedInsts)) {
1411       for (auto &Use : ROMap.find(MI)->getSecond().Uses) {
1412         auto Reg = Use.RegUnit;
1413         if (!TargetRegs.contains(Reg))
1414           continue;
1415         auto [Ite, Inserted] = LastUseMI.try_emplace(Reg, MI);
1416         if (!Inserted) {
1417           MachineInstr *Orig = Ite->second;
1418           MachineInstr *New = MI;
1419           if (InstrScore(Orig) < InstrScore(New))
1420             Ite->second = New;
1421         }
1422       }
1423     }
1424 
1425     Instr2LastUsesTy LastUses;
1426     for (auto &Entry : LastUseMI)
1427       LastUses[Entry.second].insert(Entry.first);
1428     return LastUses;
1429   }
1430 
1431   // Compute the maximum register pressure of the kernel. We'll simulate #Stage
1432   // iterations and check the register pressure at the point where all stages
1433   // overlapping.
1434   //
1435   // An example of unrolled loop where #Stage is 4..
1436   // Iter   i+0 i+1 i+2 i+3
1437   // ------------------------
1438   // Stage   0
1439   // Stage   1   0
1440   // Stage   2   1   0
1441   // Stage   3   2   1   0  <- All stages overlap
1442   //
1443   std::vector<unsigned>
1444   computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
1445                         Instr2StageTy &Stages,
1446                         const unsigned StageCount) const {
1447     using RegSetTy = SmallDenseSet<Register, 16>;
1448 
1449     // Indexed by #Iter. To treat "local" variables of each stage separately, we
1450     // manage the liveness of the registers independently by iterations.
1451     SmallVector<RegSetTy> LiveRegSets(StageCount);
1452 
1453     auto CurSetPressure = InitSetPressure;
1454     auto MaxSetPressure = InitSetPressure;
1455     auto LastUses = computeLastUses(OrderedInsts, Stages);
1456 
1457     LLVM_DEBUG({
1458       dbgs() << "Ordered instructions:\n";
1459       for (MachineInstr *MI : OrderedInsts) {
1460         dbgs() << "Stage " << Stages[MI] << ": ";
1461         MI->dump();
1462       }
1463     });
1464 
1465     const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
1466                                                    Register Reg) {
1467       if (!Reg.isValid() || isFixedRegister(Reg))
1468         return;
1469 
1470       bool Inserted = RegSet.insert(Reg).second;
1471       if (!Inserted)
1472         return;
1473 
1474       LLVM_DEBUG(dbgs() << "insert " << printReg(Reg, TRI, 0, &MRI) << "\n");
1475       increaseRegisterPressure(CurSetPressure, Reg);
1476       LLVM_DEBUG(dumpPSet(Reg));
1477     };
1478 
1479     const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
1480                                                   Register Reg) {
1481       if (!Reg.isValid() || isFixedRegister(Reg))
1482         return;
1483 
1484       // live-in register
1485       if (!RegSet.contains(Reg))
1486         return;
1487 
1488       LLVM_DEBUG(dbgs() << "erase " << printReg(Reg, TRI, 0, &MRI) << "\n");
1489       RegSet.erase(Reg);
1490       decreaseRegisterPressure(CurSetPressure, Reg);
1491       LLVM_DEBUG(dumpPSet(Reg));
1492     };
1493 
1494     for (unsigned I = 0; I < StageCount; I++) {
1495       for (MachineInstr *MI : OrderedInsts) {
1496         const auto Stage = Stages[MI];
1497         if (I < Stage)
1498           continue;
1499 
1500         const unsigned Iter = I - Stage;
1501 
1502         for (auto &Def : ROMap.find(MI)->getSecond().Defs)
1503           InsertReg(LiveRegSets[Iter], Def.RegUnit);
1504 
1505         for (auto LastUse : LastUses[MI]) {
1506           if (MI->isPHI()) {
1507             if (Iter != 0)
1508               EraseReg(LiveRegSets[Iter - 1], LastUse);
1509           } else {
1510             EraseReg(LiveRegSets[Iter], LastUse);
1511           }
1512         }
1513 
1514         for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1515           MaxSetPressure[PSet] =
1516               std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
1517 
1518         LLVM_DEBUG({
1519           dbgs() << "CurSetPressure=";
1520           dumpRegisterPressures(CurSetPressure);
1521           dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
1522           MI->dump();
1523         });
1524       }
1525     }
1526 
1527     return MaxSetPressure;
1528   }
1529 
1530 public:
1531   HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
1532                                const MachineFunction &MF)
1533       : OrigMBB(OrigMBB), MF(MF), MRI(MF.getRegInfo()),
1534         TRI(MF.getSubtarget().getRegisterInfo()),
1535         PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
1536         PressureSetLimit(PSetNum, 0) {}
1537 
1538   // Used to calculate register pressure, which is independent of loop
1539   // scheduling.
1540   void init(const RegisterClassInfo &RCI) {
1541     for (MachineInstr &MI : *OrigMBB) {
1542       if (MI.isDebugInstr())
1543         continue;
1544       ROMap[&MI].collect(MI, *TRI, MRI, false, true);
1545     }
1546 
1547     computeLiveIn();
1548     computePressureSetLimit(RCI);
1549   }
1550 
1551   // Calculate the maximum register pressures of the loop and check if they
1552   // exceed the limit
1553   bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
1554               const unsigned MaxStage) const {
1555     assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
1556            "the percentage of the margin must be between 0 to 100");
1557 
1558     OrderedInstsTy OrderedInsts;
1559     Instr2StageTy Stages;
1560     computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
1561     const auto MaxSetPressure =
1562         computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
1563 
1564     LLVM_DEBUG({
1565       dbgs() << "Dump MaxSetPressure:\n";
1566       for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
1567         dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
1568       }
1569       dbgs() << '\n';
1570     });
1571 
1572     for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
1573       unsigned Limit = PressureSetLimit[PSet];
1574       unsigned Margin = Limit * RegPressureMargin / 100;
1575       LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
1576                         << " Margin=" << Margin << "\n");
1577       if (Limit < MaxSetPressure[PSet] + Margin) {
1578         LLVM_DEBUG(
1579             dbgs()
1580             << "Rejected the schedule because of too high register pressure\n");
1581         return true;
1582       }
1583     }
1584     return false;
1585   }
1586 };
1587 
1588 } // end anonymous namespace
1589 
1590 /// Calculate the resource constrained minimum initiation interval for the
1591 /// specified loop. We use the DFA to model the resources needed for
1592 /// each instruction, and we ignore dependences. A different DFA is created
1593 /// for each cycle that is required. When adding a new instruction, we attempt
1594 /// to add it to each existing DFA, until a legal space is found. If the
1595 /// instruction cannot be reserved in an existing DFA, we create a new one.
1596 unsigned SwingSchedulerDAG::calculateResMII() {
1597   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1598   ResourceManager RM(&MF.getSubtarget(), this);
1599   return RM.calculateResMII();
1600 }
1601 
1602 /// Calculate the recurrence-constrainted minimum initiation interval.
1603 /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1604 /// for each circuit. The II needs to satisfy the inequality
1605 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1606 /// II that satisfies the inequality, and the RecMII is the maximum
1607 /// of those values.
1608 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1609   unsigned RecMII = 0;
1610 
1611   for (NodeSet &Nodes : NodeSets) {
1612     if (Nodes.empty())
1613       continue;
1614 
1615     unsigned Delay = Nodes.getLatency();
1616     unsigned Distance = 1;
1617 
1618     // ii = ceil(delay / distance)
1619     unsigned CurMII = (Delay + Distance - 1) / Distance;
1620     Nodes.setRecMII(CurMII);
1621     if (CurMII > RecMII)
1622       RecMII = CurMII;
1623   }
1624 
1625   return RecMII;
1626 }
1627 
1628 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1629 /// but we do this to find the circuits, and then change them back.
1630 static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1631   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1632   for (SUnit &SU : SUnits) {
1633     for (SDep &Pred : SU.Preds)
1634       if (Pred.getKind() == SDep::Anti)
1635         DepsAdded.push_back(std::make_pair(&SU, Pred));
1636   }
1637   for (std::pair<SUnit *, SDep> &P : DepsAdded) {
1638     // Remove this anti dependency and add one in the reverse direction.
1639     SUnit *SU = P.first;
1640     SDep &D = P.second;
1641     SUnit *TargetSU = D.getSUnit();
1642     unsigned Reg = D.getReg();
1643     unsigned Lat = D.getLatency();
1644     SU->removePred(D);
1645     SDep Dep(SU, SDep::Anti, Reg);
1646     Dep.setLatency(Lat);
1647     TargetSU->addPred(Dep);
1648   }
1649 }
1650 
1651 /// Create the adjacency structure of the nodes in the graph.
1652 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1653     SwingSchedulerDAG *DAG) {
1654   BitVector Added(SUnits.size());
1655   DenseMap<int, int> OutputDeps;
1656   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1657     Added.reset();
1658     // Add any successor to the adjacency matrix and exclude duplicates.
1659     for (auto &SI : SUnits[i].Succs) {
1660       // Only create a back-edge on the first and last nodes of a dependence
1661       // chain. This records any chains and adds them later.
1662       if (SI.getKind() == SDep::Output) {
1663         int N = SI.getSUnit()->NodeNum;
1664         int BackEdge = i;
1665         auto Dep = OutputDeps.find(BackEdge);
1666         if (Dep != OutputDeps.end()) {
1667           BackEdge = Dep->second;
1668           OutputDeps.erase(Dep);
1669         }
1670         OutputDeps[N] = BackEdge;
1671       }
1672       // Do not process a boundary node, an artificial node.
1673       // A back-edge is processed only if it goes to a Phi.
1674       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1675           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1676         continue;
1677       int N = SI.getSUnit()->NodeNum;
1678       if (!Added.test(N)) {
1679         AdjK[i].push_back(N);
1680         Added.set(N);
1681       }
1682     }
1683     // A chain edge between a store and a load is treated as a back-edge in the
1684     // adjacency matrix.
1685     for (auto &PI : SUnits[i].Preds) {
1686       if (!SUnits[i].getInstr()->mayStore() ||
1687           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1688         continue;
1689       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1690         int N = PI.getSUnit()->NodeNum;
1691         if (!Added.test(N)) {
1692           AdjK[i].push_back(N);
1693           Added.set(N);
1694         }
1695       }
1696     }
1697   }
1698   // Add back-edges in the adjacency matrix for the output dependences.
1699   for (auto &OD : OutputDeps)
1700     if (!Added.test(OD.second)) {
1701       AdjK[OD.first].push_back(OD.second);
1702       Added.set(OD.second);
1703     }
1704 }
1705 
1706 /// Identify an elementary circuit in the dependence graph starting at the
1707 /// specified node.
1708 bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1709                                           const SwingSchedulerDAG *DAG,
1710                                           bool HasBackedge) {
1711   SUnit *SV = &SUnits[V];
1712   bool F = false;
1713   Stack.insert(SV);
1714   Blocked.set(V);
1715 
1716   for (auto W : AdjK[V]) {
1717     if (NumPaths > MaxPaths)
1718       break;
1719     if (W < S)
1720       continue;
1721     if (W == S) {
1722       if (!HasBackedge)
1723         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end(), DAG));
1724       F = true;
1725       ++NumPaths;
1726       break;
1727     }
1728     if (!Blocked.test(W)) {
1729       if (circuit(W, S, NodeSets, DAG,
1730                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1731         F = true;
1732     }
1733   }
1734 
1735   if (F)
1736     unblock(V);
1737   else {
1738     for (auto W : AdjK[V]) {
1739       if (W < S)
1740         continue;
1741       B[W].insert(SV);
1742     }
1743   }
1744   Stack.pop_back();
1745   return F;
1746 }
1747 
1748 /// Unblock a node in the circuit finding algorithm.
1749 void SwingSchedulerDAG::Circuits::unblock(int U) {
1750   Blocked.reset(U);
1751   SmallPtrSet<SUnit *, 4> &BU = B[U];
1752   while (!BU.empty()) {
1753     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1754     assert(SI != BU.end() && "Invalid B set.");
1755     SUnit *W = *SI;
1756     BU.erase(W);
1757     if (Blocked.test(W->NodeNum))
1758       unblock(W->NodeNum);
1759   }
1760 }
1761 
1762 /// Identify all the elementary circuits in the dependence graph using
1763 /// Johnson's circuit algorithm.
1764 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1765   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1766   // but we do this to find the circuits, and then change them back.
1767   swapAntiDependences(SUnits);
1768 
1769   Circuits Cir(SUnits, Topo);
1770   // Create the adjacency structure.
1771   Cir.createAdjacencyStructure(this);
1772   for (int I = 0, E = SUnits.size(); I != E; ++I) {
1773     Cir.reset();
1774     Cir.circuit(I, I, NodeSets, this);
1775   }
1776 
1777   // Change the dependences back so that we've created a DAG again.
1778   swapAntiDependences(SUnits);
1779 }
1780 
1781 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1782 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1783 // additional copies that are needed across iterations. An artificial dependence
1784 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1785 
1786 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1787 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1788 // PHI-------True-Dep------> USEOfPhi
1789 
1790 // The mutation creates
1791 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1792 
1793 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1794 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1795 // late  to avoid additional copies across iterations. The possible scheduling
1796 // order would be
1797 // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
1798 
1799 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1800   for (SUnit &SU : DAG->SUnits) {
1801     // Find the COPY/REG_SEQUENCE instruction.
1802     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1803       continue;
1804 
1805     // Record the loop carried PHIs.
1806     SmallVector<SUnit *, 4> PHISUs;
1807     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1808     SmallVector<SUnit *, 4> SrcSUs;
1809 
1810     for (auto &Dep : SU.Preds) {
1811       SUnit *TmpSU = Dep.getSUnit();
1812       MachineInstr *TmpMI = TmpSU->getInstr();
1813       SDep::Kind DepKind = Dep.getKind();
1814       // Save the loop carried PHI.
1815       if (DepKind == SDep::Anti && TmpMI->isPHI())
1816         PHISUs.push_back(TmpSU);
1817       // Save the source of COPY/REG_SEQUENCE.
1818       // If the source has no pre-decessors, we will end up creating cycles.
1819       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1820         SrcSUs.push_back(TmpSU);
1821     }
1822 
1823     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1824       continue;
1825 
1826     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1827     // SUnit to the container.
1828     SmallVector<SUnit *, 8> UseSUs;
1829     // Do not use iterator based loop here as we are updating the container.
1830     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1831       for (auto &Dep : PHISUs[Index]->Succs) {
1832         if (Dep.getKind() != SDep::Data)
1833           continue;
1834 
1835         SUnit *TmpSU = Dep.getSUnit();
1836         MachineInstr *TmpMI = TmpSU->getInstr();
1837         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1838           PHISUs.push_back(TmpSU);
1839           continue;
1840         }
1841         UseSUs.push_back(TmpSU);
1842       }
1843     }
1844 
1845     if (UseSUs.size() == 0)
1846       continue;
1847 
1848     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1849     // Add the artificial dependencies if it does not form a cycle.
1850     for (auto *I : UseSUs) {
1851       for (auto *Src : SrcSUs) {
1852         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1853           Src->addPred(SDep(I, SDep::Artificial));
1854           SDAG->Topo.AddPred(Src, I);
1855         }
1856       }
1857     }
1858   }
1859 }
1860 
1861 /// Return true for DAG nodes that we ignore when computing the cost functions.
1862 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1863 /// in the calculation of the ASAP, ALAP, etc functions.
1864 static bool ignoreDependence(const SDep &D, bool isPred) {
1865   if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
1866     return true;
1867   return D.getKind() == SDep::Anti && isPred;
1868 }
1869 
1870 /// Compute several functions need to order the nodes for scheduling.
1871 ///  ASAP - Earliest time to schedule a node.
1872 ///  ALAP - Latest time to schedule a node.
1873 ///  MOV - Mobility function, difference between ALAP and ASAP.
1874 ///  D - Depth of each node.
1875 ///  H - Height of each node.
1876 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1877   ScheduleInfo.resize(SUnits.size());
1878 
1879   LLVM_DEBUG({
1880     for (int I : Topo) {
1881       const SUnit &SU = SUnits[I];
1882       dumpNode(SU);
1883     }
1884   });
1885 
1886   int maxASAP = 0;
1887   // Compute ASAP and ZeroLatencyDepth.
1888   for (int I : Topo) {
1889     int asap = 0;
1890     int zeroLatencyDepth = 0;
1891     SUnit *SU = &SUnits[I];
1892     for (const SDep &P : SU->Preds) {
1893       SUnit *pred = P.getSUnit();
1894       if (P.getLatency() == 0)
1895         zeroLatencyDepth =
1896             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1897       if (ignoreDependence(P, true))
1898         continue;
1899       asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
1900                                   getDistance(pred, SU, P) * MII));
1901     }
1902     maxASAP = std::max(maxASAP, asap);
1903     ScheduleInfo[I].ASAP = asap;
1904     ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
1905   }
1906 
1907   // Compute ALAP, ZeroLatencyHeight, and MOV.
1908   for (int I : llvm::reverse(Topo)) {
1909     int alap = maxASAP;
1910     int zeroLatencyHeight = 0;
1911     SUnit *SU = &SUnits[I];
1912     for (const SDep &S : SU->Succs) {
1913       SUnit *succ = S.getSUnit();
1914       if (succ->isBoundaryNode())
1915         continue;
1916       if (S.getLatency() == 0)
1917         zeroLatencyHeight =
1918             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1919       if (ignoreDependence(S, true))
1920         continue;
1921       alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
1922                                   getDistance(SU, succ, S) * MII));
1923     }
1924 
1925     ScheduleInfo[I].ALAP = alap;
1926     ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
1927   }
1928 
1929   // After computing the node functions, compute the summary for each node set.
1930   for (NodeSet &I : NodeSets)
1931     I.computeNodeSetInfo(this);
1932 
1933   LLVM_DEBUG({
1934     for (unsigned i = 0; i < SUnits.size(); i++) {
1935       dbgs() << "\tNode " << i << ":\n";
1936       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1937       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1938       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1939       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1940       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
1941       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1942       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1943     }
1944   });
1945 }
1946 
1947 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1948 /// as the predecessors of the elements of NodeOrder that are not also in
1949 /// NodeOrder.
1950 static bool pred_L(SetVector<SUnit *> &NodeOrder,
1951                    SmallSetVector<SUnit *, 8> &Preds,
1952                    const NodeSet *S = nullptr) {
1953   Preds.clear();
1954   for (const SUnit *SU : NodeOrder) {
1955     for (const SDep &Pred : SU->Preds) {
1956       if (S && S->count(Pred.getSUnit()) == 0)
1957         continue;
1958       if (ignoreDependence(Pred, true))
1959         continue;
1960       if (NodeOrder.count(Pred.getSUnit()) == 0)
1961         Preds.insert(Pred.getSUnit());
1962     }
1963     // Back-edges are predecessors with an anti-dependence.
1964     for (const SDep &Succ : SU->Succs) {
1965       if (Succ.getKind() != SDep::Anti)
1966         continue;
1967       if (S && S->count(Succ.getSUnit()) == 0)
1968         continue;
1969       if (NodeOrder.count(Succ.getSUnit()) == 0)
1970         Preds.insert(Succ.getSUnit());
1971     }
1972   }
1973   return !Preds.empty();
1974 }
1975 
1976 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1977 /// as the successors of the elements of NodeOrder that are not also in
1978 /// NodeOrder.
1979 static bool succ_L(SetVector<SUnit *> &NodeOrder,
1980                    SmallSetVector<SUnit *, 8> &Succs,
1981                    const NodeSet *S = nullptr) {
1982   Succs.clear();
1983   for (const SUnit *SU : NodeOrder) {
1984     for (const SDep &Succ : SU->Succs) {
1985       if (S && S->count(Succ.getSUnit()) == 0)
1986         continue;
1987       if (ignoreDependence(Succ, false))
1988         continue;
1989       if (NodeOrder.count(Succ.getSUnit()) == 0)
1990         Succs.insert(Succ.getSUnit());
1991     }
1992     for (const SDep &Pred : SU->Preds) {
1993       if (Pred.getKind() != SDep::Anti)
1994         continue;
1995       if (S && S->count(Pred.getSUnit()) == 0)
1996         continue;
1997       if (NodeOrder.count(Pred.getSUnit()) == 0)
1998         Succs.insert(Pred.getSUnit());
1999     }
2000   }
2001   return !Succs.empty();
2002 }
2003 
2004 /// Return true if there is a path from the specified node to any of the nodes
2005 /// in DestNodes. Keep track and return the nodes in any path.
2006 static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
2007                         SetVector<SUnit *> &DestNodes,
2008                         SetVector<SUnit *> &Exclude,
2009                         SmallPtrSet<SUnit *, 8> &Visited) {
2010   if (Cur->isBoundaryNode())
2011     return false;
2012   if (Exclude.contains(Cur))
2013     return false;
2014   if (DestNodes.contains(Cur))
2015     return true;
2016   if (!Visited.insert(Cur).second)
2017     return Path.contains(Cur);
2018   bool FoundPath = false;
2019   for (auto &SI : Cur->Succs)
2020     if (!ignoreDependence(SI, false))
2021       FoundPath |=
2022           computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
2023   for (auto &PI : Cur->Preds)
2024     if (PI.getKind() == SDep::Anti)
2025       FoundPath |=
2026           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
2027   if (FoundPath)
2028     Path.insert(Cur);
2029   return FoundPath;
2030 }
2031 
2032 /// Compute the live-out registers for the instructions in a node-set.
2033 /// The live-out registers are those that are defined in the node-set,
2034 /// but not used. Except for use operands of Phis.
2035 static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
2036                             NodeSet &NS) {
2037   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2038   MachineRegisterInfo &MRI = MF.getRegInfo();
2039   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
2040   SmallSet<unsigned, 4> Uses;
2041   for (SUnit *SU : NS) {
2042     const MachineInstr *MI = SU->getInstr();
2043     if (MI->isPHI())
2044       continue;
2045     for (const MachineOperand &MO : MI->all_uses()) {
2046       Register Reg = MO.getReg();
2047       if (Reg.isVirtual())
2048         Uses.insert(Reg);
2049       else if (MRI.isAllocatable(Reg))
2050         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2051           Uses.insert(Unit);
2052     }
2053   }
2054   for (SUnit *SU : NS)
2055     for (const MachineOperand &MO : SU->getInstr()->all_defs())
2056       if (!MO.isDead()) {
2057         Register Reg = MO.getReg();
2058         if (Reg.isVirtual()) {
2059           if (!Uses.count(Reg))
2060             LiveOutRegs.push_back(RegisterMaskPair(Reg,
2061                                                    LaneBitmask::getNone()));
2062         } else if (MRI.isAllocatable(Reg)) {
2063           for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2064             if (!Uses.count(Unit))
2065               LiveOutRegs.push_back(
2066                   RegisterMaskPair(Unit, LaneBitmask::getNone()));
2067         }
2068       }
2069   RPTracker.addLiveRegs(LiveOutRegs);
2070 }
2071 
2072 /// A heuristic to filter nodes in recurrent node-sets if the register
2073 /// pressure of a set is too high.
2074 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2075   for (auto &NS : NodeSets) {
2076     // Skip small node-sets since they won't cause register pressure problems.
2077     if (NS.size() <= 2)
2078       continue;
2079     IntervalPressure RecRegPressure;
2080     RegPressureTracker RecRPTracker(RecRegPressure);
2081     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
2082     computeLiveOuts(MF, RecRPTracker, NS);
2083     RecRPTracker.closeBottom();
2084 
2085     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2086     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
2087       return A->NodeNum > B->NodeNum;
2088     });
2089 
2090     for (auto &SU : SUnits) {
2091       // Since we're computing the register pressure for a subset of the
2092       // instructions in a block, we need to set the tracker for each
2093       // instruction in the node-set. The tracker is set to the instruction
2094       // just after the one we're interested in.
2095       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
2096       RecRPTracker.setPos(std::next(CurInstI));
2097 
2098       RegPressureDelta RPDelta;
2099       ArrayRef<PressureChange> CriticalPSets;
2100       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
2101                                              CriticalPSets,
2102                                              RecRegPressure.MaxSetPressure);
2103       if (RPDelta.Excess.isValid()) {
2104         LLVM_DEBUG(
2105             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
2106                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
2107                    << ":" << RPDelta.Excess.getUnitInc() << "\n");
2108         NS.setExceedPressure(SU);
2109         break;
2110       }
2111       RecRPTracker.recede();
2112     }
2113   }
2114 }
2115 
2116 /// A heuristic to colocate node sets that have the same set of
2117 /// successors.
2118 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2119   unsigned Colocate = 0;
2120   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
2121     NodeSet &N1 = NodeSets[i];
2122     SmallSetVector<SUnit *, 8> S1;
2123     if (N1.empty() || !succ_L(N1, S1))
2124       continue;
2125     for (int j = i + 1; j < e; ++j) {
2126       NodeSet &N2 = NodeSets[j];
2127       if (N1.compareRecMII(N2) != 0)
2128         continue;
2129       SmallSetVector<SUnit *, 8> S2;
2130       if (N2.empty() || !succ_L(N2, S2))
2131         continue;
2132       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
2133         N1.setColocate(++Colocate);
2134         N2.setColocate(Colocate);
2135         break;
2136       }
2137     }
2138   }
2139 }
2140 
2141 /// Check if the existing node-sets are profitable. If not, then ignore the
2142 /// recurrent node-sets, and attempt to schedule all nodes together. This is
2143 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
2144 /// then it's best to try to schedule all instructions together instead of
2145 /// starting with the recurrent node-sets.
2146 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2147   // Look for loops with a large MII.
2148   if (MII < 17)
2149     return;
2150   // Check if the node-set contains only a simple add recurrence.
2151   for (auto &NS : NodeSets) {
2152     if (NS.getRecMII() > 2)
2153       return;
2154     if (NS.getMaxDepth() > MII)
2155       return;
2156   }
2157   NodeSets.clear();
2158   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
2159 }
2160 
2161 /// Add the nodes that do not belong to a recurrence set into groups
2162 /// based upon connected components.
2163 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2164   SetVector<SUnit *> NodesAdded;
2165   SmallPtrSet<SUnit *, 8> Visited;
2166   // Add the nodes that are on a path between the previous node sets and
2167   // the current node set.
2168   for (NodeSet &I : NodeSets) {
2169     SmallSetVector<SUnit *, 8> N;
2170     // Add the nodes from the current node set to the previous node set.
2171     if (succ_L(I, N)) {
2172       SetVector<SUnit *> Path;
2173       for (SUnit *NI : N) {
2174         Visited.clear();
2175         computePath(NI, Path, NodesAdded, I, Visited);
2176       }
2177       if (!Path.empty())
2178         I.insert(Path.begin(), Path.end());
2179     }
2180     // Add the nodes from the previous node set to the current node set.
2181     N.clear();
2182     if (succ_L(NodesAdded, N)) {
2183       SetVector<SUnit *> Path;
2184       for (SUnit *NI : N) {
2185         Visited.clear();
2186         computePath(NI, Path, I, NodesAdded, Visited);
2187       }
2188       if (!Path.empty())
2189         I.insert(Path.begin(), Path.end());
2190     }
2191     NodesAdded.insert(I.begin(), I.end());
2192   }
2193 
2194   // Create a new node set with the connected nodes of any successor of a node
2195   // in a recurrent set.
2196   NodeSet NewSet;
2197   SmallSetVector<SUnit *, 8> N;
2198   if (succ_L(NodesAdded, N))
2199     for (SUnit *I : N)
2200       addConnectedNodes(I, NewSet, NodesAdded);
2201   if (!NewSet.empty())
2202     NodeSets.push_back(NewSet);
2203 
2204   // Create a new node set with the connected nodes of any predecessor of a node
2205   // in a recurrent set.
2206   NewSet.clear();
2207   if (pred_L(NodesAdded, N))
2208     for (SUnit *I : N)
2209       addConnectedNodes(I, NewSet, NodesAdded);
2210   if (!NewSet.empty())
2211     NodeSets.push_back(NewSet);
2212 
2213   // Create new nodes sets with the connected nodes any remaining node that
2214   // has no predecessor.
2215   for (SUnit &SU : SUnits) {
2216     if (NodesAdded.count(&SU) == 0) {
2217       NewSet.clear();
2218       addConnectedNodes(&SU, NewSet, NodesAdded);
2219       if (!NewSet.empty())
2220         NodeSets.push_back(NewSet);
2221     }
2222   }
2223 }
2224 
2225 /// Add the node to the set, and add all of its connected nodes to the set.
2226 void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2227                                           SetVector<SUnit *> &NodesAdded) {
2228   NewSet.insert(SU);
2229   NodesAdded.insert(SU);
2230   for (auto &SI : SU->Succs) {
2231     SUnit *Successor = SI.getSUnit();
2232     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
2233         NodesAdded.count(Successor) == 0)
2234       addConnectedNodes(Successor, NewSet, NodesAdded);
2235   }
2236   for (auto &PI : SU->Preds) {
2237     SUnit *Predecessor = PI.getSUnit();
2238     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
2239       addConnectedNodes(Predecessor, NewSet, NodesAdded);
2240   }
2241 }
2242 
2243 /// Return true if Set1 contains elements in Set2. The elements in common
2244 /// are returned in a different container.
2245 static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2246                         SmallSetVector<SUnit *, 8> &Result) {
2247   Result.clear();
2248   for (SUnit *SU : Set1) {
2249     if (Set2.count(SU) != 0)
2250       Result.insert(SU);
2251   }
2252   return !Result.empty();
2253 }
2254 
2255 /// Merge the recurrence node sets that have the same initial node.
2256 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2257   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2258        ++I) {
2259     NodeSet &NI = *I;
2260     for (NodeSetType::iterator J = I + 1; J != E;) {
2261       NodeSet &NJ = *J;
2262       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2263         if (NJ.compareRecMII(NI) > 0)
2264           NI.setRecMII(NJ.getRecMII());
2265         for (SUnit *SU : *J)
2266           I->insert(SU);
2267         NodeSets.erase(J);
2268         E = NodeSets.end();
2269       } else {
2270         ++J;
2271       }
2272     }
2273   }
2274 }
2275 
2276 /// Remove nodes that have been scheduled in previous NodeSets.
2277 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2278   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2279        ++I)
2280     for (NodeSetType::iterator J = I + 1; J != E;) {
2281       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
2282 
2283       if (J->empty()) {
2284         NodeSets.erase(J);
2285         E = NodeSets.end();
2286       } else {
2287         ++J;
2288       }
2289     }
2290 }
2291 
2292 /// Compute an ordered list of the dependence graph nodes, which
2293 /// indicates the order that the nodes will be scheduled.  This is a
2294 /// two-level algorithm. First, a partial order is created, which
2295 /// consists of a list of sets ordered from highest to lowest priority.
2296 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2297   SmallSetVector<SUnit *, 8> R;
2298   NodeOrder.clear();
2299 
2300   for (auto &Nodes : NodeSets) {
2301     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2302     OrderKind Order;
2303     SmallSetVector<SUnit *, 8> N;
2304     if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2305       R.insert(N.begin(), N.end());
2306       Order = BottomUp;
2307       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
2308     } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2309       R.insert(N.begin(), N.end());
2310       Order = TopDown;
2311       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
2312     } else if (isIntersect(N, Nodes, R)) {
2313       // If some of the successors are in the existing node-set, then use the
2314       // top-down ordering.
2315       Order = TopDown;
2316       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
2317     } else if (NodeSets.size() == 1) {
2318       for (const auto &N : Nodes)
2319         if (N->Succs.size() == 0)
2320           R.insert(N);
2321       Order = BottomUp;
2322       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
2323     } else {
2324       // Find the node with the highest ASAP.
2325       SUnit *maxASAP = nullptr;
2326       for (SUnit *SU : Nodes) {
2327         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
2328             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2329           maxASAP = SU;
2330       }
2331       R.insert(maxASAP);
2332       Order = BottomUp;
2333       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
2334     }
2335 
2336     while (!R.empty()) {
2337       if (Order == TopDown) {
2338         // Choose the node with the maximum height.  If more than one, choose
2339         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2340         // choose the node with the lowest MOV.
2341         while (!R.empty()) {
2342           SUnit *maxHeight = nullptr;
2343           for (SUnit *I : R) {
2344             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2345               maxHeight = I;
2346             else if (getHeight(I) == getHeight(maxHeight) &&
2347                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
2348               maxHeight = I;
2349             else if (getHeight(I) == getHeight(maxHeight) &&
2350                      getZeroLatencyHeight(I) ==
2351                          getZeroLatencyHeight(maxHeight) &&
2352                      getMOV(I) < getMOV(maxHeight))
2353               maxHeight = I;
2354           }
2355           NodeOrder.insert(maxHeight);
2356           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
2357           R.remove(maxHeight);
2358           for (const auto &I : maxHeight->Succs) {
2359             if (Nodes.count(I.getSUnit()) == 0)
2360               continue;
2361             if (NodeOrder.contains(I.getSUnit()))
2362               continue;
2363             if (ignoreDependence(I, false))
2364               continue;
2365             R.insert(I.getSUnit());
2366           }
2367           // Back-edges are predecessors with an anti-dependence.
2368           for (const auto &I : maxHeight->Preds) {
2369             if (I.getKind() != SDep::Anti)
2370               continue;
2371             if (Nodes.count(I.getSUnit()) == 0)
2372               continue;
2373             if (NodeOrder.contains(I.getSUnit()))
2374               continue;
2375             R.insert(I.getSUnit());
2376           }
2377         }
2378         Order = BottomUp;
2379         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
2380         SmallSetVector<SUnit *, 8> N;
2381         if (pred_L(NodeOrder, N, &Nodes))
2382           R.insert(N.begin(), N.end());
2383       } else {
2384         // Choose the node with the maximum depth.  If more than one, choose
2385         // the node with the maximum ZeroLatencyDepth. If still more than one,
2386         // choose the node with the lowest MOV.
2387         while (!R.empty()) {
2388           SUnit *maxDepth = nullptr;
2389           for (SUnit *I : R) {
2390             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2391               maxDepth = I;
2392             else if (getDepth(I) == getDepth(maxDepth) &&
2393                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
2394               maxDepth = I;
2395             else if (getDepth(I) == getDepth(maxDepth) &&
2396                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
2397                      getMOV(I) < getMOV(maxDepth))
2398               maxDepth = I;
2399           }
2400           NodeOrder.insert(maxDepth);
2401           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
2402           R.remove(maxDepth);
2403           if (Nodes.isExceedSU(maxDepth)) {
2404             Order = TopDown;
2405             R.clear();
2406             R.insert(Nodes.getNode(0));
2407             break;
2408           }
2409           for (const auto &I : maxDepth->Preds) {
2410             if (Nodes.count(I.getSUnit()) == 0)
2411               continue;
2412             if (NodeOrder.contains(I.getSUnit()))
2413               continue;
2414             R.insert(I.getSUnit());
2415           }
2416           // Back-edges are predecessors with an anti-dependence.
2417           for (const auto &I : maxDepth->Succs) {
2418             if (I.getKind() != SDep::Anti)
2419               continue;
2420             if (Nodes.count(I.getSUnit()) == 0)
2421               continue;
2422             if (NodeOrder.contains(I.getSUnit()))
2423               continue;
2424             R.insert(I.getSUnit());
2425           }
2426         }
2427         Order = TopDown;
2428         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
2429         SmallSetVector<SUnit *, 8> N;
2430         if (succ_L(NodeOrder, N, &Nodes))
2431           R.insert(N.begin(), N.end());
2432       }
2433     }
2434     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2435   }
2436 
2437   LLVM_DEBUG({
2438     dbgs() << "Node order: ";
2439     for (SUnit *I : NodeOrder)
2440       dbgs() << " " << I->NodeNum << " ";
2441     dbgs() << "\n";
2442   });
2443 }
2444 
2445 /// Process the nodes in the computed order and create the pipelined schedule
2446 /// of the instructions, if possible. Return true if a schedule is found.
2447 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2448 
2449   if (NodeOrder.empty()){
2450     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2451     return false;
2452   }
2453 
2454   bool scheduleFound = false;
2455   std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
2456   if (LimitRegPressure) {
2457     HRPDetector =
2458         std::make_unique<HighRegisterPressureDetector>(Loop.getHeader(), MF);
2459     HRPDetector->init(RegClassInfo);
2460   }
2461   // Keep increasing II until a valid schedule is found.
2462   for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2463     Schedule.reset();
2464     Schedule.setInitiationInterval(II);
2465     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2466 
2467     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2468     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2469     do {
2470       SUnit *SU = *NI;
2471 
2472       // Compute the schedule time for the instruction, which is based
2473       // upon the scheduled time for any predecessors/successors.
2474       int EarlyStart = INT_MIN;
2475       int LateStart = INT_MAX;
2476       Schedule.computeStart(SU, &EarlyStart, &LateStart, II, this);
2477       LLVM_DEBUG({
2478         dbgs() << "\n";
2479         dbgs() << "Inst (" << SU->NodeNum << ") ";
2480         SU->getInstr()->dump();
2481         dbgs() << "\n";
2482       });
2483       LLVM_DEBUG(
2484           dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2485 
2486       if (EarlyStart > LateStart)
2487         scheduleFound = false;
2488       else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2489         scheduleFound =
2490             Schedule.insert(SU, EarlyStart, EarlyStart + (int)II - 1, II);
2491       else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2492         scheduleFound =
2493             Schedule.insert(SU, LateStart, LateStart - (int)II + 1, II);
2494       else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2495         LateStart = std::min(LateStart, EarlyStart + (int)II - 1);
2496         // When scheduling a Phi it is better to start at the late cycle and
2497         // go backwards. The default order may insert the Phi too far away
2498         // from its first dependence.
2499         // Also, do backward search when all scheduled predecessors are
2500         // loop-carried output/order dependencies. Empirically, there are also
2501         // cases where scheduling becomes possible with backward search.
2502         if (SU->getInstr()->isPHI() ||
2503             Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, this))
2504           scheduleFound = Schedule.insert(SU, LateStart, EarlyStart, II);
2505         else
2506           scheduleFound = Schedule.insert(SU, EarlyStart, LateStart, II);
2507       } else {
2508         int FirstCycle = Schedule.getFirstCycle();
2509         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2510                                         FirstCycle + getASAP(SU) + II - 1, II);
2511       }
2512 
2513       // Even if we find a schedule, make sure the schedule doesn't exceed the
2514       // allowable number of stages. We keep trying if this happens.
2515       if (scheduleFound)
2516         if (SwpMaxStages > -1 &&
2517             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2518           scheduleFound = false;
2519 
2520       LLVM_DEBUG({
2521         if (!scheduleFound)
2522           dbgs() << "\tCan't schedule\n";
2523       });
2524     } while (++NI != NE && scheduleFound);
2525 
2526     // If a schedule is found, ensure non-pipelined instructions are in stage 0
2527     if (scheduleFound)
2528       scheduleFound =
2529           Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2530 
2531     // If a schedule is found, check if it is a valid schedule too.
2532     if (scheduleFound)
2533       scheduleFound = Schedule.isValidSchedule(this);
2534 
2535     // If a schedule was found and the option is enabled, check if the schedule
2536     // might generate additional register spills/fills.
2537     if (scheduleFound && LimitRegPressure)
2538       scheduleFound =
2539           !HRPDetector->detect(this, Schedule, Schedule.getMaxStageCount());
2540   }
2541 
2542   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2543                     << " (II=" << Schedule.getInitiationInterval()
2544                     << ")\n");
2545 
2546   if (scheduleFound) {
2547     scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*this, Schedule);
2548     if (!scheduleFound)
2549       LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2550   }
2551 
2552   if (scheduleFound) {
2553     Schedule.finalizeSchedule(this);
2554     Pass.ORE->emit([&]() {
2555       return MachineOptimizationRemarkAnalysis(
2556                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2557              << "Schedule found with Initiation Interval: "
2558              << ore::NV("II", Schedule.getInitiationInterval())
2559              << ", MaxStageCount: "
2560              << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2561     });
2562   } else
2563     Schedule.reset();
2564 
2565   return scheduleFound && Schedule.getMaxStageCount() > 0;
2566 }
2567 
2568 /// Return true if we can compute the amount the instruction changes
2569 /// during each iteration. Set Delta to the amount of the change.
2570 bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) const {
2571   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2572   const MachineOperand *BaseOp;
2573   int64_t Offset;
2574   bool OffsetIsScalable;
2575   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
2576     return false;
2577 
2578   // FIXME: This algorithm assumes instructions have fixed-size offsets.
2579   if (OffsetIsScalable)
2580     return false;
2581 
2582   if (!BaseOp->isReg())
2583     return false;
2584 
2585   Register BaseReg = BaseOp->getReg();
2586 
2587   MachineRegisterInfo &MRI = MF.getRegInfo();
2588   // Check if there is a Phi. If so, get the definition in the loop.
2589   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2590   if (BaseDef && BaseDef->isPHI()) {
2591     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2592     BaseDef = MRI.getVRegDef(BaseReg);
2593   }
2594   if (!BaseDef)
2595     return false;
2596 
2597   int D = 0;
2598   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2599     return false;
2600 
2601   Delta = D;
2602   return true;
2603 }
2604 
2605 /// Check if we can change the instruction to use an offset value from the
2606 /// previous iteration. If so, return true and set the base and offset values
2607 /// so that we can rewrite the load, if necessary.
2608 ///   v1 = Phi(v0, v3)
2609 ///   v2 = load v1, 0
2610 ///   v3 = post_store v1, 4, x
2611 /// This function enables the load to be rewritten as v2 = load v3, 4.
2612 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2613                                               unsigned &BasePos,
2614                                               unsigned &OffsetPos,
2615                                               unsigned &NewBase,
2616                                               int64_t &Offset) {
2617   // Get the load instruction.
2618   if (TII->isPostIncrement(*MI))
2619     return false;
2620   unsigned BasePosLd, OffsetPosLd;
2621   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2622     return false;
2623   Register BaseReg = MI->getOperand(BasePosLd).getReg();
2624 
2625   // Look for the Phi instruction.
2626   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2627   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2628   if (!Phi || !Phi->isPHI())
2629     return false;
2630   // Get the register defined in the loop block.
2631   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2632   if (!PrevReg)
2633     return false;
2634 
2635   // Check for the post-increment load/store instruction.
2636   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2637   if (!PrevDef || PrevDef == MI)
2638     return false;
2639 
2640   if (!TII->isPostIncrement(*PrevDef))
2641     return false;
2642 
2643   unsigned BasePos1 = 0, OffsetPos1 = 0;
2644   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2645     return false;
2646 
2647   // Make sure that the instructions do not access the same memory location in
2648   // the next iteration.
2649   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2650   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
2651   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2652   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2653   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2654   MF.deleteMachineInstr(NewMI);
2655   if (!Disjoint)
2656     return false;
2657 
2658   // Set the return value once we determine that we return true.
2659   BasePos = BasePosLd;
2660   OffsetPos = OffsetPosLd;
2661   NewBase = PrevReg;
2662   Offset = StoreOffset;
2663   return true;
2664 }
2665 
2666 /// Apply changes to the instruction if needed. The changes are need
2667 /// to improve the scheduling and depend up on the final schedule.
2668 void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2669                                          SMSchedule &Schedule) {
2670   SUnit *SU = getSUnit(MI);
2671   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2672       InstrChanges.find(SU);
2673   if (It != InstrChanges.end()) {
2674     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2675     unsigned BasePos, OffsetPos;
2676     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2677       return;
2678     Register BaseReg = MI->getOperand(BasePos).getReg();
2679     MachineInstr *LoopDef = findDefInLoop(BaseReg);
2680     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2681     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2682     int BaseStageNum = Schedule.stageScheduled(SU);
2683     int BaseCycleNum = Schedule.cycleScheduled(SU);
2684     if (BaseStageNum < DefStageNum) {
2685       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2686       int OffsetDiff = DefStageNum - BaseStageNum;
2687       if (DefCycleNum < BaseCycleNum) {
2688         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2689         if (OffsetDiff > 0)
2690           --OffsetDiff;
2691       }
2692       int64_t NewOffset =
2693           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2694       NewMI->getOperand(OffsetPos).setImm(NewOffset);
2695       SU->setInstr(NewMI);
2696       MISUnitMap[NewMI] = SU;
2697       NewMIs[MI] = NewMI;
2698     }
2699   }
2700 }
2701 
2702 /// Return the instruction in the loop that defines the register.
2703 /// If the definition is a Phi, then follow the Phi operand to
2704 /// the instruction in the loop.
2705 MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
2706   SmallPtrSet<MachineInstr *, 8> Visited;
2707   MachineInstr *Def = MRI.getVRegDef(Reg);
2708   while (Def->isPHI()) {
2709     if (!Visited.insert(Def).second)
2710       break;
2711     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2712       if (Def->getOperand(i + 1).getMBB() == BB) {
2713         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2714         break;
2715       }
2716   }
2717   return Def;
2718 }
2719 
2720 /// Return true for an order or output dependence that is loop carried
2721 /// potentially. A dependence is loop carried if the destination defines a value
2722 /// that may be used or defined by the source in a subsequent iteration.
2723 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2724                                          bool isSucc) const {
2725   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2726       Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
2727     return false;
2728 
2729   if (!SwpPruneLoopCarried)
2730     return true;
2731 
2732   if (Dep.getKind() == SDep::Output)
2733     return true;
2734 
2735   MachineInstr *SI = Source->getInstr();
2736   MachineInstr *DI = Dep.getSUnit()->getInstr();
2737   if (!isSucc)
2738     std::swap(SI, DI);
2739   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2740 
2741   // Assume ordered loads and stores may have a loop carried dependence.
2742   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
2743       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2744       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2745     return true;
2746 
2747   if (!DI->mayLoadOrStore() || !SI->mayLoadOrStore())
2748     return false;
2749 
2750   // The conservative assumption is that a dependence between memory operations
2751   // may be loop carried. The following code checks when it can be proved that
2752   // there is no loop carried dependence.
2753   unsigned DeltaS, DeltaD;
2754   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2755     return true;
2756 
2757   const MachineOperand *BaseOpS, *BaseOpD;
2758   int64_t OffsetS, OffsetD;
2759   bool OffsetSIsScalable, OffsetDIsScalable;
2760   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2761   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
2762                                     TRI) ||
2763       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
2764                                     TRI))
2765     return true;
2766 
2767   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
2768          "Expected offsets to be byte offsets");
2769 
2770   MachineInstr *DefS = MRI.getVRegDef(BaseOpS->getReg());
2771   MachineInstr *DefD = MRI.getVRegDef(BaseOpD->getReg());
2772   if (!DefS || !DefD || !DefS->isPHI() || !DefD->isPHI())
2773     return true;
2774 
2775   unsigned InitValS = 0;
2776   unsigned LoopValS = 0;
2777   unsigned InitValD = 0;
2778   unsigned LoopValD = 0;
2779   getPhiRegs(*DefS, BB, InitValS, LoopValS);
2780   getPhiRegs(*DefD, BB, InitValD, LoopValD);
2781   MachineInstr *InitDefS = MRI.getVRegDef(InitValS);
2782   MachineInstr *InitDefD = MRI.getVRegDef(InitValD);
2783 
2784   if (!InitDefS->isIdenticalTo(*InitDefD))
2785     return true;
2786 
2787   // Check that the base register is incremented by a constant value for each
2788   // iteration.
2789   MachineInstr *LoopDefS = MRI.getVRegDef(LoopValS);
2790   int D = 0;
2791   if (!LoopDefS || !TII->getIncrementValue(*LoopDefS, D))
2792     return true;
2793 
2794   LocationSize AccessSizeS = (*SI->memoperands_begin())->getSize();
2795   LocationSize AccessSizeD = (*DI->memoperands_begin())->getSize();
2796 
2797   // This is the main test, which checks the offset values and the loop
2798   // increment value to determine if the accesses may be loop carried.
2799   if (!AccessSizeS.hasValue() || !AccessSizeD.hasValue())
2800     return true;
2801 
2802   if (DeltaS != DeltaD || DeltaS < AccessSizeS.getValue() ||
2803       DeltaD < AccessSizeD.getValue())
2804     return true;
2805 
2806   return (OffsetS + (int64_t)AccessSizeS.getValue() <
2807           OffsetD + (int64_t)AccessSizeD.getValue());
2808 }
2809 
2810 void SwingSchedulerDAG::postProcessDAG() {
2811   for (auto &M : Mutations)
2812     M->apply(this);
2813 }
2814 
2815 /// Try to schedule the node at the specified StartCycle and continue
2816 /// until the node is schedule or the EndCycle is reached.  This function
2817 /// returns true if the node is scheduled.  This routine may search either
2818 /// forward or backward for a place to insert the instruction based upon
2819 /// the relative values of StartCycle and EndCycle.
2820 bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2821   bool forward = true;
2822   LLVM_DEBUG({
2823     dbgs() << "Trying to insert node between " << StartCycle << " and "
2824            << EndCycle << " II: " << II << "\n";
2825   });
2826   if (StartCycle > EndCycle)
2827     forward = false;
2828 
2829   // The terminating condition depends on the direction.
2830   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2831   for (int curCycle = StartCycle; curCycle != termCycle;
2832        forward ? ++curCycle : --curCycle) {
2833 
2834     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2835         ProcItinResources.canReserveResources(*SU, curCycle)) {
2836       LLVM_DEBUG({
2837         dbgs() << "\tinsert at cycle " << curCycle << " ";
2838         SU->getInstr()->dump();
2839       });
2840 
2841       if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
2842         ProcItinResources.reserveResources(*SU, curCycle);
2843       ScheduledInstrs[curCycle].push_back(SU);
2844       InstrToCycle.insert(std::make_pair(SU, curCycle));
2845       if (curCycle > LastCycle)
2846         LastCycle = curCycle;
2847       if (curCycle < FirstCycle)
2848         FirstCycle = curCycle;
2849       return true;
2850     }
2851     LLVM_DEBUG({
2852       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2853       SU->getInstr()->dump();
2854     });
2855   }
2856   return false;
2857 }
2858 
2859 // Return the cycle of the earliest scheduled instruction in the chain.
2860 int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2861   SmallPtrSet<SUnit *, 8> Visited;
2862   SmallVector<SDep, 8> Worklist;
2863   Worklist.push_back(Dep);
2864   int EarlyCycle = INT_MAX;
2865   while (!Worklist.empty()) {
2866     const SDep &Cur = Worklist.pop_back_val();
2867     SUnit *PrevSU = Cur.getSUnit();
2868     if (Visited.count(PrevSU))
2869       continue;
2870     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2871     if (it == InstrToCycle.end())
2872       continue;
2873     EarlyCycle = std::min(EarlyCycle, it->second);
2874     for (const auto &PI : PrevSU->Preds)
2875       if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
2876         Worklist.push_back(PI);
2877     Visited.insert(PrevSU);
2878   }
2879   return EarlyCycle;
2880 }
2881 
2882 // Return the cycle of the latest scheduled instruction in the chain.
2883 int SMSchedule::latestCycleInChain(const SDep &Dep) {
2884   SmallPtrSet<SUnit *, 8> Visited;
2885   SmallVector<SDep, 8> Worklist;
2886   Worklist.push_back(Dep);
2887   int LateCycle = INT_MIN;
2888   while (!Worklist.empty()) {
2889     const SDep &Cur = Worklist.pop_back_val();
2890     SUnit *SuccSU = Cur.getSUnit();
2891     if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
2892       continue;
2893     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2894     if (it == InstrToCycle.end())
2895       continue;
2896     LateCycle = std::max(LateCycle, it->second);
2897     for (const auto &SI : SuccSU->Succs)
2898       if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
2899         Worklist.push_back(SI);
2900     Visited.insert(SuccSU);
2901   }
2902   return LateCycle;
2903 }
2904 
2905 /// If an instruction has a use that spans multiple iterations, then
2906 /// return true. These instructions are characterized by having a back-ege
2907 /// to a Phi, which contains a reference to another Phi.
2908 static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2909   for (auto &P : SU->Preds)
2910     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2911       for (auto &S : P.getSUnit()->Succs)
2912         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2913           return P.getSUnit();
2914   return nullptr;
2915 }
2916 
2917 /// Compute the scheduling start slot for the instruction.  The start slot
2918 /// depends on any predecessor or successor nodes scheduled already.
2919 void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2920                               int II, SwingSchedulerDAG *DAG) {
2921   // Iterate over each instruction that has been scheduled already.  The start
2922   // slot computation depends on whether the previously scheduled instruction
2923   // is a predecessor or successor of the specified instruction.
2924   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2925 
2926     // Iterate over each instruction in the current cycle.
2927     for (SUnit *I : getInstructions(cycle)) {
2928       // Because we're processing a DAG for the dependences, we recognize
2929       // the back-edge in recurrences by anti dependences.
2930       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2931         const SDep &Dep = SU->Preds[i];
2932         if (Dep.getSUnit() == I) {
2933           if (!DAG->isBackedge(SU, Dep)) {
2934             int EarlyStart = cycle + Dep.getLatency() -
2935                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2936             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2937             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2938               int End = earliestCycleInChain(Dep) + (II - 1);
2939               *MinLateStart = std::min(*MinLateStart, End);
2940             }
2941           } else {
2942             int LateStart = cycle - Dep.getLatency() +
2943                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2944             *MinLateStart = std::min(*MinLateStart, LateStart);
2945           }
2946         }
2947         // For instruction that requires multiple iterations, make sure that
2948         // the dependent instruction is not scheduled past the definition.
2949         SUnit *BE = multipleIterations(I, DAG);
2950         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2951             !SU->isPred(I))
2952           *MinLateStart = std::min(*MinLateStart, cycle);
2953       }
2954       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2955         if (SU->Succs[i].getSUnit() == I) {
2956           const SDep &Dep = SU->Succs[i];
2957           if (!DAG->isBackedge(SU, Dep)) {
2958             int LateStart = cycle - Dep.getLatency() +
2959                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2960             *MinLateStart = std::min(*MinLateStart, LateStart);
2961             if (DAG->isLoopCarriedDep(SU, Dep)) {
2962               int Start = latestCycleInChain(Dep) + 1 - II;
2963               *MaxEarlyStart = std::max(*MaxEarlyStart, Start);
2964             }
2965           } else {
2966             int EarlyStart = cycle + Dep.getLatency() -
2967                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2968             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2969           }
2970         }
2971       }
2972     }
2973   }
2974 }
2975 
2976 /// Order the instructions within a cycle so that the definitions occur
2977 /// before the uses. Returns true if the instruction is added to the start
2978 /// of the list, or false if added to the end.
2979 void SMSchedule::orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
2980                                  std::deque<SUnit *> &Insts) const {
2981   MachineInstr *MI = SU->getInstr();
2982   bool OrderBeforeUse = false;
2983   bool OrderAfterDef = false;
2984   bool OrderBeforeDef = false;
2985   unsigned MoveDef = 0;
2986   unsigned MoveUse = 0;
2987   int StageInst1 = stageScheduled(SU);
2988 
2989   unsigned Pos = 0;
2990   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2991        ++I, ++Pos) {
2992     for (MachineOperand &MO : MI->operands()) {
2993       if (!MO.isReg() || !MO.getReg().isVirtual())
2994         continue;
2995 
2996       Register Reg = MO.getReg();
2997       unsigned BasePos, OffsetPos;
2998       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2999         if (MI->getOperand(BasePos).getReg() == Reg)
3000           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3001             Reg = NewReg;
3002       bool Reads, Writes;
3003       std::tie(Reads, Writes) =
3004           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3005       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3006         OrderBeforeUse = true;
3007         if (MoveUse == 0)
3008           MoveUse = Pos;
3009       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3010         // Add the instruction after the scheduled instruction.
3011         OrderAfterDef = true;
3012         MoveDef = Pos;
3013       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3014         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3015           OrderBeforeUse = true;
3016           if (MoveUse == 0)
3017             MoveUse = Pos;
3018         } else {
3019           OrderAfterDef = true;
3020           MoveDef = Pos;
3021         }
3022       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3023         OrderBeforeUse = true;
3024         if (MoveUse == 0)
3025           MoveUse = Pos;
3026         if (MoveUse != 0) {
3027           OrderAfterDef = true;
3028           MoveDef = Pos - 1;
3029         }
3030       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3031         // Add the instruction before the scheduled instruction.
3032         OrderBeforeUse = true;
3033         if (MoveUse == 0)
3034           MoveUse = Pos;
3035       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3036                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3037         if (MoveUse == 0) {
3038           OrderBeforeDef = true;
3039           MoveUse = Pos;
3040         }
3041       }
3042     }
3043     // Check for order dependences between instructions. Make sure the source
3044     // is ordered before the destination.
3045     for (auto &S : SU->Succs) {
3046       if (S.getSUnit() != *I)
3047         continue;
3048       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3049         OrderBeforeUse = true;
3050         if (Pos < MoveUse)
3051           MoveUse = Pos;
3052       }
3053       // We did not handle HW dependences in previous for loop,
3054       // and we normally set Latency = 0 for Anti/Output deps,
3055       // so may have nodes in same cycle with Anti/Output dependent on HW regs.
3056       else if ((S.getKind() == SDep::Anti || S.getKind() == SDep::Output) &&
3057                stageScheduled(*I) == StageInst1) {
3058         OrderBeforeUse = true;
3059         if ((MoveUse == 0) || (Pos < MoveUse))
3060           MoveUse = Pos;
3061       }
3062     }
3063     for (auto &P : SU->Preds) {
3064       if (P.getSUnit() != *I)
3065         continue;
3066       if ((P.getKind() == SDep::Order || P.getKind() == SDep::Anti ||
3067            P.getKind() == SDep::Output) &&
3068           stageScheduled(*I) == StageInst1) {
3069         OrderAfterDef = true;
3070         MoveDef = Pos;
3071       }
3072     }
3073   }
3074 
3075   // A circular dependence.
3076   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3077     OrderBeforeUse = false;
3078 
3079   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3080   // to a loop-carried dependence.
3081   if (OrderBeforeDef)
3082     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3083 
3084   // The uncommon case when the instruction order needs to be updated because
3085   // there is both a use and def.
3086   if (OrderBeforeUse && OrderAfterDef) {
3087     SUnit *UseSU = Insts.at(MoveUse);
3088     SUnit *DefSU = Insts.at(MoveDef);
3089     if (MoveUse > MoveDef) {
3090       Insts.erase(Insts.begin() + MoveUse);
3091       Insts.erase(Insts.begin() + MoveDef);
3092     } else {
3093       Insts.erase(Insts.begin() + MoveDef);
3094       Insts.erase(Insts.begin() + MoveUse);
3095     }
3096     orderDependence(SSD, UseSU, Insts);
3097     orderDependence(SSD, SU, Insts);
3098     orderDependence(SSD, DefSU, Insts);
3099     return;
3100   }
3101   // Put the new instruction first if there is a use in the list. Otherwise,
3102   // put it at the end of the list.
3103   if (OrderBeforeUse)
3104     Insts.push_front(SU);
3105   else
3106     Insts.push_back(SU);
3107 }
3108 
3109 /// Return true if the scheduled Phi has a loop carried operand.
3110 bool SMSchedule::isLoopCarried(const SwingSchedulerDAG *SSD,
3111                                MachineInstr &Phi) const {
3112   if (!Phi.isPHI())
3113     return false;
3114   assert(Phi.isPHI() && "Expecting a Phi.");
3115   SUnit *DefSU = SSD->getSUnit(&Phi);
3116   unsigned DefCycle = cycleScheduled(DefSU);
3117   int DefStage = stageScheduled(DefSU);
3118 
3119   unsigned InitVal = 0;
3120   unsigned LoopVal = 0;
3121   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3122   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3123   if (!UseSU)
3124     return true;
3125   if (UseSU->getInstr()->isPHI())
3126     return true;
3127   unsigned LoopCycle = cycleScheduled(UseSU);
3128   int LoopStage = stageScheduled(UseSU);
3129   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3130 }
3131 
3132 /// Return true if the instruction is a definition that is loop carried
3133 /// and defines the use on the next iteration.
3134 ///        v1 = phi(v2, v3)
3135 ///  (Def) v3 = op v1
3136 ///  (MO)   = v1
3137 /// If MO appears before Def, then v1 and v3 may get assigned to the same
3138 /// register.
3139 bool SMSchedule::isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
3140                                        MachineInstr *Def,
3141                                        MachineOperand &MO) const {
3142   if (!MO.isReg())
3143     return false;
3144   if (Def->isPHI())
3145     return false;
3146   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3147   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3148     return false;
3149   if (!isLoopCarried(SSD, *Phi))
3150     return false;
3151   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3152   for (MachineOperand &DMO : Def->all_defs()) {
3153     if (DMO.getReg() == LoopReg)
3154       return true;
3155   }
3156   return false;
3157 }
3158 
3159 /// Return true if all scheduled predecessors are loop-carried output/order
3160 /// dependencies.
3161 bool SMSchedule::onlyHasLoopCarriedOutputOrOrderPreds(
3162     SUnit *SU, SwingSchedulerDAG *DAG) const {
3163   for (const SDep &Pred : SU->Preds)
3164     if (InstrToCycle.count(Pred.getSUnit()) && !DAG->isBackedge(SU, Pred))
3165       return false;
3166   for (const SDep &Succ : SU->Succs)
3167     if (InstrToCycle.count(Succ.getSUnit()) && DAG->isBackedge(SU, Succ))
3168       return false;
3169   return true;
3170 }
3171 
3172 /// Determine transitive dependences of unpipelineable instructions
3173 SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
3174     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3175   SmallSet<SUnit *, 8> DoNotPipeline;
3176   SmallVector<SUnit *, 8> Worklist;
3177 
3178   for (auto &SU : SSD->SUnits)
3179     if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
3180       Worklist.push_back(&SU);
3181 
3182   while (!Worklist.empty()) {
3183     auto SU = Worklist.pop_back_val();
3184     if (DoNotPipeline.count(SU))
3185       continue;
3186     LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
3187     DoNotPipeline.insert(SU);
3188     for (auto &Dep : SU->Preds)
3189       Worklist.push_back(Dep.getSUnit());
3190     if (SU->getInstr()->isPHI())
3191       for (auto &Dep : SU->Succs)
3192         if (Dep.getKind() == SDep::Anti)
3193           Worklist.push_back(Dep.getSUnit());
3194   }
3195   return DoNotPipeline;
3196 }
3197 
3198 // Determine all instructions upon which any unpipelineable instruction depends
3199 // and ensure that they are in stage 0.  If unable to do so, return false.
3200 bool SMSchedule::normalizeNonPipelinedInstructions(
3201     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3202   SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
3203 
3204   int NewLastCycle = INT_MIN;
3205   for (SUnit &SU : SSD->SUnits) {
3206     if (!SU.isInstr())
3207       continue;
3208     if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
3209       NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
3210       continue;
3211     }
3212 
3213     // Put the non-pipelined instruction as early as possible in the schedule
3214     int NewCycle = getFirstCycle();
3215     for (auto &Dep : SU.Preds)
3216       NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
3217 
3218     int OldCycle = InstrToCycle[&SU];
3219     if (OldCycle != NewCycle) {
3220       InstrToCycle[&SU] = NewCycle;
3221       auto &OldS = getInstructions(OldCycle);
3222       llvm::erase(OldS, &SU);
3223       getInstructions(NewCycle).emplace_back(&SU);
3224       LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
3225                         << ") is not pipelined; moving from cycle " << OldCycle
3226                         << " to " << NewCycle << " Instr:" << *SU.getInstr());
3227     }
3228     NewLastCycle = std::max(NewLastCycle, NewCycle);
3229   }
3230   LastCycle = NewLastCycle;
3231   return true;
3232 }
3233 
3234 // Check if the generated schedule is valid. This function checks if
3235 // an instruction that uses a physical register is scheduled in a
3236 // different stage than the definition. The pipeliner does not handle
3237 // physical register values that may cross a basic block boundary.
3238 // Furthermore, if a physical def/use pair is assigned to the same
3239 // cycle, orderDependence does not guarantee def/use ordering, so that
3240 // case should be considered invalid.  (The test checks for both
3241 // earlier and same-cycle use to be more robust.)
3242 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3243   for (SUnit &SU : SSD->SUnits) {
3244     if (!SU.hasPhysRegDefs)
3245       continue;
3246     int StageDef = stageScheduled(&SU);
3247     int CycleDef = InstrToCycle[&SU];
3248     assert(StageDef != -1 && "Instruction should have been scheduled.");
3249     for (auto &SI : SU.Succs)
3250       if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
3251         if (Register::isPhysicalRegister(SI.getReg())) {
3252           if (stageScheduled(SI.getSUnit()) != StageDef)
3253             return false;
3254           if (InstrToCycle[SI.getSUnit()] <= CycleDef)
3255             return false;
3256         }
3257   }
3258   return true;
3259 }
3260 
3261 /// A property of the node order in swing-modulo-scheduling is
3262 /// that for nodes outside circuits the following holds:
3263 /// none of them is scheduled after both a successor and a
3264 /// predecessor.
3265 /// The method below checks whether the property is met.
3266 /// If not, debug information is printed and statistics information updated.
3267 /// Note that we do not use an assert statement.
3268 /// The reason is that although an invalid node oder may prevent
3269 /// the pipeliner from finding a pipelined schedule for arbitrary II,
3270 /// it does not lead to the generation of incorrect code.
3271 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3272 
3273   // a sorted vector that maps each SUnit to its index in the NodeOrder
3274   typedef std::pair<SUnit *, unsigned> UnitIndex;
3275   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3276 
3277   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3278     Indices.push_back(std::make_pair(NodeOrder[i], i));
3279 
3280   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3281     return std::get<0>(i1) < std::get<0>(i2);
3282   };
3283 
3284   // sort, so that we can perform a binary search
3285   llvm::sort(Indices, CompareKey);
3286 
3287   bool Valid = true;
3288   (void)Valid;
3289   // for each SUnit in the NodeOrder, check whether
3290   // it appears after both a successor and a predecessor
3291   // of the SUnit. If this is the case, and the SUnit
3292   // is not part of circuit, then the NodeOrder is not
3293   // valid.
3294   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3295     SUnit *SU = NodeOrder[i];
3296     unsigned Index = i;
3297 
3298     bool PredBefore = false;
3299     bool SuccBefore = false;
3300 
3301     SUnit *Succ;
3302     SUnit *Pred;
3303     (void)Succ;
3304     (void)Pred;
3305 
3306     for (SDep &PredEdge : SU->Preds) {
3307       SUnit *PredSU = PredEdge.getSUnit();
3308       unsigned PredIndex = std::get<1>(
3309           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
3310       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3311         PredBefore = true;
3312         Pred = PredSU;
3313         break;
3314       }
3315     }
3316 
3317     for (SDep &SuccEdge : SU->Succs) {
3318       SUnit *SuccSU = SuccEdge.getSUnit();
3319       // Do not process a boundary node, it was not included in NodeOrder,
3320       // hence not in Indices either, call to std::lower_bound() below will
3321       // return Indices.end().
3322       if (SuccSU->isBoundaryNode())
3323         continue;
3324       unsigned SuccIndex = std::get<1>(
3325           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
3326       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3327         SuccBefore = true;
3328         Succ = SuccSU;
3329         break;
3330       }
3331     }
3332 
3333     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3334       // instructions in circuits are allowed to be scheduled
3335       // after both a successor and predecessor.
3336       bool InCircuit = llvm::any_of(
3337           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3338       if (InCircuit)
3339         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
3340       else {
3341         Valid = false;
3342         NumNodeOrderIssues++;
3343         LLVM_DEBUG(dbgs() << "Predecessor ";);
3344       }
3345       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3346                         << " are scheduled before node " << SU->NodeNum
3347                         << "\n";);
3348     }
3349   }
3350 
3351   LLVM_DEBUG({
3352     if (!Valid)
3353       dbgs() << "Invalid node order found!\n";
3354   });
3355 }
3356 
3357 /// Attempt to fix the degenerate cases when the instruction serialization
3358 /// causes the register lifetimes to overlap. For example,
3359 ///   p' = store_pi(p, b)
3360 ///      = load p, offset
3361 /// In this case p and p' overlap, which means that two registers are needed.
3362 /// Instead, this function changes the load to use p' and updates the offset.
3363 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3364   unsigned OverlapReg = 0;
3365   unsigned NewBaseReg = 0;
3366   for (SUnit *SU : Instrs) {
3367     MachineInstr *MI = SU->getInstr();
3368     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3369       const MachineOperand &MO = MI->getOperand(i);
3370       // Look for an instruction that uses p. The instruction occurs in the
3371       // same cycle but occurs later in the serialized order.
3372       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3373         // Check that the instruction appears in the InstrChanges structure,
3374         // which contains instructions that can have the offset updated.
3375         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3376           InstrChanges.find(SU);
3377         if (It != InstrChanges.end()) {
3378           unsigned BasePos, OffsetPos;
3379           // Update the base register and adjust the offset.
3380           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
3381             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3382             NewMI->getOperand(BasePos).setReg(NewBaseReg);
3383             int64_t NewOffset =
3384                 MI->getOperand(OffsetPos).getImm() - It->second.second;
3385             NewMI->getOperand(OffsetPos).setImm(NewOffset);
3386             SU->setInstr(NewMI);
3387             MISUnitMap[NewMI] = SU;
3388             NewMIs[MI] = NewMI;
3389           }
3390         }
3391         OverlapReg = 0;
3392         NewBaseReg = 0;
3393         break;
3394       }
3395       // Look for an instruction of the form p' = op(p), which uses and defines
3396       // two virtual registers that get allocated to the same physical register.
3397       unsigned TiedUseIdx = 0;
3398       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3399         // OverlapReg is p in the example above.
3400         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3401         // NewBaseReg is p' in the example above.
3402         NewBaseReg = MI->getOperand(i).getReg();
3403         break;
3404       }
3405     }
3406   }
3407 }
3408 
3409 std::deque<SUnit *>
3410 SMSchedule::reorderInstructions(const SwingSchedulerDAG *SSD,
3411                                 const std::deque<SUnit *> &Instrs) const {
3412   std::deque<SUnit *> NewOrderPhi;
3413   for (SUnit *SU : Instrs) {
3414     if (SU->getInstr()->isPHI())
3415       NewOrderPhi.push_back(SU);
3416   }
3417   std::deque<SUnit *> NewOrderI;
3418   for (SUnit *SU : Instrs) {
3419     if (!SU->getInstr()->isPHI())
3420       orderDependence(SSD, SU, NewOrderI);
3421   }
3422   llvm::append_range(NewOrderPhi, NewOrderI);
3423   return NewOrderPhi;
3424 }
3425 
3426 /// After the schedule has been formed, call this function to combine
3427 /// the instructions from the different stages/cycles.  That is, this
3428 /// function creates a schedule that represents a single iteration.
3429 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3430   // Move all instructions to the first stage from later stages.
3431   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3432     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3433          ++stage) {
3434       std::deque<SUnit *> &cycleInstrs =
3435           ScheduledInstrs[cycle + (stage * InitiationInterval)];
3436       for (SUnit *SU : llvm::reverse(cycleInstrs))
3437         ScheduledInstrs[cycle].push_front(SU);
3438     }
3439   }
3440 
3441   // Erase all the elements in the later stages. Only one iteration should
3442   // remain in the scheduled list, and it contains all the instructions.
3443   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3444     ScheduledInstrs.erase(cycle);
3445 
3446   // Change the registers in instruction as specified in the InstrChanges
3447   // map. We need to use the new registers to create the correct order.
3448   for (const SUnit &SU : SSD->SUnits)
3449     SSD->applyInstrChange(SU.getInstr(), *this);
3450 
3451   // Reorder the instructions in each cycle to fix and improve the
3452   // generated code.
3453   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3454     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3455     cycleInstrs = reorderInstructions(SSD, cycleInstrs);
3456     SSD->fixupRegisterOverlaps(cycleInstrs);
3457   }
3458 
3459   LLVM_DEBUG(dump(););
3460 }
3461 
3462 void NodeSet::print(raw_ostream &os) const {
3463   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3464      << " depth " << MaxDepth << " col " << Colocate << "\n";
3465   for (const auto &I : Nodes)
3466     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
3467   os << "\n";
3468 }
3469 
3470 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3471 /// Print the schedule information to the given output.
3472 void SMSchedule::print(raw_ostream &os) const {
3473   // Iterate over each cycle.
3474   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3475     // Iterate over each instruction in the cycle.
3476     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3477     for (SUnit *CI : cycleInstrs->second) {
3478       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3479       os << "(" << CI->NodeNum << ") ";
3480       CI->getInstr()->print(os);
3481       os << "\n";
3482     }
3483   }
3484 }
3485 
3486 /// Utility function used for debugging to print the schedule.
3487 LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3488 LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3489 
3490 void ResourceManager::dumpMRT() const {
3491   LLVM_DEBUG({
3492     if (UseDFA)
3493       return;
3494     std::stringstream SS;
3495     SS << "MRT:\n";
3496     SS << std::setw(4) << "Slot";
3497     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3498       SS << std::setw(3) << I;
3499     SS << std::setw(7) << "#Mops"
3500        << "\n";
3501     for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3502       SS << std::setw(4) << Slot;
3503       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3504         SS << std::setw(3) << MRT[Slot][I];
3505       SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3506     }
3507     dbgs() << SS.str();
3508   });
3509 }
3510 #endif
3511 
3512 void ResourceManager::initProcResourceVectors(
3513     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3514   unsigned ProcResourceID = 0;
3515 
3516   // We currently limit the resource kinds to 64 and below so that we can use
3517   // uint64_t for Masks
3518   assert(SM.getNumProcResourceKinds() < 64 &&
3519          "Too many kinds of resources, unsupported");
3520   // Create a unique bitmask for every processor resource unit.
3521   // Skip resource at index 0, since it always references 'InvalidUnit'.
3522   Masks.resize(SM.getNumProcResourceKinds());
3523   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3524     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3525     if (Desc.SubUnitsIdxBegin)
3526       continue;
3527     Masks[I] = 1ULL << ProcResourceID;
3528     ProcResourceID++;
3529   }
3530   // Create a unique bitmask for every processor resource group.
3531   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3532     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3533     if (!Desc.SubUnitsIdxBegin)
3534       continue;
3535     Masks[I] = 1ULL << ProcResourceID;
3536     for (unsigned U = 0; U < Desc.NumUnits; ++U)
3537       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3538     ProcResourceID++;
3539   }
3540   LLVM_DEBUG({
3541     if (SwpShowResMask) {
3542       dbgs() << "ProcResourceDesc:\n";
3543       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3544         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3545         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3546                          ProcResource->Name, I, Masks[I],
3547                          ProcResource->NumUnits);
3548       }
3549       dbgs() << " -----------------\n";
3550     }
3551   });
3552 }
3553 
3554 bool ResourceManager::canReserveResources(SUnit &SU, int Cycle) {
3555   LLVM_DEBUG({
3556     if (SwpDebugResource)
3557       dbgs() << "canReserveResources:\n";
3558   });
3559   if (UseDFA)
3560     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3561         ->canReserveResources(&SU.getInstr()->getDesc());
3562 
3563   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3564   if (!SCDesc->isValid()) {
3565     LLVM_DEBUG({
3566       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3567       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3568     });
3569     return true;
3570   }
3571 
3572   reserveResources(SCDesc, Cycle);
3573   bool Result = !isOverbooked();
3574   unreserveResources(SCDesc, Cycle);
3575 
3576   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return " << Result << "\n\n";);
3577   return Result;
3578 }
3579 
3580 void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
3581   LLVM_DEBUG({
3582     if (SwpDebugResource)
3583       dbgs() << "reserveResources:\n";
3584   });
3585   if (UseDFA)
3586     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3587         ->reserveResources(&SU.getInstr()->getDesc());
3588 
3589   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3590   if (!SCDesc->isValid()) {
3591     LLVM_DEBUG({
3592       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3593       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3594     });
3595     return;
3596   }
3597 
3598   reserveResources(SCDesc, Cycle);
3599 
3600   LLVM_DEBUG({
3601     if (SwpDebugResource) {
3602       dumpMRT();
3603       dbgs() << "reserveResources: done!\n\n";
3604     }
3605   });
3606 }
3607 
3608 void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
3609                                        int Cycle) {
3610   assert(!UseDFA);
3611   for (const MCWriteProcResEntry &PRE : make_range(
3612            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3613     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3614       ++MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3615 
3616   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3617     ++NumScheduledMops[positiveModulo(C, InitiationInterval)];
3618 }
3619 
3620 void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
3621                                          int Cycle) {
3622   assert(!UseDFA);
3623   for (const MCWriteProcResEntry &PRE : make_range(
3624            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3625     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3626       --MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3627 
3628   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3629     --NumScheduledMops[positiveModulo(C, InitiationInterval)];
3630 }
3631 
3632 bool ResourceManager::isOverbooked() const {
3633   assert(!UseDFA);
3634   for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3635     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3636       const MCProcResourceDesc *Desc = SM.getProcResource(I);
3637       if (MRT[Slot][I] > Desc->NumUnits)
3638         return true;
3639     }
3640     if (NumScheduledMops[Slot] > IssueWidth)
3641       return true;
3642   }
3643   return false;
3644 }
3645 
3646 int ResourceManager::calculateResMIIDFA() const {
3647   assert(UseDFA);
3648 
3649   // Sort the instructions by the number of available choices for scheduling,
3650   // least to most. Use the number of critical resources as the tie breaker.
3651   FuncUnitSorter FUS = FuncUnitSorter(*ST);
3652   for (SUnit &SU : DAG->SUnits)
3653     FUS.calcCriticalResources(*SU.getInstr());
3654   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
3655       FuncUnitOrder(FUS);
3656 
3657   for (SUnit &SU : DAG->SUnits)
3658     FuncUnitOrder.push(SU.getInstr());
3659 
3660   SmallVector<std::unique_ptr<DFAPacketizer>, 8> Resources;
3661   Resources.push_back(
3662       std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
3663 
3664   while (!FuncUnitOrder.empty()) {
3665     MachineInstr *MI = FuncUnitOrder.top();
3666     FuncUnitOrder.pop();
3667     if (TII->isZeroCost(MI->getOpcode()))
3668       continue;
3669 
3670     // Attempt to reserve the instruction in an existing DFA. At least one
3671     // DFA is needed for each cycle.
3672     unsigned NumCycles = DAG->getSUnit(MI)->Latency;
3673     unsigned ReservedCycles = 0;
3674     auto *RI = Resources.begin();
3675     auto *RE = Resources.end();
3676     LLVM_DEBUG({
3677       dbgs() << "Trying to reserve resource for " << NumCycles
3678              << " cycles for \n";
3679       MI->dump();
3680     });
3681     for (unsigned C = 0; C < NumCycles; ++C)
3682       while (RI != RE) {
3683         if ((*RI)->canReserveResources(*MI)) {
3684           (*RI)->reserveResources(*MI);
3685           ++ReservedCycles;
3686           break;
3687         }
3688         RI++;
3689       }
3690     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
3691                       << ", NumCycles:" << NumCycles << "\n");
3692     // Add new DFAs, if needed, to reserve resources.
3693     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
3694       LLVM_DEBUG(if (SwpDebugResource) dbgs()
3695                  << "NewResource created to reserve resources"
3696                  << "\n");
3697       auto *NewResource = TII->CreateTargetScheduleState(*ST);
3698       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
3699       NewResource->reserveResources(*MI);
3700       Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
3701     }
3702   }
3703 
3704   int Resmii = Resources.size();
3705   LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
3706   return Resmii;
3707 }
3708 
3709 int ResourceManager::calculateResMII() const {
3710   if (UseDFA)
3711     return calculateResMIIDFA();
3712 
3713   // Count each resource consumption and divide it by the number of units.
3714   // ResMII is the max value among them.
3715 
3716   int NumMops = 0;
3717   SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
3718   for (SUnit &SU : DAG->SUnits) {
3719     if (TII->isZeroCost(SU.getInstr()->getOpcode()))
3720       continue;
3721 
3722     const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3723     if (!SCDesc->isValid())
3724       continue;
3725 
3726     LLVM_DEBUG({
3727       if (SwpDebugResource) {
3728         DAG->dumpNode(SU);
3729         dbgs() << "  #Mops: " << SCDesc->NumMicroOps << "\n"
3730                << "  WriteProcRes: ";
3731       }
3732     });
3733     NumMops += SCDesc->NumMicroOps;
3734     for (const MCWriteProcResEntry &PRE :
3735          make_range(STI->getWriteProcResBegin(SCDesc),
3736                     STI->getWriteProcResEnd(SCDesc))) {
3737       LLVM_DEBUG({
3738         if (SwpDebugResource) {
3739           const MCProcResourceDesc *Desc =
3740               SM.getProcResource(PRE.ProcResourceIdx);
3741           dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
3742         }
3743       });
3744       ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
3745     }
3746     LLVM_DEBUG(if (SwpDebugResource) dbgs() << "\n");
3747   }
3748 
3749   int Result = (NumMops + IssueWidth - 1) / IssueWidth;
3750   LLVM_DEBUG({
3751     if (SwpDebugResource)
3752       dbgs() << "#Mops: " << NumMops << ", "
3753              << "IssueWidth: " << IssueWidth << ", "
3754              << "Cycles: " << Result << "\n";
3755   });
3756 
3757   LLVM_DEBUG({
3758     if (SwpDebugResource) {
3759       std::stringstream SS;
3760       SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
3761          << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
3762          << "\n";
3763       dbgs() << SS.str();
3764     }
3765   });
3766   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3767     const MCProcResourceDesc *Desc = SM.getProcResource(I);
3768     int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
3769     LLVM_DEBUG({
3770       if (SwpDebugResource) {
3771         std::stringstream SS;
3772         SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
3773            << Desc->NumUnits << std::setw(10) << ResourceCount[I]
3774            << std::setw(10) << Cycles << "\n";
3775         dbgs() << SS.str();
3776       }
3777     });
3778     if (Cycles > Result)
3779       Result = Cycles;
3780   }
3781   return Result;
3782 }
3783 
3784 void ResourceManager::init(int II) {
3785   InitiationInterval = II;
3786   DFAResources.clear();
3787   DFAResources.resize(II);
3788   for (auto &I : DFAResources)
3789     I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
3790   MRT.clear();
3791   MRT.resize(II, SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
3792   NumScheduledMops.clear();
3793   NumScheduledMops.resize(II);
3794 }
3795