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