132a40564SEugene Zelenko //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2254f889dSBrendon Cahoon //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6254f889dSBrendon Cahoon //
7254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
8254f889dSBrendon Cahoon //
9254f889dSBrendon Cahoon // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10254f889dSBrendon Cahoon //
11254f889dSBrendon Cahoon // This SMS implementation is a target-independent back-end pass. When enabled,
12254f889dSBrendon Cahoon // the pass runs just prior to the register allocation pass, while the machine
13254f889dSBrendon Cahoon // IR is in SSA form. If software pipelining is successful, then the original
14254f889dSBrendon Cahoon // loop is replaced by the optimized loop. The optimized loop contains one or
15254f889dSBrendon Cahoon // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16254f889dSBrendon Cahoon // the instructions cannot be scheduled in a given MII, we increase the MII by
17254f889dSBrendon Cahoon // one and try again.
18254f889dSBrendon Cahoon //
19254f889dSBrendon Cahoon // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20254f889dSBrendon Cahoon // represent loop carried dependences in the DAG as order edges to the Phi
21254f889dSBrendon Cahoon // nodes. We also perform several passes over the DAG to eliminate unnecessary
22254f889dSBrendon Cahoon // edges that inhibit the ability to pipeline. The implementation uses the
23254f889dSBrendon Cahoon // DFAPacketizer class to compute the minimum initiation interval and the check
24254f889dSBrendon Cahoon // where an instruction may be inserted in the pipelined schedule.
25254f889dSBrendon Cahoon //
26254f889dSBrendon Cahoon // In order for the SMS pass to work, several target specific hooks need to be
27254f889dSBrendon Cahoon // implemented to get information about the loop structure and to rewrite
28254f889dSBrendon Cahoon // instructions.
29254f889dSBrendon Cahoon //
30254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
31254f889dSBrendon Cahoon 
32989f1c72Sserge-sans-paille #include "llvm/CodeGen/MachinePipeliner.h"
33cdc71612SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
34cdc71612SEugene Zelenko #include "llvm/ADT/BitVector.h"
35254f889dSBrendon Cahoon #include "llvm/ADT/DenseMap.h"
36254f889dSBrendon Cahoon #include "llvm/ADT/MapVector.h"
37254f889dSBrendon Cahoon #include "llvm/ADT/PriorityQueue.h"
38d6391209SKazu Hirata #include "llvm/ADT/SetOperations.h"
39254f889dSBrendon Cahoon #include "llvm/ADT/SetVector.h"
40254f889dSBrendon Cahoon #include "llvm/ADT/SmallPtrSet.h"
41254f889dSBrendon Cahoon #include "llvm/ADT/SmallSet.h"
42cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h"
43254f889dSBrendon Cahoon #include "llvm/ADT/Statistic.h"
446bda14b3SChandler Carruth #include "llvm/ADT/iterator_range.h"
45254f889dSBrendon Cahoon #include "llvm/Analysis/AliasAnalysis.h"
46cdc71612SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h"
47989f1c72Sserge-sans-paille #include "llvm/Analysis/OptimizationRemarkEmitter.h"
48254f889dSBrendon Cahoon #include "llvm/Analysis/ValueTracking.h"
49254f889dSBrendon Cahoon #include "llvm/CodeGen/DFAPacketizer.h"
50f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
51254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineBasicBlock.h"
52254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineDominators.h"
53cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
54cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunctionPass.h"
55cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h"
56254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineInstrBuilder.h"
57254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineLoopInfo.h"
58cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineMemOperand.h"
59cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h"
60254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineRegisterInfo.h"
61790a779fSJames Molloy #include "llvm/CodeGen/ModuloSchedule.h"
62254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterPressure.h"
63cdc71612SEugene Zelenko #include "llvm/CodeGen/ScheduleDAG.h"
6488391248SKrzysztof Parzyszek #include "llvm/CodeGen/ScheduleDAGMutation.h"
65b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h"
66b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
67b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
68432a3883SNico Weber #include "llvm/Config/llvm-config.h"
69cdc71612SEugene Zelenko #include "llvm/IR/Attributes.h"
7032a40564SEugene Zelenko #include "llvm/IR/Function.h"
7132a40564SEugene Zelenko #include "llvm/MC/LaneBitmask.h"
7232a40564SEugene Zelenko #include "llvm/MC/MCInstrDesc.h"
73254f889dSBrendon Cahoon #include "llvm/MC/MCInstrItineraries.h"
7432a40564SEugene Zelenko #include "llvm/MC/MCRegisterInfo.h"
7532a40564SEugene Zelenko #include "llvm/Pass.h"
76254f889dSBrendon Cahoon #include "llvm/Support/CommandLine.h"
7732a40564SEugene Zelenko #include "llvm/Support/Compiler.h"
78254f889dSBrendon Cahoon #include "llvm/Support/Debug.h"
79cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h"
80254f889dSBrendon Cahoon #include "llvm/Support/raw_ostream.h"
81cdc71612SEugene Zelenko #include <algorithm>
82cdc71612SEugene Zelenko #include <cassert>
83254f889dSBrendon Cahoon #include <climits>
84cdc71612SEugene Zelenko #include <cstdint>
85254f889dSBrendon Cahoon #include <deque>
86cdc71612SEugene Zelenko #include <functional>
87cdc71612SEugene Zelenko #include <iterator>
88254f889dSBrendon Cahoon #include <map>
8932a40564SEugene Zelenko #include <memory>
90cdc71612SEugene Zelenko #include <tuple>
91cdc71612SEugene Zelenko #include <utility>
92cdc71612SEugene Zelenko #include <vector>
93254f889dSBrendon Cahoon 
94254f889dSBrendon Cahoon using namespace llvm;
95254f889dSBrendon Cahoon 
96254f889dSBrendon Cahoon #define DEBUG_TYPE "pipeliner"
97254f889dSBrendon Cahoon 
98254f889dSBrendon Cahoon STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
99254f889dSBrendon Cahoon STATISTIC(NumPipelined, "Number of loops software pipelined");
1004b8bcf00SRoorda, Jan-Willem STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
10118e7bf5cSJinsong Ji STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
10218e7bf5cSJinsong Ji STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
10318e7bf5cSJinsong Ji STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
10418e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
10518e7bf5cSJinsong Ji STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
10618e7bf5cSJinsong Ji STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
10718e7bf5cSJinsong Ji STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
10818e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
109254f889dSBrendon Cahoon 
110254f889dSBrendon Cahoon /// A command line option to turn software pipelining on or off.
111b7d3311cSBenjamin Kramer static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
112b7d3311cSBenjamin Kramer                                cl::ZeroOrMore,
113b7d3311cSBenjamin Kramer                                cl::desc("Enable Software Pipelining"));
114254f889dSBrendon Cahoon 
115254f889dSBrendon Cahoon /// A command line option to enable SWP at -Os.
116254f889dSBrendon Cahoon static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
117254f889dSBrendon Cahoon                                       cl::desc("Enable SWP at Os."), cl::Hidden,
118254f889dSBrendon Cahoon                                       cl::init(false));
119254f889dSBrendon Cahoon 
120254f889dSBrendon Cahoon /// A command line argument to limit minimum initial interval for pipelining.
121254f889dSBrendon Cahoon static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
1228f976ba0SHiroshi Inoue                               cl::desc("Size limit for the MII."),
123254f889dSBrendon Cahoon                               cl::Hidden, cl::init(27));
124254f889dSBrendon Cahoon 
125254f889dSBrendon Cahoon /// A command line argument to limit the number of stages in the pipeline.
126254f889dSBrendon Cahoon static cl::opt<int>
127254f889dSBrendon Cahoon     SwpMaxStages("pipeliner-max-stages",
128254f889dSBrendon Cahoon                  cl::desc("Maximum stages allowed in the generated scheduled."),
129254f889dSBrendon Cahoon                  cl::Hidden, cl::init(3));
130254f889dSBrendon Cahoon 
131254f889dSBrendon Cahoon /// A command line option to disable the pruning of chain dependences due to
132254f889dSBrendon Cahoon /// an unrelated Phi.
133254f889dSBrendon Cahoon static cl::opt<bool>
134254f889dSBrendon Cahoon     SwpPruneDeps("pipeliner-prune-deps",
135254f889dSBrendon Cahoon                  cl::desc("Prune dependences between unrelated Phi nodes."),
136254f889dSBrendon Cahoon                  cl::Hidden, cl::init(true));
137254f889dSBrendon Cahoon 
138254f889dSBrendon Cahoon /// A command line option to disable the pruning of loop carried order
139254f889dSBrendon Cahoon /// dependences.
140254f889dSBrendon Cahoon static cl::opt<bool>
141254f889dSBrendon Cahoon     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
142254f889dSBrendon Cahoon                         cl::desc("Prune loop carried order dependences."),
143254f889dSBrendon Cahoon                         cl::Hidden, cl::init(true));
144254f889dSBrendon Cahoon 
145254f889dSBrendon Cahoon #ifndef NDEBUG
146254f889dSBrendon Cahoon static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
147254f889dSBrendon Cahoon #endif
148254f889dSBrendon Cahoon 
149254f889dSBrendon Cahoon static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
150254f889dSBrendon Cahoon                                      cl::ReallyHidden, cl::init(false),
151254f889dSBrendon Cahoon                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
152254f889dSBrendon Cahoon 
153ba43840bSJinsong Ji static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
154ba43840bSJinsong Ji                                     cl::init(false));
155ba43840bSJinsong Ji static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
156ba43840bSJinsong Ji                                       cl::init(false));
157ba43840bSJinsong Ji 
15893549957SJames Molloy static cl::opt<bool> EmitTestAnnotations(
15993549957SJames Molloy     "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
16093549957SJames Molloy     cl::desc("Instead of emitting the pipelined code, annotate instructions "
16193549957SJames Molloy              "with the generated schedule for feeding into the "
16293549957SJames Molloy              "-modulo-schedule-test pass"));
16393549957SJames Molloy 
164fef9f590SJames Molloy static cl::opt<bool> ExperimentalCodeGen(
165fef9f590SJames Molloy     "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
166fef9f590SJames Molloy     cl::desc(
167fef9f590SJames Molloy         "Use the experimental peeling code generator for software pipelining"));
168fef9f590SJames Molloy 
169fa2e3583SAdrian Prantl namespace llvm {
170fa2e3583SAdrian Prantl 
17162ac69d4SSumanth Gundapaneni // A command line option to enable the CopyToPhi DAG mutation.
172fa2e3583SAdrian Prantl cl::opt<bool>
17300d4c386SAleksandr Urakov     SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
17462ac69d4SSumanth Gundapaneni                        cl::init(true), cl::ZeroOrMore,
17562ac69d4SSumanth Gundapaneni                        cl::desc("Enable CopyToPhi DAG Mutation"));
17662ac69d4SSumanth Gundapaneni 
177fa2e3583SAdrian Prantl } // end namespace llvm
178254f889dSBrendon Cahoon 
179254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
180254f889dSBrendon Cahoon char MachinePipeliner::ID = 0;
181254f889dSBrendon Cahoon #ifndef NDEBUG
182254f889dSBrendon Cahoon int MachinePipeliner::NumTries = 0;
183254f889dSBrendon Cahoon #endif
184254f889dSBrendon Cahoon char &llvm::MachinePipelinerID = MachinePipeliner::ID;
18532a40564SEugene Zelenko 
1861527baabSMatthias Braun INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
187254f889dSBrendon Cahoon                       "Modulo Software Pipelining", false, false)
188254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
189254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
190254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
191254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1921527baabSMatthias Braun INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
193254f889dSBrendon Cahoon                     "Modulo Software Pipelining", false, false)
194254f889dSBrendon Cahoon 
195254f889dSBrendon Cahoon /// The "main" function for implementing Swing Modulo Scheduling.
196254f889dSBrendon Cahoon bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
197f1caa283SMatthias Braun   if (skipFunction(mf.getFunction()))
198254f889dSBrendon Cahoon     return false;
199254f889dSBrendon Cahoon 
200254f889dSBrendon Cahoon   if (!EnableSWP)
201254f889dSBrendon Cahoon     return false;
202254f889dSBrendon Cahoon 
203d7593ebaSArthur Eubanks   if (mf.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
204254f889dSBrendon Cahoon       !EnableSWPOptSize.getPosition())
205254f889dSBrendon Cahoon     return false;
206254f889dSBrendon Cahoon 
207ef2d6d99SJinsong Ji   if (!mf.getSubtarget().enableMachinePipeliner())
208ef2d6d99SJinsong Ji     return false;
209ef2d6d99SJinsong Ji 
210f6cb3bcbSJinsong Ji   // Cannot pipeline loops without instruction itineraries if we are using
211f6cb3bcbSJinsong Ji   // DFA for the pipeliner.
212f6cb3bcbSJinsong Ji   if (mf.getSubtarget().useDFAforSMS() &&
213f6cb3bcbSJinsong Ji       (!mf.getSubtarget().getInstrItineraryData() ||
214f6cb3bcbSJinsong Ji        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
215f6cb3bcbSJinsong Ji     return false;
216f6cb3bcbSJinsong Ji 
217254f889dSBrendon Cahoon   MF = &mf;
218254f889dSBrendon Cahoon   MLI = &getAnalysis<MachineLoopInfo>();
219254f889dSBrendon Cahoon   MDT = &getAnalysis<MachineDominatorTree>();
22080b78a47SJinsong Ji   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
221254f889dSBrendon Cahoon   TII = MF->getSubtarget().getInstrInfo();
222254f889dSBrendon Cahoon   RegClassInfo.runOnMachineFunction(*MF);
223254f889dSBrendon Cahoon 
224254f889dSBrendon Cahoon   for (auto &L : *MLI)
225254f889dSBrendon Cahoon     scheduleLoop(*L);
226254f889dSBrendon Cahoon 
227254f889dSBrendon Cahoon   return false;
228254f889dSBrendon Cahoon }
229254f889dSBrendon Cahoon 
230254f889dSBrendon Cahoon /// Attempt to perform the SMS algorithm on the specified loop. This function is
231254f889dSBrendon Cahoon /// the main entry point for the algorithm.  The function identifies candidate
232254f889dSBrendon Cahoon /// loops, calculates the minimum initiation interval, and attempts to schedule
233254f889dSBrendon Cahoon /// the loop.
234254f889dSBrendon Cahoon bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
235254f889dSBrendon Cahoon   bool Changed = false;
236254f889dSBrendon Cahoon   for (auto &InnerLoop : L)
237254f889dSBrendon Cahoon     Changed |= scheduleLoop(*InnerLoop);
238254f889dSBrendon Cahoon 
239254f889dSBrendon Cahoon #ifndef NDEBUG
240254f889dSBrendon Cahoon   // Stop trying after reaching the limit (if any).
241254f889dSBrendon Cahoon   int Limit = SwpLoopLimit;
242254f889dSBrendon Cahoon   if (Limit >= 0) {
243254f889dSBrendon Cahoon     if (NumTries >= SwpLoopLimit)
244254f889dSBrendon Cahoon       return Changed;
245254f889dSBrendon Cahoon     NumTries++;
246254f889dSBrendon Cahoon   }
247254f889dSBrendon Cahoon #endif
248254f889dSBrendon Cahoon 
24959d99731SBrendon Cahoon   setPragmaPipelineOptions(L);
25059d99731SBrendon Cahoon   if (!canPipelineLoop(L)) {
25159d99731SBrendon Cahoon     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
25280b78a47SJinsong Ji     ORE->emit([&]() {
25380b78a47SJinsong Ji       return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
25480b78a47SJinsong Ji                                              L.getStartLoc(), L.getHeader())
25580b78a47SJinsong Ji              << "Failed to pipeline loop";
25680b78a47SJinsong Ji     });
25780b78a47SJinsong Ji 
258dcb77643SDavid Penry     LI.LoopPipelinerInfo.reset();
259254f889dSBrendon Cahoon     return Changed;
26059d99731SBrendon Cahoon   }
261254f889dSBrendon Cahoon 
262254f889dSBrendon Cahoon   ++NumTrytoPipeline;
263254f889dSBrendon Cahoon 
264254f889dSBrendon Cahoon   Changed = swingModuloScheduler(L);
265254f889dSBrendon Cahoon 
266dcb77643SDavid Penry   LI.LoopPipelinerInfo.reset();
267254f889dSBrendon Cahoon   return Changed;
268254f889dSBrendon Cahoon }
269254f889dSBrendon Cahoon 
27059d99731SBrendon Cahoon void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
271a04ab2ecSSumanth Gundapaneni   // Reset the pragma for the next loop in iteration.
272a04ab2ecSSumanth Gundapaneni   disabledByPragma = false;
273818cf30bSAlon Kom   II_setByPragma = 0;
274a04ab2ecSSumanth Gundapaneni 
27559d99731SBrendon Cahoon   MachineBasicBlock *LBLK = L.getTopBlock();
27659d99731SBrendon Cahoon 
27759d99731SBrendon Cahoon   if (LBLK == nullptr)
27859d99731SBrendon Cahoon     return;
27959d99731SBrendon Cahoon 
28059d99731SBrendon Cahoon   const BasicBlock *BBLK = LBLK->getBasicBlock();
28159d99731SBrendon Cahoon   if (BBLK == nullptr)
28259d99731SBrendon Cahoon     return;
28359d99731SBrendon Cahoon 
28459d99731SBrendon Cahoon   const Instruction *TI = BBLK->getTerminator();
28559d99731SBrendon Cahoon   if (TI == nullptr)
28659d99731SBrendon Cahoon     return;
28759d99731SBrendon Cahoon 
28859d99731SBrendon Cahoon   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
28959d99731SBrendon Cahoon   if (LoopID == nullptr)
29059d99731SBrendon Cahoon     return;
29159d99731SBrendon Cahoon 
29259d99731SBrendon Cahoon   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
29359d99731SBrendon Cahoon   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
29459d99731SBrendon Cahoon 
29559d99731SBrendon Cahoon   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
29659d99731SBrendon Cahoon     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
29759d99731SBrendon Cahoon 
29859d99731SBrendon Cahoon     if (MD == nullptr)
29959d99731SBrendon Cahoon       continue;
30059d99731SBrendon Cahoon 
30159d99731SBrendon Cahoon     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
30259d99731SBrendon Cahoon 
30359d99731SBrendon Cahoon     if (S == nullptr)
30459d99731SBrendon Cahoon       continue;
30559d99731SBrendon Cahoon 
30659d99731SBrendon Cahoon     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
30759d99731SBrendon Cahoon       assert(MD->getNumOperands() == 2 &&
30859d99731SBrendon Cahoon              "Pipeline initiation interval hint metadata should have two operands.");
30959d99731SBrendon Cahoon       II_setByPragma =
31059d99731SBrendon Cahoon           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
31159d99731SBrendon Cahoon       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
31259d99731SBrendon Cahoon     } else if (S->getString() == "llvm.loop.pipeline.disable") {
31359d99731SBrendon Cahoon       disabledByPragma = true;
31459d99731SBrendon Cahoon     }
31559d99731SBrendon Cahoon   }
31659d99731SBrendon Cahoon }
31759d99731SBrendon Cahoon 
318254f889dSBrendon Cahoon /// Return true if the loop can be software pipelined.  The algorithm is
319254f889dSBrendon Cahoon /// restricted to loops with a single basic block.  Make sure that the
320254f889dSBrendon Cahoon /// branch in the loop can be analyzed.
321254f889dSBrendon Cahoon bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
32280b78a47SJinsong Ji   if (L.getNumBlocks() != 1) {
32380b78a47SJinsong Ji     ORE->emit([&]() {
32480b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
32580b78a47SJinsong Ji                                                L.getStartLoc(), L.getHeader())
32680b78a47SJinsong Ji              << "Not a single basic block: "
32780b78a47SJinsong Ji              << ore::NV("NumBlocks", L.getNumBlocks());
32880b78a47SJinsong Ji     });
329254f889dSBrendon Cahoon     return false;
33080b78a47SJinsong Ji   }
331254f889dSBrendon Cahoon 
33280b78a47SJinsong Ji   if (disabledByPragma) {
33380b78a47SJinsong Ji     ORE->emit([&]() {
33480b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
33580b78a47SJinsong Ji                                                L.getStartLoc(), L.getHeader())
33680b78a47SJinsong Ji              << "Disabled by Pragma.";
33780b78a47SJinsong Ji     });
33859d99731SBrendon Cahoon     return false;
33980b78a47SJinsong Ji   }
34059d99731SBrendon Cahoon 
341254f889dSBrendon Cahoon   // Check if the branch can't be understood because we can't do pipelining
342254f889dSBrendon Cahoon   // if that's the case.
343254f889dSBrendon Cahoon   LI.TBB = nullptr;
344254f889dSBrendon Cahoon   LI.FBB = nullptr;
345254f889dSBrendon Cahoon   LI.BrCond.clear();
34618e7bf5cSJinsong Ji   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
34780b78a47SJinsong Ji     LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
34818e7bf5cSJinsong Ji     NumFailBranch++;
34980b78a47SJinsong Ji     ORE->emit([&]() {
35080b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
35180b78a47SJinsong Ji                                                L.getStartLoc(), L.getHeader())
35280b78a47SJinsong Ji              << "The branch can't be understood";
35380b78a47SJinsong Ji     });
354254f889dSBrendon Cahoon     return false;
35518e7bf5cSJinsong Ji   }
356254f889dSBrendon Cahoon 
357254f889dSBrendon Cahoon   LI.LoopInductionVar = nullptr;
358254f889dSBrendon Cahoon   LI.LoopCompare = nullptr;
359dcb77643SDavid Penry   LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
360dcb77643SDavid Penry   if (!LI.LoopPipelinerInfo) {
36180b78a47SJinsong Ji     LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
36218e7bf5cSJinsong Ji     NumFailLoop++;
36380b78a47SJinsong Ji     ORE->emit([&]() {
36480b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
36580b78a47SJinsong Ji                                                L.getStartLoc(), L.getHeader())
36680b78a47SJinsong Ji              << "The loop structure is not supported";
36780b78a47SJinsong Ji     });
368254f889dSBrendon Cahoon     return false;
36918e7bf5cSJinsong Ji   }
370254f889dSBrendon Cahoon 
37118e7bf5cSJinsong Ji   if (!L.getLoopPreheader()) {
37280b78a47SJinsong Ji     LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
37318e7bf5cSJinsong Ji     NumFailPreheader++;
37480b78a47SJinsong Ji     ORE->emit([&]() {
37580b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
37680b78a47SJinsong Ji                                                L.getStartLoc(), L.getHeader())
37780b78a47SJinsong Ji              << "No loop preheader found";
37880b78a47SJinsong Ji     });
379254f889dSBrendon Cahoon     return false;
38018e7bf5cSJinsong Ji   }
381254f889dSBrendon Cahoon 
382c715a5d2SKrzysztof Parzyszek   // Remove any subregisters from inputs to phi nodes.
383c715a5d2SKrzysztof Parzyszek   preprocessPhiNodes(*L.getHeader());
384254f889dSBrendon Cahoon   return true;
385254f889dSBrendon Cahoon }
386254f889dSBrendon Cahoon 
387c715a5d2SKrzysztof Parzyszek void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
388c715a5d2SKrzysztof Parzyszek   MachineRegisterInfo &MRI = MF->getRegInfo();
389c715a5d2SKrzysztof Parzyszek   SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
390c715a5d2SKrzysztof Parzyszek 
391c3e698e2SKazu Hirata   for (MachineInstr &PI : B.phis()) {
392c715a5d2SKrzysztof Parzyszek     MachineOperand &DefOp = PI.getOperand(0);
393c715a5d2SKrzysztof Parzyszek     assert(DefOp.getSubReg() == 0);
394c715a5d2SKrzysztof Parzyszek     auto *RC = MRI.getRegClass(DefOp.getReg());
395c715a5d2SKrzysztof Parzyszek 
396c715a5d2SKrzysztof Parzyszek     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
397c715a5d2SKrzysztof Parzyszek       MachineOperand &RegOp = PI.getOperand(i);
398c715a5d2SKrzysztof Parzyszek       if (RegOp.getSubReg() == 0)
399c715a5d2SKrzysztof Parzyszek         continue;
400c715a5d2SKrzysztof Parzyszek 
401c715a5d2SKrzysztof Parzyszek       // If the operand uses a subregister, replace it with a new register
402c715a5d2SKrzysztof Parzyszek       // without subregisters, and generate a copy to the new register.
4030c476111SDaniel Sanders       Register NewReg = MRI.createVirtualRegister(RC);
404c715a5d2SKrzysztof Parzyszek       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
405c715a5d2SKrzysztof Parzyszek       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
406c715a5d2SKrzysztof Parzyszek       const DebugLoc &DL = PredB.findDebugLoc(At);
407c715a5d2SKrzysztof Parzyszek       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
408c715a5d2SKrzysztof Parzyszek                     .addReg(RegOp.getReg(), getRegState(RegOp),
409c715a5d2SKrzysztof Parzyszek                             RegOp.getSubReg());
410c715a5d2SKrzysztof Parzyszek       Slots.insertMachineInstrInMaps(*Copy);
411c715a5d2SKrzysztof Parzyszek       RegOp.setReg(NewReg);
412c715a5d2SKrzysztof Parzyszek       RegOp.setSubReg(0);
413c715a5d2SKrzysztof Parzyszek     }
414c715a5d2SKrzysztof Parzyszek   }
415c715a5d2SKrzysztof Parzyszek }
416c715a5d2SKrzysztof Parzyszek 
417254f889dSBrendon Cahoon /// The SMS algorithm consists of the following main steps:
418254f889dSBrendon Cahoon /// 1. Computation and analysis of the dependence graph.
419254f889dSBrendon Cahoon /// 2. Ordering of the nodes (instructions).
420254f889dSBrendon Cahoon /// 3. Attempt to Schedule the loop.
421254f889dSBrendon Cahoon bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
422254f889dSBrendon Cahoon   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
423254f889dSBrendon Cahoon 
42459d99731SBrendon Cahoon   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
425dcb77643SDavid Penry                         II_setByPragma, LI.LoopPipelinerInfo.get());
426254f889dSBrendon Cahoon 
427254f889dSBrendon Cahoon   MachineBasicBlock *MBB = L.getHeader();
428254f889dSBrendon Cahoon   // The kernel should not include any terminator instructions.  These
429254f889dSBrendon Cahoon   // will be added back later.
430254f889dSBrendon Cahoon   SMS.startBlock(MBB);
431254f889dSBrendon Cahoon 
432254f889dSBrendon Cahoon   // Compute the number of 'real' instructions in the basic block by
433254f889dSBrendon Cahoon   // ignoring terminators.
434254f889dSBrendon Cahoon   unsigned size = MBB->size();
435254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
436254f889dSBrendon Cahoon                                    E = MBB->instr_end();
437254f889dSBrendon Cahoon        I != E; ++I, --size)
438254f889dSBrendon Cahoon     ;
439254f889dSBrendon Cahoon 
440254f889dSBrendon Cahoon   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
441254f889dSBrendon Cahoon   SMS.schedule();
442254f889dSBrendon Cahoon   SMS.exitRegion();
443254f889dSBrendon Cahoon 
444254f889dSBrendon Cahoon   SMS.finishBlock();
445254f889dSBrendon Cahoon   return SMS.hasNewSchedule();
446254f889dSBrendon Cahoon }
447254f889dSBrendon Cahoon 
4482ce38b3fSdfukalov void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
4492ce38b3fSdfukalov   AU.addRequired<AAResultsWrapperPass>();
4502ce38b3fSdfukalov   AU.addPreserved<AAResultsWrapperPass>();
4512ce38b3fSdfukalov   AU.addRequired<MachineLoopInfo>();
4522ce38b3fSdfukalov   AU.addRequired<MachineDominatorTree>();
4532ce38b3fSdfukalov   AU.addRequired<LiveIntervals>();
4542ce38b3fSdfukalov   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
4552ce38b3fSdfukalov   MachineFunctionPass::getAnalysisUsage(AU);
4562ce38b3fSdfukalov }
4572ce38b3fSdfukalov 
45859d99731SBrendon Cahoon void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
45959d99731SBrendon Cahoon   if (II_setByPragma > 0)
46059d99731SBrendon Cahoon     MII = II_setByPragma;
46159d99731SBrendon Cahoon   else
46259d99731SBrendon Cahoon     MII = std::max(ResMII, RecMII);
46359d99731SBrendon Cahoon }
46459d99731SBrendon Cahoon 
46559d99731SBrendon Cahoon void SwingSchedulerDAG::setMAX_II() {
46659d99731SBrendon Cahoon   if (II_setByPragma > 0)
46759d99731SBrendon Cahoon     MAX_II = II_setByPragma;
46859d99731SBrendon Cahoon   else
46959d99731SBrendon Cahoon     MAX_II = MII + 10;
47059d99731SBrendon Cahoon }
47159d99731SBrendon Cahoon 
472254f889dSBrendon Cahoon /// We override the schedule function in ScheduleDAGInstrs to implement the
473254f889dSBrendon Cahoon /// scheduling part of the Swing Modulo Scheduling algorithm.
474254f889dSBrendon Cahoon void SwingSchedulerDAG::schedule() {
475254f889dSBrendon Cahoon   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
476254f889dSBrendon Cahoon   buildSchedGraph(AA);
477254f889dSBrendon Cahoon   addLoopCarriedDependences(AA);
478254f889dSBrendon Cahoon   updatePhiDependences();
479254f889dSBrendon Cahoon   Topo.InitDAGTopologicalSorting();
480254f889dSBrendon Cahoon   changeDependences();
48162ac69d4SSumanth Gundapaneni   postprocessDAG();
482726e12cfSMatthias Braun   LLVM_DEBUG(dump());
483254f889dSBrendon Cahoon 
484254f889dSBrendon Cahoon   NodeSetType NodeSets;
485254f889dSBrendon Cahoon   findCircuits(NodeSets);
4864b8bcf00SRoorda, Jan-Willem   NodeSetType Circuits = NodeSets;
487254f889dSBrendon Cahoon 
488254f889dSBrendon Cahoon   // Calculate the MII.
489254f889dSBrendon Cahoon   unsigned ResMII = calculateResMII();
490254f889dSBrendon Cahoon   unsigned RecMII = calculateRecMII(NodeSets);
491254f889dSBrendon Cahoon 
492254f889dSBrendon Cahoon   fuseRecs(NodeSets);
493254f889dSBrendon Cahoon 
494254f889dSBrendon Cahoon   // This flag is used for testing and can cause correctness problems.
495254f889dSBrendon Cahoon   if (SwpIgnoreRecMII)
496254f889dSBrendon Cahoon     RecMII = 0;
497254f889dSBrendon Cahoon 
49859d99731SBrendon Cahoon   setMII(ResMII, RecMII);
49959d99731SBrendon Cahoon   setMAX_II();
50059d99731SBrendon Cahoon 
50159d99731SBrendon Cahoon   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
50259d99731SBrendon Cahoon                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
503254f889dSBrendon Cahoon 
504254f889dSBrendon Cahoon   // Can't schedule a loop without a valid MII.
50518e7bf5cSJinsong Ji   if (MII == 0) {
50680b78a47SJinsong Ji     LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
50718e7bf5cSJinsong Ji     NumFailZeroMII++;
50880b78a47SJinsong Ji     Pass.ORE->emit([&]() {
50980b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
51080b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
51180b78a47SJinsong Ji              << "Invalid Minimal Initiation Interval: 0";
51280b78a47SJinsong Ji     });
513254f889dSBrendon Cahoon     return;
51418e7bf5cSJinsong Ji   }
515254f889dSBrendon Cahoon 
516254f889dSBrendon Cahoon   // Don't pipeline large loops.
51718e7bf5cSJinsong Ji   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
51818e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
51918e7bf5cSJinsong Ji                       << ", we don't pipleline large loops\n");
52018e7bf5cSJinsong Ji     NumFailLargeMaxMII++;
52180b78a47SJinsong Ji     Pass.ORE->emit([&]() {
52280b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
52380b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
52480b78a47SJinsong Ji              << "Minimal Initiation Interval too large: "
52580b78a47SJinsong Ji              << ore::NV("MII", (int)MII) << " > "
52680b78a47SJinsong Ji              << ore::NV("SwpMaxMii", SwpMaxMii) << "."
52780b78a47SJinsong Ji              << "Refer to -pipeliner-max-mii.";
52880b78a47SJinsong Ji     });
529254f889dSBrendon Cahoon     return;
53018e7bf5cSJinsong Ji   }
531254f889dSBrendon Cahoon 
532254f889dSBrendon Cahoon   computeNodeFunctions(NodeSets);
533254f889dSBrendon Cahoon 
534254f889dSBrendon Cahoon   registerPressureFilter(NodeSets);
535254f889dSBrendon Cahoon 
536254f889dSBrendon Cahoon   colocateNodeSets(NodeSets);
537254f889dSBrendon Cahoon 
538254f889dSBrendon Cahoon   checkNodeSets(NodeSets);
539254f889dSBrendon Cahoon 
540d34e60caSNicola Zaghen   LLVM_DEBUG({
541254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
542254f889dSBrendon Cahoon       dbgs() << "  Rec NodeSet ";
543254f889dSBrendon Cahoon       I.dump();
544254f889dSBrendon Cahoon     }
545254f889dSBrendon Cahoon   });
546254f889dSBrendon Cahoon 
547efd94c56SFangrui Song   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
548254f889dSBrendon Cahoon 
549254f889dSBrendon Cahoon   groupRemainingNodes(NodeSets);
550254f889dSBrendon Cahoon 
551254f889dSBrendon Cahoon   removeDuplicateNodes(NodeSets);
552254f889dSBrendon Cahoon 
553d34e60caSNicola Zaghen   LLVM_DEBUG({
554254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
555254f889dSBrendon Cahoon       dbgs() << "  NodeSet ";
556254f889dSBrendon Cahoon       I.dump();
557254f889dSBrendon Cahoon     }
558254f889dSBrendon Cahoon   });
559254f889dSBrendon Cahoon 
560254f889dSBrendon Cahoon   computeNodeOrder(NodeSets);
561254f889dSBrendon Cahoon 
5624b8bcf00SRoorda, Jan-Willem   // check for node order issues
5634b8bcf00SRoorda, Jan-Willem   checkValidNodeOrder(Circuits);
5644b8bcf00SRoorda, Jan-Willem 
565254f889dSBrendon Cahoon   SMSchedule Schedule(Pass.MF);
566254f889dSBrendon Cahoon   Scheduled = schedulePipeline(Schedule);
567254f889dSBrendon Cahoon 
56818e7bf5cSJinsong Ji   if (!Scheduled){
56918e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
57018e7bf5cSJinsong Ji     NumFailNoSchedule++;
57180b78a47SJinsong Ji     Pass.ORE->emit([&]() {
57280b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
57380b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
57480b78a47SJinsong Ji              << "Unable to find schedule";
57580b78a47SJinsong Ji     });
576254f889dSBrendon Cahoon     return;
57718e7bf5cSJinsong Ji   }
578254f889dSBrendon Cahoon 
579254f889dSBrendon Cahoon   unsigned numStages = Schedule.getMaxStageCount();
580254f889dSBrendon Cahoon   // No need to generate pipeline if there are no overlapped iterations.
58118e7bf5cSJinsong Ji   if (numStages == 0) {
58280b78a47SJinsong Ji     LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
58318e7bf5cSJinsong Ji     NumFailZeroStage++;
58480b78a47SJinsong Ji     Pass.ORE->emit([&]() {
58580b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
58680b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
58780b78a47SJinsong Ji              << "No need to pipeline - no overlapped iterations in schedule.";
58880b78a47SJinsong Ji     });
589254f889dSBrendon Cahoon     return;
59018e7bf5cSJinsong Ji   }
591254f889dSBrendon Cahoon   // Check that the maximum stage count is less than user-defined limit.
59218e7bf5cSJinsong Ji   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
59318e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
59418e7bf5cSJinsong Ji                       << " : too many stages, abort\n");
59518e7bf5cSJinsong Ji     NumFailLargeMaxStage++;
59680b78a47SJinsong Ji     Pass.ORE->emit([&]() {
59780b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
59880b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
59980b78a47SJinsong Ji              << "Too many stages in schedule: "
60080b78a47SJinsong Ji              << ore::NV("numStages", (int)numStages) << " > "
60180b78a47SJinsong Ji              << ore::NV("SwpMaxStages", SwpMaxStages)
60280b78a47SJinsong Ji              << ". Refer to -pipeliner-max-stages.";
60380b78a47SJinsong Ji     });
604254f889dSBrendon Cahoon     return;
60518e7bf5cSJinsong Ji   }
606254f889dSBrendon Cahoon 
60780b78a47SJinsong Ji   Pass.ORE->emit([&]() {
60880b78a47SJinsong Ji     return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
60980b78a47SJinsong Ji                                      Loop.getHeader())
61080b78a47SJinsong Ji            << "Pipelined succesfully!";
61180b78a47SJinsong Ji   });
61280b78a47SJinsong Ji 
613790a779fSJames Molloy   // Generate the schedule as a ModuloSchedule.
614790a779fSJames Molloy   DenseMap<MachineInstr *, int> Cycles, Stages;
615790a779fSJames Molloy   std::vector<MachineInstr *> OrderedInsts;
616790a779fSJames Molloy   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
617790a779fSJames Molloy        ++Cycle) {
618790a779fSJames Molloy     for (SUnit *SU : Schedule.getInstructions(Cycle)) {
619790a779fSJames Molloy       OrderedInsts.push_back(SU->getInstr());
620790a779fSJames Molloy       Cycles[SU->getInstr()] = Cycle;
621790a779fSJames Molloy       Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
622790a779fSJames Molloy     }
623790a779fSJames Molloy   }
624790a779fSJames Molloy   DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
625790a779fSJames Molloy   for (auto &KV : NewMIs) {
626790a779fSJames Molloy     Cycles[KV.first] = Cycles[KV.second];
627790a779fSJames Molloy     Stages[KV.first] = Stages[KV.second];
628790a779fSJames Molloy     NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
629790a779fSJames Molloy   }
630790a779fSJames Molloy 
631790a779fSJames Molloy   ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
632790a779fSJames Molloy                     std::move(Stages));
63393549957SJames Molloy   if (EmitTestAnnotations) {
63493549957SJames Molloy     assert(NewInstrChanges.empty() &&
63593549957SJames Molloy            "Cannot serialize a schedule with InstrChanges!");
63693549957SJames Molloy     ModuloScheduleTestAnnotater MSTI(MF, MS);
63793549957SJames Molloy     MSTI.annotate();
63893549957SJames Molloy     return;
63993549957SJames Molloy   }
640fef9f590SJames Molloy   // The experimental code generator can't work if there are InstChanges.
641fef9f590SJames Molloy   if (ExperimentalCodeGen && NewInstrChanges.empty()) {
642fef9f590SJames Molloy     PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
6439026518eSJames Molloy     MSE.expand();
644fef9f590SJames Molloy   } else {
645790a779fSJames Molloy     ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
646790a779fSJames Molloy     MSE.expand();
647fef9f590SJames Molloy     MSE.cleanup();
648fef9f590SJames Molloy   }
649254f889dSBrendon Cahoon   ++NumPipelined;
650254f889dSBrendon Cahoon }
651254f889dSBrendon Cahoon 
652254f889dSBrendon Cahoon /// Clean up after the software pipeliner runs.
653254f889dSBrendon Cahoon void SwingSchedulerDAG::finishBlock() {
654790a779fSJames Molloy   for (auto &KV : NewMIs)
655b0127424SMircea Trofin     MF.deleteMachineInstr(KV.second);
656254f889dSBrendon Cahoon   NewMIs.clear();
657254f889dSBrendon Cahoon 
658254f889dSBrendon Cahoon   // Call the superclass.
659254f889dSBrendon Cahoon   ScheduleDAGInstrs::finishBlock();
660254f889dSBrendon Cahoon }
661254f889dSBrendon Cahoon 
662254f889dSBrendon Cahoon /// Return the register values for  the operands of a Phi instruction.
663254f889dSBrendon Cahoon /// This function assume the instruction is a Phi.
664254f889dSBrendon Cahoon static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
665254f889dSBrendon Cahoon                        unsigned &InitVal, unsigned &LoopVal) {
666254f889dSBrendon Cahoon   assert(Phi.isPHI() && "Expecting a Phi.");
667254f889dSBrendon Cahoon 
668254f889dSBrendon Cahoon   InitVal = 0;
669254f889dSBrendon Cahoon   LoopVal = 0;
670254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
671254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() != Loop)
672254f889dSBrendon Cahoon       InitVal = Phi.getOperand(i).getReg();
673fbfb19b1SSimon Pilgrim     else
674254f889dSBrendon Cahoon       LoopVal = Phi.getOperand(i).getReg();
675254f889dSBrendon Cahoon 
676254f889dSBrendon Cahoon   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
677254f889dSBrendon Cahoon }
678254f889dSBrendon Cahoon 
6798f976ba0SHiroshi Inoue /// Return the Phi register value that comes the loop block.
680254f889dSBrendon Cahoon static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
681254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
682254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
683254f889dSBrendon Cahoon       return Phi.getOperand(i).getReg();
684254f889dSBrendon Cahoon   return 0;
685254f889dSBrendon Cahoon }
686254f889dSBrendon Cahoon 
687254f889dSBrendon Cahoon /// Return true if SUb can be reached from SUa following the chain edges.
688254f889dSBrendon Cahoon static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
689254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
690254f889dSBrendon Cahoon   SmallVector<SUnit *, 8> Worklist;
691254f889dSBrendon Cahoon   Worklist.push_back(SUa);
692254f889dSBrendon Cahoon   while (!Worklist.empty()) {
693254f889dSBrendon Cahoon     const SUnit *SU = Worklist.pop_back_val();
694254f889dSBrendon Cahoon     for (auto &SI : SU->Succs) {
695254f889dSBrendon Cahoon       SUnit *SuccSU = SI.getSUnit();
696254f889dSBrendon Cahoon       if (SI.getKind() == SDep::Order) {
697254f889dSBrendon Cahoon         if (Visited.count(SuccSU))
698254f889dSBrendon Cahoon           continue;
699254f889dSBrendon Cahoon         if (SuccSU == SUb)
700254f889dSBrendon Cahoon           return true;
701254f889dSBrendon Cahoon         Worklist.push_back(SuccSU);
702254f889dSBrendon Cahoon         Visited.insert(SuccSU);
703254f889dSBrendon Cahoon       }
704254f889dSBrendon Cahoon     }
705254f889dSBrendon Cahoon   }
706254f889dSBrendon Cahoon   return false;
707254f889dSBrendon Cahoon }
708254f889dSBrendon Cahoon 
709254f889dSBrendon Cahoon /// Return true if the instruction causes a chain between memory
710254f889dSBrendon Cahoon /// references before and after it.
711254f889dSBrendon Cahoon static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
7126c5d5ce5SUlrich Weigand   return MI.isCall() || MI.mayRaiseFPException() ||
7136c5d5ce5SUlrich Weigand          MI.hasUnmodeledSideEffects() ||
714254f889dSBrendon Cahoon          (MI.hasOrderedMemoryRef() &&
715d98cf00cSJustin Lebar           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
716254f889dSBrendon Cahoon }
717254f889dSBrendon Cahoon 
718254f889dSBrendon Cahoon /// Return the underlying objects for the memory references of an instruction.
719254f889dSBrendon Cahoon /// This function calls the code in ValueTracking, but first checks that the
720254f889dSBrendon Cahoon /// instruction has a memory operand.
72171e8c6f2SBjorn Pettersson static void getUnderlyingObjects(const MachineInstr *MI,
722b0eb40caSVitaly Buka                                  SmallVectorImpl<const Value *> &Objs) {
723254f889dSBrendon Cahoon   if (!MI->hasOneMemOperand())
724254f889dSBrendon Cahoon     return;
725254f889dSBrendon Cahoon   MachineMemOperand *MM = *MI->memoperands_begin();
726254f889dSBrendon Cahoon   if (!MM->getValue())
727254f889dSBrendon Cahoon     return;
728b0eb40caSVitaly Buka   getUnderlyingObjects(MM->getValue(), Objs);
72971e8c6f2SBjorn Pettersson   for (const Value *V : Objs) {
7309f041b18SKrzysztof Parzyszek     if (!isIdentifiedObject(V)) {
7319f041b18SKrzysztof Parzyszek       Objs.clear();
7329f041b18SKrzysztof Parzyszek       return;
7339f041b18SKrzysztof Parzyszek     }
7349f041b18SKrzysztof Parzyszek     Objs.push_back(V);
7359f041b18SKrzysztof Parzyszek   }
736254f889dSBrendon Cahoon }
737254f889dSBrendon Cahoon 
738254f889dSBrendon Cahoon /// Add a chain edge between a load and store if the store can be an
739254f889dSBrendon Cahoon /// alias of the load on a subsequent iteration, i.e., a loop carried
740254f889dSBrendon Cahoon /// dependence. This code is very similar to the code in ScheduleDAGInstrs
741254f889dSBrendon Cahoon /// but that code doesn't create loop carried dependences.
742254f889dSBrendon Cahoon void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
74371e8c6f2SBjorn Pettersson   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
7449f041b18SKrzysztof Parzyszek   Value *UnknownValue =
7459f041b18SKrzysztof Parzyszek     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
746254f889dSBrendon Cahoon   for (auto &SU : SUnits) {
747254f889dSBrendon Cahoon     MachineInstr &MI = *SU.getInstr();
748254f889dSBrendon Cahoon     if (isDependenceBarrier(MI, AA))
749254f889dSBrendon Cahoon       PendingLoads.clear();
750254f889dSBrendon Cahoon     else if (MI.mayLoad()) {
75171e8c6f2SBjorn Pettersson       SmallVector<const Value *, 4> Objs;
752b0eb40caSVitaly Buka       ::getUnderlyingObjects(&MI, Objs);
7539f041b18SKrzysztof Parzyszek       if (Objs.empty())
7549f041b18SKrzysztof Parzyszek         Objs.push_back(UnknownValue);
755254f889dSBrendon Cahoon       for (auto V : Objs) {
756254f889dSBrendon Cahoon         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
757254f889dSBrendon Cahoon         SUs.push_back(&SU);
758254f889dSBrendon Cahoon       }
759254f889dSBrendon Cahoon     } else if (MI.mayStore()) {
76071e8c6f2SBjorn Pettersson       SmallVector<const Value *, 4> Objs;
761b0eb40caSVitaly Buka       ::getUnderlyingObjects(&MI, Objs);
7629f041b18SKrzysztof Parzyszek       if (Objs.empty())
7639f041b18SKrzysztof Parzyszek         Objs.push_back(UnknownValue);
764254f889dSBrendon Cahoon       for (auto V : Objs) {
76571e8c6f2SBjorn Pettersson         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
766254f889dSBrendon Cahoon             PendingLoads.find(V);
767254f889dSBrendon Cahoon         if (I == PendingLoads.end())
768254f889dSBrendon Cahoon           continue;
769254f889dSBrendon Cahoon         for (auto Load : I->second) {
770254f889dSBrendon Cahoon           if (isSuccOrder(Load, &SU))
771254f889dSBrendon Cahoon             continue;
772254f889dSBrendon Cahoon           MachineInstr &LdMI = *Load->getInstr();
773254f889dSBrendon Cahoon           // First, perform the cheaper check that compares the base register.
774254f889dSBrendon Cahoon           // If they are the same and the load offset is less than the store
775254f889dSBrendon Cahoon           // offset, then mark the dependence as loop carried potentially.
776238c9d63SBjorn Pettersson           const MachineOperand *BaseOp1, *BaseOp2;
777254f889dSBrendon Cahoon           int64_t Offset1, Offset2;
7788fbc9258SSander de Smalen           bool Offset1IsScalable, Offset2IsScalable;
7798fbc9258SSander de Smalen           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
7808fbc9258SSander de Smalen                                            Offset1IsScalable, TRI) &&
7818fbc9258SSander de Smalen               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
7828fbc9258SSander de Smalen                                            Offset2IsScalable, TRI)) {
783d7eebd6dSFrancis Visoiu Mistrih             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
7848fbc9258SSander de Smalen                 Offset1IsScalable == Offset2IsScalable &&
785d7eebd6dSFrancis Visoiu Mistrih                 (int)Offset1 < (int)Offset2) {
786f5524f04SChangpeng Fang               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
787254f889dSBrendon Cahoon                      "What happened to the chain edge?");
788c715a5d2SKrzysztof Parzyszek               SDep Dep(Load, SDep::Barrier);
789c715a5d2SKrzysztof Parzyszek               Dep.setLatency(1);
790c715a5d2SKrzysztof Parzyszek               SU.addPred(Dep);
791254f889dSBrendon Cahoon               continue;
792254f889dSBrendon Cahoon             }
7939f041b18SKrzysztof Parzyszek           }
794254f889dSBrendon Cahoon           // Second, the more expensive check that uses alias analysis on the
795254f889dSBrendon Cahoon           // base registers. If they alias, and the load offset is less than
796254f889dSBrendon Cahoon           // the store offset, the mark the dependence as loop carried.
797254f889dSBrendon Cahoon           if (!AA) {
798c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
799c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
800c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
801254f889dSBrendon Cahoon             continue;
802254f889dSBrendon Cahoon           }
803254f889dSBrendon Cahoon           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
804254f889dSBrendon Cahoon           MachineMemOperand *MMO2 = *MI.memoperands_begin();
805254f889dSBrendon Cahoon           if (!MMO1->getValue() || !MMO2->getValue()) {
806c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
807c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
808c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
809254f889dSBrendon Cahoon             continue;
810254f889dSBrendon Cahoon           }
811254f889dSBrendon Cahoon           if (MMO1->getValue() == MMO2->getValue() &&
812254f889dSBrendon Cahoon               MMO1->getOffset() <= MMO2->getOffset()) {
813c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
814c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
815c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
816254f889dSBrendon Cahoon             continue;
817254f889dSBrendon Cahoon           }
818d0660797Sdfukalov           if (!AA->isNoAlias(
8194df8efceSNikita Popov                   MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
820d0660797Sdfukalov                   MemoryLocation::getAfter(MMO2->getValue(),
821d0660797Sdfukalov                                            MMO2->getAAInfo()))) {
822c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
823c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
824c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
825c715a5d2SKrzysztof Parzyszek           }
826254f889dSBrendon Cahoon         }
827254f889dSBrendon Cahoon       }
828254f889dSBrendon Cahoon     }
829254f889dSBrendon Cahoon   }
830254f889dSBrendon Cahoon }
831254f889dSBrendon Cahoon 
832254f889dSBrendon Cahoon /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
833254f889dSBrendon Cahoon /// processes dependences for PHIs. This function adds true dependences
834254f889dSBrendon Cahoon /// from a PHI to a use, and a loop carried dependence from the use to the
835254f889dSBrendon Cahoon /// PHI. The loop carried dependence is represented as an anti dependence
836254f889dSBrendon Cahoon /// edge. This function also removes chain dependences between unrelated
837254f889dSBrendon Cahoon /// PHIs.
838254f889dSBrendon Cahoon void SwingSchedulerDAG::updatePhiDependences() {
839254f889dSBrendon Cahoon   SmallVector<SDep, 4> RemoveDeps;
840254f889dSBrendon Cahoon   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
841254f889dSBrendon Cahoon 
842254f889dSBrendon Cahoon   // Iterate over each DAG node.
843254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
844254f889dSBrendon Cahoon     RemoveDeps.clear();
845254f889dSBrendon Cahoon     // Set to true if the instruction has an operand defined by a Phi.
846254f889dSBrendon Cahoon     unsigned HasPhiUse = 0;
847254f889dSBrendon Cahoon     unsigned HasPhiDef = 0;
848254f889dSBrendon Cahoon     MachineInstr *MI = I.getInstr();
849254f889dSBrendon Cahoon     // Iterate over each operand, and we process the definitions.
850254f889dSBrendon Cahoon     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
851254f889dSBrendon Cahoon                                     MOE = MI->operands_end();
852254f889dSBrendon Cahoon          MOI != MOE; ++MOI) {
853254f889dSBrendon Cahoon       if (!MOI->isReg())
854254f889dSBrendon Cahoon         continue;
8550c476111SDaniel Sanders       Register Reg = MOI->getReg();
856254f889dSBrendon Cahoon       if (MOI->isDef()) {
857254f889dSBrendon Cahoon         // If the register is used by a Phi, then create an anti dependence.
858254f889dSBrendon Cahoon         for (MachineRegisterInfo::use_instr_iterator
859254f889dSBrendon Cahoon                  UI = MRI.use_instr_begin(Reg),
860254f889dSBrendon Cahoon                  UE = MRI.use_instr_end();
861254f889dSBrendon Cahoon              UI != UE; ++UI) {
862254f889dSBrendon Cahoon           MachineInstr *UseMI = &*UI;
863254f889dSBrendon Cahoon           SUnit *SU = getSUnit(UseMI);
864cdc71612SEugene Zelenko           if (SU != nullptr && UseMI->isPHI()) {
865254f889dSBrendon Cahoon             if (!MI->isPHI()) {
866254f889dSBrendon Cahoon               SDep Dep(SU, SDep::Anti, Reg);
867c715a5d2SKrzysztof Parzyszek               Dep.setLatency(1);
868254f889dSBrendon Cahoon               I.addPred(Dep);
869254f889dSBrendon Cahoon             } else {
870254f889dSBrendon Cahoon               HasPhiDef = Reg;
871254f889dSBrendon Cahoon               // Add a chain edge to a dependent Phi that isn't an existing
872254f889dSBrendon Cahoon               // predecessor.
873254f889dSBrendon Cahoon               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
874254f889dSBrendon Cahoon                 I.addPred(SDep(SU, SDep::Barrier));
875254f889dSBrendon Cahoon             }
876254f889dSBrendon Cahoon           }
877254f889dSBrendon Cahoon         }
878254f889dSBrendon Cahoon       } else if (MOI->isUse()) {
879254f889dSBrendon Cahoon         // If the register is defined by a Phi, then create a true dependence.
880254f889dSBrendon Cahoon         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
881cdc71612SEugene Zelenko         if (DefMI == nullptr)
882254f889dSBrendon Cahoon           continue;
883254f889dSBrendon Cahoon         SUnit *SU = getSUnit(DefMI);
884cdc71612SEugene Zelenko         if (SU != nullptr && DefMI->isPHI()) {
885254f889dSBrendon Cahoon           if (!MI->isPHI()) {
886254f889dSBrendon Cahoon             SDep Dep(SU, SDep::Data, Reg);
887254f889dSBrendon Cahoon             Dep.setLatency(0);
888c819ef96SFraser Cormack             ST.adjustSchedDependency(SU, 0, &I, MI->getOperandNo(MOI), Dep);
889254f889dSBrendon Cahoon             I.addPred(Dep);
890254f889dSBrendon Cahoon           } else {
891254f889dSBrendon Cahoon             HasPhiUse = Reg;
892254f889dSBrendon Cahoon             // Add a chain edge to a dependent Phi that isn't an existing
893254f889dSBrendon Cahoon             // predecessor.
894254f889dSBrendon Cahoon             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
895254f889dSBrendon Cahoon               I.addPred(SDep(SU, SDep::Barrier));
896254f889dSBrendon Cahoon           }
897254f889dSBrendon Cahoon         }
898254f889dSBrendon Cahoon       }
899254f889dSBrendon Cahoon     }
900254f889dSBrendon Cahoon     // Remove order dependences from an unrelated Phi.
901254f889dSBrendon Cahoon     if (!SwpPruneDeps)
902254f889dSBrendon Cahoon       continue;
903254f889dSBrendon Cahoon     for (auto &PI : I.Preds) {
904254f889dSBrendon Cahoon       MachineInstr *PMI = PI.getSUnit()->getInstr();
905254f889dSBrendon Cahoon       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
906254f889dSBrendon Cahoon         if (I.getInstr()->isPHI()) {
907254f889dSBrendon Cahoon           if (PMI->getOperand(0).getReg() == HasPhiUse)
908254f889dSBrendon Cahoon             continue;
909254f889dSBrendon Cahoon           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
910254f889dSBrendon Cahoon             continue;
911254f889dSBrendon Cahoon         }
912254f889dSBrendon Cahoon         RemoveDeps.push_back(PI);
913254f889dSBrendon Cahoon       }
914254f889dSBrendon Cahoon     }
915254f889dSBrendon Cahoon     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
916254f889dSBrendon Cahoon       I.removePred(RemoveDeps[i]);
917254f889dSBrendon Cahoon   }
918254f889dSBrendon Cahoon }
919254f889dSBrendon Cahoon 
920254f889dSBrendon Cahoon /// Iterate over each DAG node and see if we can change any dependences
921254f889dSBrendon Cahoon /// in order to reduce the recurrence MII.
922254f889dSBrendon Cahoon void SwingSchedulerDAG::changeDependences() {
923254f889dSBrendon Cahoon   // See if an instruction can use a value from the previous iteration.
924254f889dSBrendon Cahoon   // If so, we update the base and offset of the instruction and change
925254f889dSBrendon Cahoon   // the dependences.
926254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
927254f889dSBrendon Cahoon     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
928254f889dSBrendon Cahoon     int64_t NewOffset = 0;
929254f889dSBrendon Cahoon     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
930254f889dSBrendon Cahoon                                NewOffset))
931254f889dSBrendon Cahoon       continue;
932254f889dSBrendon Cahoon 
933254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defines the original base.
9340c476111SDaniel Sanders     Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
935254f889dSBrendon Cahoon     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
936254f889dSBrendon Cahoon     if (!DefMI)
937254f889dSBrendon Cahoon       continue;
938254f889dSBrendon Cahoon     SUnit *DefSU = getSUnit(DefMI);
939254f889dSBrendon Cahoon     if (!DefSU)
940254f889dSBrendon Cahoon       continue;
941254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defins the new base.
942254f889dSBrendon Cahoon     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
943254f889dSBrendon Cahoon     if (!LastMI)
944254f889dSBrendon Cahoon       continue;
945254f889dSBrendon Cahoon     SUnit *LastSU = getSUnit(LastMI);
946254f889dSBrendon Cahoon     if (!LastSU)
947254f889dSBrendon Cahoon       continue;
948254f889dSBrendon Cahoon 
949254f889dSBrendon Cahoon     if (Topo.IsReachable(&I, LastSU))
950254f889dSBrendon Cahoon       continue;
951254f889dSBrendon Cahoon 
952254f889dSBrendon Cahoon     // Remove the dependence. The value now depends on a prior iteration.
953254f889dSBrendon Cahoon     SmallVector<SDep, 4> Deps;
9543279943aSKazu Hirata     for (const SDep &P : I.Preds)
9553279943aSKazu Hirata       if (P.getSUnit() == DefSU)
9563279943aSKazu Hirata         Deps.push_back(P);
957254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
958254f889dSBrendon Cahoon       Topo.RemovePred(&I, Deps[i].getSUnit());
959254f889dSBrendon Cahoon       I.removePred(Deps[i]);
960254f889dSBrendon Cahoon     }
961254f889dSBrendon Cahoon     // Remove the chain dependence between the instructions.
962254f889dSBrendon Cahoon     Deps.clear();
963254f889dSBrendon Cahoon     for (auto &P : LastSU->Preds)
964254f889dSBrendon Cahoon       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
965254f889dSBrendon Cahoon         Deps.push_back(P);
966254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
967254f889dSBrendon Cahoon       Topo.RemovePred(LastSU, Deps[i].getSUnit());
968254f889dSBrendon Cahoon       LastSU->removePred(Deps[i]);
969254f889dSBrendon Cahoon     }
970254f889dSBrendon Cahoon 
971254f889dSBrendon Cahoon     // Add a dependence between the new instruction and the instruction
972254f889dSBrendon Cahoon     // that defines the new base.
973254f889dSBrendon Cahoon     SDep Dep(&I, SDep::Anti, NewBase);
9748916e438SSumanth Gundapaneni     Topo.AddPred(LastSU, &I);
975254f889dSBrendon Cahoon     LastSU->addPred(Dep);
976254f889dSBrendon Cahoon 
977254f889dSBrendon Cahoon     // Remember the base and offset information so that we can update the
978254f889dSBrendon Cahoon     // instruction during code generation.
979254f889dSBrendon Cahoon     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
980254f889dSBrendon Cahoon   }
981254f889dSBrendon Cahoon }
982254f889dSBrendon Cahoon 
983254f889dSBrendon Cahoon namespace {
984cdc71612SEugene Zelenko 
985254f889dSBrendon Cahoon // FuncUnitSorter - Comparison operator used to sort instructions by
986254f889dSBrendon Cahoon // the number of functional unit choices.
987254f889dSBrendon Cahoon struct FuncUnitSorter {
988254f889dSBrendon Cahoon   const InstrItineraryData *InstrItins;
989f6cb3bcbSJinsong Ji   const MCSubtargetInfo *STI;
990c3f36accSBevin Hansson   DenseMap<InstrStage::FuncUnits, unsigned> Resources;
991254f889dSBrendon Cahoon 
992f6cb3bcbSJinsong Ji   FuncUnitSorter(const TargetSubtargetInfo &TSI)
993f6cb3bcbSJinsong Ji       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
99432a40564SEugene Zelenko 
995254f889dSBrendon Cahoon   // Compute the number of functional unit alternatives needed
996254f889dSBrendon Cahoon   // at each stage, and take the minimum value. We prioritize the
997254f889dSBrendon Cahoon   // instructions by the least number of choices first.
998c3f36accSBevin Hansson   unsigned minFuncUnits(const MachineInstr *Inst,
999c3f36accSBevin Hansson                         InstrStage::FuncUnits &F) const {
1000f6cb3bcbSJinsong Ji     unsigned SchedClass = Inst->getDesc().getSchedClass();
1001254f889dSBrendon Cahoon     unsigned min = UINT_MAX;
1002f6cb3bcbSJinsong Ji     if (InstrItins && !InstrItins->isEmpty()) {
1003f6cb3bcbSJinsong Ji       for (const InstrStage &IS :
1004f6cb3bcbSJinsong Ji            make_range(InstrItins->beginStage(SchedClass),
1005f6cb3bcbSJinsong Ji                       InstrItins->endStage(SchedClass))) {
1006c3f36accSBevin Hansson         InstrStage::FuncUnits funcUnits = IS.getUnits();
1007254f889dSBrendon Cahoon         unsigned numAlternatives = countPopulation(funcUnits);
1008254f889dSBrendon Cahoon         if (numAlternatives < min) {
1009254f889dSBrendon Cahoon           min = numAlternatives;
1010254f889dSBrendon Cahoon           F = funcUnits;
1011254f889dSBrendon Cahoon         }
1012254f889dSBrendon Cahoon       }
1013254f889dSBrendon Cahoon       return min;
1014254f889dSBrendon Cahoon     }
1015f6cb3bcbSJinsong Ji     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1016f6cb3bcbSJinsong Ji       const MCSchedClassDesc *SCDesc =
1017f6cb3bcbSJinsong Ji           STI->getSchedModel().getSchedClassDesc(SchedClass);
1018f6cb3bcbSJinsong Ji       if (!SCDesc->isValid())
1019f6cb3bcbSJinsong Ji         // No valid Schedule Class Desc for schedClass, should be
1020f6cb3bcbSJinsong Ji         // Pseudo/PostRAPseudo
1021f6cb3bcbSJinsong Ji         return min;
1022f6cb3bcbSJinsong Ji 
1023f6cb3bcbSJinsong Ji       for (const MCWriteProcResEntry &PRE :
1024f6cb3bcbSJinsong Ji            make_range(STI->getWriteProcResBegin(SCDesc),
1025f6cb3bcbSJinsong Ji                       STI->getWriteProcResEnd(SCDesc))) {
1026f6cb3bcbSJinsong Ji         if (!PRE.Cycles)
1027f6cb3bcbSJinsong Ji           continue;
1028f6cb3bcbSJinsong Ji         const MCProcResourceDesc *ProcResource =
1029f6cb3bcbSJinsong Ji             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
1030f6cb3bcbSJinsong Ji         unsigned NumUnits = ProcResource->NumUnits;
1031f6cb3bcbSJinsong Ji         if (NumUnits < min) {
1032f6cb3bcbSJinsong Ji           min = NumUnits;
1033f6cb3bcbSJinsong Ji           F = PRE.ProcResourceIdx;
1034f6cb3bcbSJinsong Ji         }
1035f6cb3bcbSJinsong Ji       }
1036f6cb3bcbSJinsong Ji       return min;
1037f6cb3bcbSJinsong Ji     }
1038f6cb3bcbSJinsong Ji     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1039f6cb3bcbSJinsong Ji   }
1040254f889dSBrendon Cahoon 
1041254f889dSBrendon Cahoon   // Compute the critical resources needed by the instruction. This
1042254f889dSBrendon Cahoon   // function records the functional units needed by instructions that
1043254f889dSBrendon Cahoon   // must use only one functional unit. We use this as a tie breaker
1044254f889dSBrendon Cahoon   // for computing the resource MII. The instrutions that require
1045254f889dSBrendon Cahoon   // the same, highly used, functional unit have high priority.
1046254f889dSBrendon Cahoon   void calcCriticalResources(MachineInstr &MI) {
1047254f889dSBrendon Cahoon     unsigned SchedClass = MI.getDesc().getSchedClass();
1048f6cb3bcbSJinsong Ji     if (InstrItins && !InstrItins->isEmpty()) {
1049f6cb3bcbSJinsong Ji       for (const InstrStage &IS :
1050f6cb3bcbSJinsong Ji            make_range(InstrItins->beginStage(SchedClass),
1051f6cb3bcbSJinsong Ji                       InstrItins->endStage(SchedClass))) {
1052c3f36accSBevin Hansson         InstrStage::FuncUnits FuncUnits = IS.getUnits();
1053254f889dSBrendon Cahoon         if (countPopulation(FuncUnits) == 1)
1054254f889dSBrendon Cahoon           Resources[FuncUnits]++;
1055254f889dSBrendon Cahoon       }
1056f6cb3bcbSJinsong Ji       return;
1057f6cb3bcbSJinsong Ji     }
1058f6cb3bcbSJinsong Ji     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1059f6cb3bcbSJinsong Ji       const MCSchedClassDesc *SCDesc =
1060f6cb3bcbSJinsong Ji           STI->getSchedModel().getSchedClassDesc(SchedClass);
1061f6cb3bcbSJinsong Ji       if (!SCDesc->isValid())
1062f6cb3bcbSJinsong Ji         // No valid Schedule Class Desc for schedClass, should be
1063f6cb3bcbSJinsong Ji         // Pseudo/PostRAPseudo
1064f6cb3bcbSJinsong Ji         return;
1065f6cb3bcbSJinsong Ji 
1066f6cb3bcbSJinsong Ji       for (const MCWriteProcResEntry &PRE :
1067f6cb3bcbSJinsong Ji            make_range(STI->getWriteProcResBegin(SCDesc),
1068f6cb3bcbSJinsong Ji                       STI->getWriteProcResEnd(SCDesc))) {
1069f6cb3bcbSJinsong Ji         if (!PRE.Cycles)
1070f6cb3bcbSJinsong Ji           continue;
1071f6cb3bcbSJinsong Ji         Resources[PRE.ProcResourceIdx]++;
1072f6cb3bcbSJinsong Ji       }
1073f6cb3bcbSJinsong Ji       return;
1074f6cb3bcbSJinsong Ji     }
1075f6cb3bcbSJinsong Ji     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1076254f889dSBrendon Cahoon   }
1077254f889dSBrendon Cahoon 
1078254f889dSBrendon Cahoon   /// Return true if IS1 has less priority than IS2.
1079254f889dSBrendon Cahoon   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1080c3f36accSBevin Hansson     InstrStage::FuncUnits F1 = 0, F2 = 0;
1081254f889dSBrendon Cahoon     unsigned MFUs1 = minFuncUnits(IS1, F1);
1082254f889dSBrendon Cahoon     unsigned MFUs2 = minFuncUnits(IS2, F2);
10836349ce5cSJinsong Ji     if (MFUs1 == MFUs2)
1084254f889dSBrendon Cahoon       return Resources.lookup(F1) < Resources.lookup(F2);
1085254f889dSBrendon Cahoon     return MFUs1 > MFUs2;
1086254f889dSBrendon Cahoon   }
1087254f889dSBrendon Cahoon };
1088cdc71612SEugene Zelenko 
1089cdc71612SEugene Zelenko } // end anonymous namespace
1090254f889dSBrendon Cahoon 
1091254f889dSBrendon Cahoon /// Calculate the resource constrained minimum initiation interval for the
1092254f889dSBrendon Cahoon /// specified loop. We use the DFA to model the resources needed for
1093254f889dSBrendon Cahoon /// each instruction, and we ignore dependences. A different DFA is created
1094254f889dSBrendon Cahoon /// for each cycle that is required. When adding a new instruction, we attempt
1095254f889dSBrendon Cahoon /// to add it to each existing DFA, until a legal space is found. If the
1096254f889dSBrendon Cahoon /// instruction cannot be reserved in an existing DFA, we create a new one.
1097254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateResMII() {
1098f6cb3bcbSJinsong Ji 
109918e7bf5cSJinsong Ji   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1100f6cb3bcbSJinsong Ji   SmallVector<ResourceManager*, 8> Resources;
1101254f889dSBrendon Cahoon   MachineBasicBlock *MBB = Loop.getHeader();
1102f6cb3bcbSJinsong Ji   Resources.push_back(new ResourceManager(&MF.getSubtarget()));
1103254f889dSBrendon Cahoon 
1104254f889dSBrendon Cahoon   // Sort the instructions by the number of available choices for scheduling,
1105254f889dSBrendon Cahoon   // least to most. Use the number of critical resources as the tie breaker.
1106f6cb3bcbSJinsong Ji   FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
1107c4a8928bSKazu Hirata   for (MachineInstr &MI :
1108c4a8928bSKazu Hirata        llvm::make_range(MBB->getFirstNonPHI(), MBB->getFirstTerminator()))
1109c4a8928bSKazu Hirata     FUS.calcCriticalResources(MI);
1110254f889dSBrendon Cahoon   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
1111254f889dSBrendon Cahoon       FuncUnitOrder(FUS);
1112254f889dSBrendon Cahoon 
1113c4a8928bSKazu Hirata   for (MachineInstr &MI :
1114c4a8928bSKazu Hirata        llvm::make_range(MBB->getFirstNonPHI(), MBB->getFirstTerminator()))
1115c4a8928bSKazu Hirata     FuncUnitOrder.push(&MI);
1116254f889dSBrendon Cahoon 
1117254f889dSBrendon Cahoon   while (!FuncUnitOrder.empty()) {
1118254f889dSBrendon Cahoon     MachineInstr *MI = FuncUnitOrder.top();
1119254f889dSBrendon Cahoon     FuncUnitOrder.pop();
1120254f889dSBrendon Cahoon     if (TII->isZeroCost(MI->getOpcode()))
1121254f889dSBrendon Cahoon       continue;
1122254f889dSBrendon Cahoon     // Attempt to reserve the instruction in an existing DFA. At least one
1123254f889dSBrendon Cahoon     // DFA is needed for each cycle.
1124254f889dSBrendon Cahoon     unsigned NumCycles = getSUnit(MI)->Latency;
1125254f889dSBrendon Cahoon     unsigned ReservedCycles = 0;
1126f6cb3bcbSJinsong Ji     SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1127f6cb3bcbSJinsong Ji     SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
112818e7bf5cSJinsong Ji     LLVM_DEBUG({
112918e7bf5cSJinsong Ji       dbgs() << "Trying to reserve resource for " << NumCycles
113018e7bf5cSJinsong Ji              << " cycles for \n";
113118e7bf5cSJinsong Ji       MI->dump();
113218e7bf5cSJinsong Ji     });
1133254f889dSBrendon Cahoon     for (unsigned C = 0; C < NumCycles; ++C)
1134254f889dSBrendon Cahoon       while (RI != RE) {
1135fee855b5SJinsong Ji         if ((*RI)->canReserveResources(*MI)) {
1136fee855b5SJinsong Ji           (*RI)->reserveResources(*MI);
1137254f889dSBrendon Cahoon           ++ReservedCycles;
1138254f889dSBrendon Cahoon           break;
1139254f889dSBrendon Cahoon         }
1140fee855b5SJinsong Ji         RI++;
1141254f889dSBrendon Cahoon       }
114218e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
114318e7bf5cSJinsong Ji                       << ", NumCycles:" << NumCycles << "\n");
1144254f889dSBrendon Cahoon     // Add new DFAs, if needed, to reserve resources.
1145254f889dSBrendon Cahoon     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1146ba43840bSJinsong Ji       LLVM_DEBUG(if (SwpDebugResource) dbgs()
1147ba43840bSJinsong Ji                  << "NewResource created to reserve resources"
114818e7bf5cSJinsong Ji                  << "\n");
1149f6cb3bcbSJinsong Ji       ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
1150254f889dSBrendon Cahoon       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1151254f889dSBrendon Cahoon       NewResource->reserveResources(*MI);
1152254f889dSBrendon Cahoon       Resources.push_back(NewResource);
1153254f889dSBrendon Cahoon     }
1154254f889dSBrendon Cahoon   }
1155254f889dSBrendon Cahoon   int Resmii = Resources.size();
115680b78a47SJinsong Ji   LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
1157254f889dSBrendon Cahoon   // Delete the memory for each of the DFAs that were created earlier.
1158f6cb3bcbSJinsong Ji   for (ResourceManager *RI : Resources) {
1159f6cb3bcbSJinsong Ji     ResourceManager *D = RI;
1160254f889dSBrendon Cahoon     delete D;
1161254f889dSBrendon Cahoon   }
1162254f889dSBrendon Cahoon   Resources.clear();
1163254f889dSBrendon Cahoon   return Resmii;
1164254f889dSBrendon Cahoon }
1165254f889dSBrendon Cahoon 
1166254f889dSBrendon Cahoon /// Calculate the recurrence-constrainted minimum initiation interval.
1167254f889dSBrendon Cahoon /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1168254f889dSBrendon Cahoon /// for each circuit. The II needs to satisfy the inequality
1169254f889dSBrendon Cahoon /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1170c73b6d6bSHiroshi Inoue /// II that satisfies the inequality, and the RecMII is the maximum
1171254f889dSBrendon Cahoon /// of those values.
1172254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1173254f889dSBrendon Cahoon   unsigned RecMII = 0;
1174254f889dSBrendon Cahoon 
1175254f889dSBrendon Cahoon   for (NodeSet &Nodes : NodeSets) {
117632a40564SEugene Zelenko     if (Nodes.empty())
1177254f889dSBrendon Cahoon       continue;
1178254f889dSBrendon Cahoon 
1179a2122044SKrzysztof Parzyszek     unsigned Delay = Nodes.getLatency();
1180254f889dSBrendon Cahoon     unsigned Distance = 1;
1181254f889dSBrendon Cahoon 
1182254f889dSBrendon Cahoon     // ii = ceil(delay / distance)
1183254f889dSBrendon Cahoon     unsigned CurMII = (Delay + Distance - 1) / Distance;
1184254f889dSBrendon Cahoon     Nodes.setRecMII(CurMII);
1185254f889dSBrendon Cahoon     if (CurMII > RecMII)
1186254f889dSBrendon Cahoon       RecMII = CurMII;
1187254f889dSBrendon Cahoon   }
1188254f889dSBrendon Cahoon 
1189254f889dSBrendon Cahoon   return RecMII;
1190254f889dSBrendon Cahoon }
1191254f889dSBrendon Cahoon 
1192254f889dSBrendon Cahoon /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1193254f889dSBrendon Cahoon /// but we do this to find the circuits, and then change them back.
1194254f889dSBrendon Cahoon static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1195254f889dSBrendon Cahoon   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1196ca2f5389SKazu Hirata   for (SUnit &SU : SUnits) {
1197ca2f5389SKazu Hirata     for (SDep &Pred : SU.Preds)
1198ca2f5389SKazu Hirata       if (Pred.getKind() == SDep::Anti)
1199ca2f5389SKazu Hirata         DepsAdded.push_back(std::make_pair(&SU, Pred));
1200254f889dSBrendon Cahoon   }
12013279943aSKazu Hirata   for (std::pair<SUnit *, SDep> &P : DepsAdded) {
1202254f889dSBrendon Cahoon     // Remove this anti dependency and add one in the reverse direction.
12033279943aSKazu Hirata     SUnit *SU = P.first;
12043279943aSKazu Hirata     SDep &D = P.second;
1205254f889dSBrendon Cahoon     SUnit *TargetSU = D.getSUnit();
1206254f889dSBrendon Cahoon     unsigned Reg = D.getReg();
1207254f889dSBrendon Cahoon     unsigned Lat = D.getLatency();
1208254f889dSBrendon Cahoon     SU->removePred(D);
1209254f889dSBrendon Cahoon     SDep Dep(SU, SDep::Anti, Reg);
1210254f889dSBrendon Cahoon     Dep.setLatency(Lat);
1211254f889dSBrendon Cahoon     TargetSU->addPred(Dep);
1212254f889dSBrendon Cahoon   }
1213254f889dSBrendon Cahoon }
1214254f889dSBrendon Cahoon 
1215254f889dSBrendon Cahoon /// Create the adjacency structure of the nodes in the graph.
1216254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1217254f889dSBrendon Cahoon     SwingSchedulerDAG *DAG) {
1218254f889dSBrendon Cahoon   BitVector Added(SUnits.size());
12198e1363dfSKrzysztof Parzyszek   DenseMap<int, int> OutputDeps;
1220254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1221254f889dSBrendon Cahoon     Added.reset();
1222254f889dSBrendon Cahoon     // Add any successor to the adjacency matrix and exclude duplicates.
1223254f889dSBrendon Cahoon     for (auto &SI : SUnits[i].Succs) {
12248e1363dfSKrzysztof Parzyszek       // Only create a back-edge on the first and last nodes of a dependence
12258e1363dfSKrzysztof Parzyszek       // chain. This records any chains and adds them later.
12268e1363dfSKrzysztof Parzyszek       if (SI.getKind() == SDep::Output) {
12278e1363dfSKrzysztof Parzyszek         int N = SI.getSUnit()->NodeNum;
12288e1363dfSKrzysztof Parzyszek         int BackEdge = i;
12298e1363dfSKrzysztof Parzyszek         auto Dep = OutputDeps.find(BackEdge);
12308e1363dfSKrzysztof Parzyszek         if (Dep != OutputDeps.end()) {
12318e1363dfSKrzysztof Parzyszek           BackEdge = Dep->second;
12328e1363dfSKrzysztof Parzyszek           OutputDeps.erase(Dep);
12338e1363dfSKrzysztof Parzyszek         }
12348e1363dfSKrzysztof Parzyszek         OutputDeps[N] = BackEdge;
12358e1363dfSKrzysztof Parzyszek       }
1236ada0f511SSumanth Gundapaneni       // Do not process a boundary node, an artificial node.
1237ada0f511SSumanth Gundapaneni       // A back-edge is processed only if it goes to a Phi.
1238ada0f511SSumanth Gundapaneni       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1239254f889dSBrendon Cahoon           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1240254f889dSBrendon Cahoon         continue;
1241254f889dSBrendon Cahoon       int N = SI.getSUnit()->NodeNum;
1242254f889dSBrendon Cahoon       if (!Added.test(N)) {
1243254f889dSBrendon Cahoon         AdjK[i].push_back(N);
1244254f889dSBrendon Cahoon         Added.set(N);
1245254f889dSBrendon Cahoon       }
1246254f889dSBrendon Cahoon     }
1247254f889dSBrendon Cahoon     // A chain edge between a store and a load is treated as a back-edge in the
1248254f889dSBrendon Cahoon     // adjacency matrix.
1249254f889dSBrendon Cahoon     for (auto &PI : SUnits[i].Preds) {
1250254f889dSBrendon Cahoon       if (!SUnits[i].getInstr()->mayStore() ||
12518e1363dfSKrzysztof Parzyszek           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1252254f889dSBrendon Cahoon         continue;
1253254f889dSBrendon Cahoon       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1254254f889dSBrendon Cahoon         int N = PI.getSUnit()->NodeNum;
1255254f889dSBrendon Cahoon         if (!Added.test(N)) {
1256254f889dSBrendon Cahoon           AdjK[i].push_back(N);
1257254f889dSBrendon Cahoon           Added.set(N);
1258254f889dSBrendon Cahoon         }
1259254f889dSBrendon Cahoon       }
1260254f889dSBrendon Cahoon     }
1261254f889dSBrendon Cahoon   }
1262dad8c6a1SHiroshi Inoue   // Add back-edges in the adjacency matrix for the output dependences.
12638e1363dfSKrzysztof Parzyszek   for (auto &OD : OutputDeps)
12648e1363dfSKrzysztof Parzyszek     if (!Added.test(OD.second)) {
12658e1363dfSKrzysztof Parzyszek       AdjK[OD.first].push_back(OD.second);
12668e1363dfSKrzysztof Parzyszek       Added.set(OD.second);
12678e1363dfSKrzysztof Parzyszek     }
1268254f889dSBrendon Cahoon }
1269254f889dSBrendon Cahoon 
1270254f889dSBrendon Cahoon /// Identify an elementary circuit in the dependence graph starting at the
1271254f889dSBrendon Cahoon /// specified node.
1272254f889dSBrendon Cahoon bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1273254f889dSBrendon Cahoon                                           bool HasBackedge) {
1274254f889dSBrendon Cahoon   SUnit *SV = &SUnits[V];
1275254f889dSBrendon Cahoon   bool F = false;
1276254f889dSBrendon Cahoon   Stack.insert(SV);
1277254f889dSBrendon Cahoon   Blocked.set(V);
1278254f889dSBrendon Cahoon 
1279254f889dSBrendon Cahoon   for (auto W : AdjK[V]) {
1280254f889dSBrendon Cahoon     if (NumPaths > MaxPaths)
1281254f889dSBrendon Cahoon       break;
1282254f889dSBrendon Cahoon     if (W < S)
1283254f889dSBrendon Cahoon       continue;
1284254f889dSBrendon Cahoon     if (W == S) {
1285254f889dSBrendon Cahoon       if (!HasBackedge)
1286254f889dSBrendon Cahoon         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1287254f889dSBrendon Cahoon       F = true;
1288254f889dSBrendon Cahoon       ++NumPaths;
1289254f889dSBrendon Cahoon       break;
1290254f889dSBrendon Cahoon     } else if (!Blocked.test(W)) {
129177418a37SSumanth Gundapaneni       if (circuit(W, S, NodeSets,
129277418a37SSumanth Gundapaneni                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1293254f889dSBrendon Cahoon         F = true;
1294254f889dSBrendon Cahoon     }
1295254f889dSBrendon Cahoon   }
1296254f889dSBrendon Cahoon 
1297254f889dSBrendon Cahoon   if (F)
1298254f889dSBrendon Cahoon     unblock(V);
1299254f889dSBrendon Cahoon   else {
1300254f889dSBrendon Cahoon     for (auto W : AdjK[V]) {
1301254f889dSBrendon Cahoon       if (W < S)
1302254f889dSBrendon Cahoon         continue;
1303254f889dSBrendon Cahoon       if (B[W].count(SV) == 0)
1304254f889dSBrendon Cahoon         B[W].insert(SV);
1305254f889dSBrendon Cahoon     }
1306254f889dSBrendon Cahoon   }
1307254f889dSBrendon Cahoon   Stack.pop_back();
1308254f889dSBrendon Cahoon   return F;
1309254f889dSBrendon Cahoon }
1310254f889dSBrendon Cahoon 
1311254f889dSBrendon Cahoon /// Unblock a node in the circuit finding algorithm.
1312254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::unblock(int U) {
1313254f889dSBrendon Cahoon   Blocked.reset(U);
1314254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 4> &BU = B[U];
1315254f889dSBrendon Cahoon   while (!BU.empty()) {
1316254f889dSBrendon Cahoon     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1317254f889dSBrendon Cahoon     assert(SI != BU.end() && "Invalid B set.");
1318254f889dSBrendon Cahoon     SUnit *W = *SI;
1319254f889dSBrendon Cahoon     BU.erase(W);
1320254f889dSBrendon Cahoon     if (Blocked.test(W->NodeNum))
1321254f889dSBrendon Cahoon       unblock(W->NodeNum);
1322254f889dSBrendon Cahoon   }
1323254f889dSBrendon Cahoon }
1324254f889dSBrendon Cahoon 
1325254f889dSBrendon Cahoon /// Identify all the elementary circuits in the dependence graph using
1326254f889dSBrendon Cahoon /// Johnson's circuit algorithm.
1327254f889dSBrendon Cahoon void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1328254f889dSBrendon Cahoon   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1329254f889dSBrendon Cahoon   // but we do this to find the circuits, and then change them back.
1330254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1331254f889dSBrendon Cahoon 
133277418a37SSumanth Gundapaneni   Circuits Cir(SUnits, Topo);
1333254f889dSBrendon Cahoon   // Create the adjacency structure.
1334254f889dSBrendon Cahoon   Cir.createAdjacencyStructure(this);
1335254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1336254f889dSBrendon Cahoon     Cir.reset();
1337254f889dSBrendon Cahoon     Cir.circuit(i, i, NodeSets);
1338254f889dSBrendon Cahoon   }
1339254f889dSBrendon Cahoon 
1340254f889dSBrendon Cahoon   // Change the dependences back so that we've created a DAG again.
1341254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1342254f889dSBrendon Cahoon }
1343254f889dSBrendon Cahoon 
134462ac69d4SSumanth Gundapaneni // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
134562ac69d4SSumanth Gundapaneni // is loop-carried to the USE in next iteration. This will help pipeliner avoid
134662ac69d4SSumanth Gundapaneni // additional copies that are needed across iterations. An artificial dependence
134762ac69d4SSumanth Gundapaneni // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
134862ac69d4SSumanth Gundapaneni 
134962ac69d4SSumanth Gundapaneni // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
135062ac69d4SSumanth Gundapaneni // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
135162ac69d4SSumanth Gundapaneni // PHI-------True-Dep------> USEOfPhi
135262ac69d4SSumanth Gundapaneni 
135362ac69d4SSumanth Gundapaneni // The mutation creates
135462ac69d4SSumanth Gundapaneni // USEOfPHI -------Artificial-Dep---> SRCOfCopy
135562ac69d4SSumanth Gundapaneni 
135662ac69d4SSumanth Gundapaneni // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
135762ac69d4SSumanth Gundapaneni // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
135862ac69d4SSumanth Gundapaneni // late  to avoid additional copies across iterations. The possible scheduling
135962ac69d4SSumanth Gundapaneni // order would be
136062ac69d4SSumanth Gundapaneni // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
136162ac69d4SSumanth Gundapaneni 
136262ac69d4SSumanth Gundapaneni void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
136362ac69d4SSumanth Gundapaneni   for (SUnit &SU : DAG->SUnits) {
136462ac69d4SSumanth Gundapaneni     // Find the COPY/REG_SEQUENCE instruction.
136562ac69d4SSumanth Gundapaneni     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
136662ac69d4SSumanth Gundapaneni       continue;
136762ac69d4SSumanth Gundapaneni 
136862ac69d4SSumanth Gundapaneni     // Record the loop carried PHIs.
136962ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 4> PHISUs;
137062ac69d4SSumanth Gundapaneni     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
137162ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 4> SrcSUs;
137262ac69d4SSumanth Gundapaneni 
137362ac69d4SSumanth Gundapaneni     for (auto &Dep : SU.Preds) {
137462ac69d4SSumanth Gundapaneni       SUnit *TmpSU = Dep.getSUnit();
137562ac69d4SSumanth Gundapaneni       MachineInstr *TmpMI = TmpSU->getInstr();
137662ac69d4SSumanth Gundapaneni       SDep::Kind DepKind = Dep.getKind();
137762ac69d4SSumanth Gundapaneni       // Save the loop carried PHI.
137862ac69d4SSumanth Gundapaneni       if (DepKind == SDep::Anti && TmpMI->isPHI())
137962ac69d4SSumanth Gundapaneni         PHISUs.push_back(TmpSU);
138062ac69d4SSumanth Gundapaneni       // Save the source of COPY/REG_SEQUENCE.
138162ac69d4SSumanth Gundapaneni       // If the source has no pre-decessors, we will end up creating cycles.
138262ac69d4SSumanth Gundapaneni       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
138362ac69d4SSumanth Gundapaneni         SrcSUs.push_back(TmpSU);
138462ac69d4SSumanth Gundapaneni     }
138562ac69d4SSumanth Gundapaneni 
138662ac69d4SSumanth Gundapaneni     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
138762ac69d4SSumanth Gundapaneni       continue;
138862ac69d4SSumanth Gundapaneni 
138962ac69d4SSumanth Gundapaneni     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
139062ac69d4SSumanth Gundapaneni     // SUnit to the container.
139162ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 8> UseSUs;
13927c7e368aSSumanth Gundapaneni     // Do not use iterator based loop here as we are updating the container.
13937c7e368aSSumanth Gundapaneni     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
13947c7e368aSSumanth Gundapaneni       for (auto &Dep : PHISUs[Index]->Succs) {
139562ac69d4SSumanth Gundapaneni         if (Dep.getKind() != SDep::Data)
139662ac69d4SSumanth Gundapaneni           continue;
139762ac69d4SSumanth Gundapaneni 
139862ac69d4SSumanth Gundapaneni         SUnit *TmpSU = Dep.getSUnit();
139962ac69d4SSumanth Gundapaneni         MachineInstr *TmpMI = TmpSU->getInstr();
140062ac69d4SSumanth Gundapaneni         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
140162ac69d4SSumanth Gundapaneni           PHISUs.push_back(TmpSU);
140262ac69d4SSumanth Gundapaneni           continue;
140362ac69d4SSumanth Gundapaneni         }
140462ac69d4SSumanth Gundapaneni         UseSUs.push_back(TmpSU);
140562ac69d4SSumanth Gundapaneni       }
140662ac69d4SSumanth Gundapaneni     }
140762ac69d4SSumanth Gundapaneni 
140862ac69d4SSumanth Gundapaneni     if (UseSUs.size() == 0)
140962ac69d4SSumanth Gundapaneni       continue;
141062ac69d4SSumanth Gundapaneni 
141162ac69d4SSumanth Gundapaneni     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
141262ac69d4SSumanth Gundapaneni     // Add the artificial dependencies if it does not form a cycle.
141362ac69d4SSumanth Gundapaneni     for (auto I : UseSUs) {
141462ac69d4SSumanth Gundapaneni       for (auto Src : SrcSUs) {
141562ac69d4SSumanth Gundapaneni         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
141662ac69d4SSumanth Gundapaneni           Src->addPred(SDep(I, SDep::Artificial));
141762ac69d4SSumanth Gundapaneni           SDAG->Topo.AddPred(Src, I);
141862ac69d4SSumanth Gundapaneni         }
141962ac69d4SSumanth Gundapaneni       }
142062ac69d4SSumanth Gundapaneni     }
142162ac69d4SSumanth Gundapaneni   }
142262ac69d4SSumanth Gundapaneni }
142362ac69d4SSumanth Gundapaneni 
1424254f889dSBrendon Cahoon /// Return true for DAG nodes that we ignore when computing the cost functions.
1425c73b6d6bSHiroshi Inoue /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1426254f889dSBrendon Cahoon /// in the calculation of the ASAP, ALAP, etc functions.
1427254f889dSBrendon Cahoon static bool ignoreDependence(const SDep &D, bool isPred) {
1428dcb77643SDavid Penry   if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
1429254f889dSBrendon Cahoon     return true;
1430254f889dSBrendon Cahoon   return D.getKind() == SDep::Anti && isPred;
1431254f889dSBrendon Cahoon }
1432254f889dSBrendon Cahoon 
1433254f889dSBrendon Cahoon /// Compute several functions need to order the nodes for scheduling.
1434254f889dSBrendon Cahoon ///  ASAP - Earliest time to schedule a node.
1435254f889dSBrendon Cahoon ///  ALAP - Latest time to schedule a node.
1436254f889dSBrendon Cahoon ///  MOV - Mobility function, difference between ALAP and ASAP.
1437254f889dSBrendon Cahoon ///  D - Depth of each node.
1438254f889dSBrendon Cahoon ///  H - Height of each node.
1439254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1440254f889dSBrendon Cahoon   ScheduleInfo.resize(SUnits.size());
1441254f889dSBrendon Cahoon 
1442d34e60caSNicola Zaghen   LLVM_DEBUG({
14433279943aSKazu Hirata     for (int I : Topo) {
14443279943aSKazu Hirata       const SUnit &SU = SUnits[I];
1445726e12cfSMatthias Braun       dumpNode(SU);
1446254f889dSBrendon Cahoon     }
1447254f889dSBrendon Cahoon   });
1448254f889dSBrendon Cahoon 
1449254f889dSBrendon Cahoon   int maxASAP = 0;
14504b8bcf00SRoorda, Jan-Willem   // Compute ASAP and ZeroLatencyDepth.
14513279943aSKazu Hirata   for (int I : Topo) {
1452254f889dSBrendon Cahoon     int asap = 0;
14534b8bcf00SRoorda, Jan-Willem     int zeroLatencyDepth = 0;
14543279943aSKazu Hirata     SUnit *SU = &SUnits[I];
1455fd7d4064SKazu Hirata     for (const SDep &P : SU->Preds) {
1456fd7d4064SKazu Hirata       SUnit *pred = P.getSUnit();
1457fd7d4064SKazu Hirata       if (P.getLatency() == 0)
14584b8bcf00SRoorda, Jan-Willem         zeroLatencyDepth =
14594b8bcf00SRoorda, Jan-Willem             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1460fd7d4064SKazu Hirata       if (ignoreDependence(P, true))
1461254f889dSBrendon Cahoon         continue;
1462fd7d4064SKazu Hirata       asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
1463fd7d4064SKazu Hirata                                   getDistance(pred, SU, P) * MII));
1464254f889dSBrendon Cahoon     }
1465254f889dSBrendon Cahoon     maxASAP = std::max(maxASAP, asap);
14663279943aSKazu Hirata     ScheduleInfo[I].ASAP = asap;
14673279943aSKazu Hirata     ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
1468254f889dSBrendon Cahoon   }
1469254f889dSBrendon Cahoon 
14704b8bcf00SRoorda, Jan-Willem   // Compute ALAP, ZeroLatencyHeight, and MOV.
1471ca2f5389SKazu Hirata   for (int I : llvm::reverse(Topo)) {
1472254f889dSBrendon Cahoon     int alap = maxASAP;
14734b8bcf00SRoorda, Jan-Willem     int zeroLatencyHeight = 0;
1474ca2f5389SKazu Hirata     SUnit *SU = &SUnits[I];
1475ca2f5389SKazu Hirata     for (const SDep &S : SU->Succs) {
1476ca2f5389SKazu Hirata       SUnit *succ = S.getSUnit();
1477dcb77643SDavid Penry       if (succ->isBoundaryNode())
1478dcb77643SDavid Penry         continue;
1479ca2f5389SKazu Hirata       if (S.getLatency() == 0)
14804b8bcf00SRoorda, Jan-Willem         zeroLatencyHeight =
14814b8bcf00SRoorda, Jan-Willem             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1482ca2f5389SKazu Hirata       if (ignoreDependence(S, true))
1483254f889dSBrendon Cahoon         continue;
1484ca2f5389SKazu Hirata       alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
1485ca2f5389SKazu Hirata                                   getDistance(SU, succ, S) * MII));
1486254f889dSBrendon Cahoon     }
1487254f889dSBrendon Cahoon 
1488ca2f5389SKazu Hirata     ScheduleInfo[I].ALAP = alap;
1489ca2f5389SKazu Hirata     ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
1490254f889dSBrendon Cahoon   }
1491254f889dSBrendon Cahoon 
1492254f889dSBrendon Cahoon   // After computing the node functions, compute the summary for each node set.
1493254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets)
1494254f889dSBrendon Cahoon     I.computeNodeSetInfo(this);
1495254f889dSBrendon Cahoon 
1496d34e60caSNicola Zaghen   LLVM_DEBUG({
1497254f889dSBrendon Cahoon     for (unsigned i = 0; i < SUnits.size(); i++) {
1498254f889dSBrendon Cahoon       dbgs() << "\tNode " << i << ":\n";
1499254f889dSBrendon Cahoon       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1500254f889dSBrendon Cahoon       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1501254f889dSBrendon Cahoon       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1502254f889dSBrendon Cahoon       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1503254f889dSBrendon Cahoon       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
15044b8bcf00SRoorda, Jan-Willem       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
15054b8bcf00SRoorda, Jan-Willem       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1506254f889dSBrendon Cahoon     }
1507254f889dSBrendon Cahoon   });
1508254f889dSBrendon Cahoon }
1509254f889dSBrendon Cahoon 
1510254f889dSBrendon Cahoon /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1511254f889dSBrendon Cahoon /// as the predecessors of the elements of NodeOrder that are not also in
1512254f889dSBrendon Cahoon /// NodeOrder.
1513254f889dSBrendon Cahoon static bool pred_L(SetVector<SUnit *> &NodeOrder,
1514254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Preds,
1515254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1516254f889dSBrendon Cahoon   Preds.clear();
1517f240e528SKazu Hirata   for (const SUnit *SU : NodeOrder) {
1518f240e528SKazu Hirata     for (const SDep &Pred : SU->Preds) {
15193279943aSKazu Hirata       if (S && S->count(Pred.getSUnit()) == 0)
1520254f889dSBrendon Cahoon         continue;
15213279943aSKazu Hirata       if (ignoreDependence(Pred, true))
1522254f889dSBrendon Cahoon         continue;
15233279943aSKazu Hirata       if (NodeOrder.count(Pred.getSUnit()) == 0)
15243279943aSKazu Hirata         Preds.insert(Pred.getSUnit());
1525254f889dSBrendon Cahoon     }
1526254f889dSBrendon Cahoon     // Back-edges are predecessors with an anti-dependence.
1527f240e528SKazu Hirata     for (const SDep &Succ : SU->Succs) {
15283279943aSKazu Hirata       if (Succ.getKind() != SDep::Anti)
1529254f889dSBrendon Cahoon         continue;
15303279943aSKazu Hirata       if (S && S->count(Succ.getSUnit()) == 0)
1531254f889dSBrendon Cahoon         continue;
15323279943aSKazu Hirata       if (NodeOrder.count(Succ.getSUnit()) == 0)
15333279943aSKazu Hirata         Preds.insert(Succ.getSUnit());
1534254f889dSBrendon Cahoon     }
1535254f889dSBrendon Cahoon   }
153632a40564SEugene Zelenko   return !Preds.empty();
1537254f889dSBrendon Cahoon }
1538254f889dSBrendon Cahoon 
1539254f889dSBrendon Cahoon /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1540254f889dSBrendon Cahoon /// as the successors of the elements of NodeOrder that are not also in
1541254f889dSBrendon Cahoon /// NodeOrder.
1542254f889dSBrendon Cahoon static bool succ_L(SetVector<SUnit *> &NodeOrder,
1543254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Succs,
1544254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1545254f889dSBrendon Cahoon   Succs.clear();
1546ca2f5389SKazu Hirata   for (const SUnit *SU : NodeOrder) {
1547ca2f5389SKazu Hirata     for (const SDep &Succ : SU->Succs) {
15483279943aSKazu Hirata       if (S && S->count(Succ.getSUnit()) == 0)
1549254f889dSBrendon Cahoon         continue;
15503279943aSKazu Hirata       if (ignoreDependence(Succ, false))
1551254f889dSBrendon Cahoon         continue;
15523279943aSKazu Hirata       if (NodeOrder.count(Succ.getSUnit()) == 0)
15533279943aSKazu Hirata         Succs.insert(Succ.getSUnit());
1554254f889dSBrendon Cahoon     }
1555ca2f5389SKazu Hirata     for (const SDep &Pred : SU->Preds) {
15563279943aSKazu Hirata       if (Pred.getKind() != SDep::Anti)
1557254f889dSBrendon Cahoon         continue;
15583279943aSKazu Hirata       if (S && S->count(Pred.getSUnit()) == 0)
1559254f889dSBrendon Cahoon         continue;
15603279943aSKazu Hirata       if (NodeOrder.count(Pred.getSUnit()) == 0)
15613279943aSKazu Hirata         Succs.insert(Pred.getSUnit());
1562254f889dSBrendon Cahoon     }
1563254f889dSBrendon Cahoon   }
156432a40564SEugene Zelenko   return !Succs.empty();
1565254f889dSBrendon Cahoon }
1566254f889dSBrendon Cahoon 
1567254f889dSBrendon Cahoon /// Return true if there is a path from the specified node to any of the nodes
1568254f889dSBrendon Cahoon /// in DestNodes. Keep track and return the nodes in any path.
1569254f889dSBrendon Cahoon static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1570254f889dSBrendon Cahoon                         SetVector<SUnit *> &DestNodes,
1571254f889dSBrendon Cahoon                         SetVector<SUnit *> &Exclude,
1572254f889dSBrendon Cahoon                         SmallPtrSet<SUnit *, 8> &Visited) {
1573254f889dSBrendon Cahoon   if (Cur->isBoundaryNode())
1574254f889dSBrendon Cahoon     return false;
1575b7c5e0b0SKazu Hirata   if (Exclude.contains(Cur))
1576254f889dSBrendon Cahoon     return false;
1577b7c5e0b0SKazu Hirata   if (DestNodes.contains(Cur))
1578254f889dSBrendon Cahoon     return true;
1579254f889dSBrendon Cahoon   if (!Visited.insert(Cur).second)
1580b7c5e0b0SKazu Hirata     return Path.contains(Cur);
1581254f889dSBrendon Cahoon   bool FoundPath = false;
1582254f889dSBrendon Cahoon   for (auto &SI : Cur->Succs)
1583*68dee839SThomas Preud'homme     if (!ignoreDependence(SI, false))
1584*68dee839SThomas Preud'homme       FoundPath |=
1585*68dee839SThomas Preud'homme           computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1586254f889dSBrendon Cahoon   for (auto &PI : Cur->Preds)
1587254f889dSBrendon Cahoon     if (PI.getKind() == SDep::Anti)
1588254f889dSBrendon Cahoon       FoundPath |=
1589254f889dSBrendon Cahoon           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1590254f889dSBrendon Cahoon   if (FoundPath)
1591254f889dSBrendon Cahoon     Path.insert(Cur);
1592254f889dSBrendon Cahoon   return FoundPath;
1593254f889dSBrendon Cahoon }
1594254f889dSBrendon Cahoon 
1595254f889dSBrendon Cahoon /// Compute the live-out registers for the instructions in a node-set.
1596254f889dSBrendon Cahoon /// The live-out registers are those that are defined in the node-set,
1597254f889dSBrendon Cahoon /// but not used. Except for use operands of Phis.
1598254f889dSBrendon Cahoon static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1599254f889dSBrendon Cahoon                             NodeSet &NS) {
1600254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1601254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
1602254f889dSBrendon Cahoon   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1603254f889dSBrendon Cahoon   SmallSet<unsigned, 4> Uses;
1604254f889dSBrendon Cahoon   for (SUnit *SU : NS) {
1605254f889dSBrendon Cahoon     const MachineInstr *MI = SU->getInstr();
1606254f889dSBrendon Cahoon     if (MI->isPHI())
1607254f889dSBrendon Cahoon       continue;
1608fc371558SMatthias Braun     for (const MachineOperand &MO : MI->operands())
1609fc371558SMatthias Braun       if (MO.isReg() && MO.isUse()) {
16100c476111SDaniel Sanders         Register Reg = MO.getReg();
16112bea69bfSDaniel Sanders         if (Register::isVirtualRegister(Reg))
1612254f889dSBrendon Cahoon           Uses.insert(Reg);
1613254f889dSBrendon Cahoon         else if (MRI.isAllocatable(Reg))
1614c8fcffe7SMircea Trofin           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1615c8fcffe7SMircea Trofin                ++Units)
1616254f889dSBrendon Cahoon             Uses.insert(*Units);
1617254f889dSBrendon Cahoon       }
1618254f889dSBrendon Cahoon   }
1619254f889dSBrendon Cahoon   for (SUnit *SU : NS)
1620fc371558SMatthias Braun     for (const MachineOperand &MO : SU->getInstr()->operands())
1621fc371558SMatthias Braun       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
16220c476111SDaniel Sanders         Register Reg = MO.getReg();
16232bea69bfSDaniel Sanders         if (Register::isVirtualRegister(Reg)) {
1624254f889dSBrendon Cahoon           if (!Uses.count(Reg))
162591b5cf84SKrzysztof Parzyszek             LiveOutRegs.push_back(RegisterMaskPair(Reg,
162691b5cf84SKrzysztof Parzyszek                                                    LaneBitmask::getNone()));
1627254f889dSBrendon Cahoon         } else if (MRI.isAllocatable(Reg)) {
1628c8fcffe7SMircea Trofin           for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
1629c8fcffe7SMircea Trofin                ++Units)
1630254f889dSBrendon Cahoon             if (!Uses.count(*Units))
163191b5cf84SKrzysztof Parzyszek               LiveOutRegs.push_back(RegisterMaskPair(*Units,
163291b5cf84SKrzysztof Parzyszek                                                      LaneBitmask::getNone()));
1633254f889dSBrendon Cahoon         }
1634254f889dSBrendon Cahoon       }
1635254f889dSBrendon Cahoon   RPTracker.addLiveRegs(LiveOutRegs);
1636254f889dSBrendon Cahoon }
1637254f889dSBrendon Cahoon 
1638254f889dSBrendon Cahoon /// A heuristic to filter nodes in recurrent node-sets if the register
1639254f889dSBrendon Cahoon /// pressure of a set is too high.
1640254f889dSBrendon Cahoon void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1641254f889dSBrendon Cahoon   for (auto &NS : NodeSets) {
1642254f889dSBrendon Cahoon     // Skip small node-sets since they won't cause register pressure problems.
1643254f889dSBrendon Cahoon     if (NS.size() <= 2)
1644254f889dSBrendon Cahoon       continue;
1645254f889dSBrendon Cahoon     IntervalPressure RecRegPressure;
1646254f889dSBrendon Cahoon     RegPressureTracker RecRPTracker(RecRegPressure);
1647254f889dSBrendon Cahoon     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1648254f889dSBrendon Cahoon     computeLiveOuts(MF, RecRPTracker, NS);
1649254f889dSBrendon Cahoon     RecRPTracker.closeBottom();
1650254f889dSBrendon Cahoon 
1651254f889dSBrendon Cahoon     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
16520cac726aSFangrui Song     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
1653254f889dSBrendon Cahoon       return A->NodeNum > B->NodeNum;
1654254f889dSBrendon Cahoon     });
1655254f889dSBrendon Cahoon 
1656254f889dSBrendon Cahoon     for (auto &SU : SUnits) {
1657254f889dSBrendon Cahoon       // Since we're computing the register pressure for a subset of the
1658254f889dSBrendon Cahoon       // instructions in a block, we need to set the tracker for each
1659254f889dSBrendon Cahoon       // instruction in the node-set. The tracker is set to the instruction
1660254f889dSBrendon Cahoon       // just after the one we're interested in.
1661254f889dSBrendon Cahoon       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1662254f889dSBrendon Cahoon       RecRPTracker.setPos(std::next(CurInstI));
1663254f889dSBrendon Cahoon 
1664254f889dSBrendon Cahoon       RegPressureDelta RPDelta;
1665254f889dSBrendon Cahoon       ArrayRef<PressureChange> CriticalPSets;
1666254f889dSBrendon Cahoon       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1667254f889dSBrendon Cahoon                                              CriticalPSets,
1668254f889dSBrendon Cahoon                                              RecRegPressure.MaxSetPressure);
1669254f889dSBrendon Cahoon       if (RPDelta.Excess.isValid()) {
1670d34e60caSNicola Zaghen         LLVM_DEBUG(
1671d34e60caSNicola Zaghen             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1672254f889dSBrendon Cahoon                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1673254f889dSBrendon Cahoon                    << ":" << RPDelta.Excess.getUnitInc());
1674254f889dSBrendon Cahoon         NS.setExceedPressure(SU);
1675254f889dSBrendon Cahoon         break;
1676254f889dSBrendon Cahoon       }
1677254f889dSBrendon Cahoon       RecRPTracker.recede();
1678254f889dSBrendon Cahoon     }
1679254f889dSBrendon Cahoon   }
1680254f889dSBrendon Cahoon }
1681254f889dSBrendon Cahoon 
1682254f889dSBrendon Cahoon /// A heuristic to colocate node sets that have the same set of
1683254f889dSBrendon Cahoon /// successors.
1684254f889dSBrendon Cahoon void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1685254f889dSBrendon Cahoon   unsigned Colocate = 0;
1686254f889dSBrendon Cahoon   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1687254f889dSBrendon Cahoon     NodeSet &N1 = NodeSets[i];
1688254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> S1;
1689254f889dSBrendon Cahoon     if (N1.empty() || !succ_L(N1, S1))
1690254f889dSBrendon Cahoon       continue;
1691254f889dSBrendon Cahoon     for (int j = i + 1; j < e; ++j) {
1692254f889dSBrendon Cahoon       NodeSet &N2 = NodeSets[j];
1693254f889dSBrendon Cahoon       if (N1.compareRecMII(N2) != 0)
1694254f889dSBrendon Cahoon         continue;
1695254f889dSBrendon Cahoon       SmallSetVector<SUnit *, 8> S2;
1696254f889dSBrendon Cahoon       if (N2.empty() || !succ_L(N2, S2))
1697254f889dSBrendon Cahoon         continue;
1698d6391209SKazu Hirata       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
1699254f889dSBrendon Cahoon         N1.setColocate(++Colocate);
1700254f889dSBrendon Cahoon         N2.setColocate(Colocate);
1701254f889dSBrendon Cahoon         break;
1702254f889dSBrendon Cahoon       }
1703254f889dSBrendon Cahoon     }
1704254f889dSBrendon Cahoon   }
1705254f889dSBrendon Cahoon }
1706254f889dSBrendon Cahoon 
1707254f889dSBrendon Cahoon /// Check if the existing node-sets are profitable. If not, then ignore the
1708254f889dSBrendon Cahoon /// recurrent node-sets, and attempt to schedule all nodes together. This is
17093ca23341SKrzysztof Parzyszek /// a heuristic. If the MII is large and all the recurrent node-sets are small,
17103ca23341SKrzysztof Parzyszek /// then it's best to try to schedule all instructions together instead of
17113ca23341SKrzysztof Parzyszek /// starting with the recurrent node-sets.
1712254f889dSBrendon Cahoon void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1713254f889dSBrendon Cahoon   // Look for loops with a large MII.
17143ca23341SKrzysztof Parzyszek   if (MII < 17)
1715254f889dSBrendon Cahoon     return;
1716254f889dSBrendon Cahoon   // Check if the node-set contains only a simple add recurrence.
17173ca23341SKrzysztof Parzyszek   for (auto &NS : NodeSets) {
17183ca23341SKrzysztof Parzyszek     if (NS.getRecMII() > 2)
1719254f889dSBrendon Cahoon       return;
17203ca23341SKrzysztof Parzyszek     if (NS.getMaxDepth() > MII)
17213ca23341SKrzysztof Parzyszek       return;
17223ca23341SKrzysztof Parzyszek   }
1723254f889dSBrendon Cahoon   NodeSets.clear();
1724d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1725254f889dSBrendon Cahoon }
1726254f889dSBrendon Cahoon 
1727254f889dSBrendon Cahoon /// Add the nodes that do not belong to a recurrence set into groups
1728449ef2fcSThomas Preud'homme /// based upon connected components.
1729254f889dSBrendon Cahoon void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1730254f889dSBrendon Cahoon   SetVector<SUnit *> NodesAdded;
1731254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
1732254f889dSBrendon Cahoon   // Add the nodes that are on a path between the previous node sets and
1733254f889dSBrendon Cahoon   // the current node set.
1734254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets) {
1735254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
1736254f889dSBrendon Cahoon     // Add the nodes from the current node set to the previous node set.
1737254f889dSBrendon Cahoon     if (succ_L(I, N)) {
1738254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1739254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1740254f889dSBrendon Cahoon         Visited.clear();
1741254f889dSBrendon Cahoon         computePath(NI, Path, NodesAdded, I, Visited);
1742254f889dSBrendon Cahoon       }
174332a40564SEugene Zelenko       if (!Path.empty())
1744254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1745254f889dSBrendon Cahoon     }
1746254f889dSBrendon Cahoon     // Add the nodes from the previous node set to the current node set.
1747254f889dSBrendon Cahoon     N.clear();
1748254f889dSBrendon Cahoon     if (succ_L(NodesAdded, N)) {
1749254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1750254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1751254f889dSBrendon Cahoon         Visited.clear();
1752254f889dSBrendon Cahoon         computePath(NI, Path, I, NodesAdded, Visited);
1753254f889dSBrendon Cahoon       }
175432a40564SEugene Zelenko       if (!Path.empty())
1755254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1756254f889dSBrendon Cahoon     }
1757254f889dSBrendon Cahoon     NodesAdded.insert(I.begin(), I.end());
1758254f889dSBrendon Cahoon   }
1759254f889dSBrendon Cahoon 
1760254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any successor of a node
1761254f889dSBrendon Cahoon   // in a recurrent set.
1762254f889dSBrendon Cahoon   NodeSet NewSet;
1763254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> N;
1764254f889dSBrendon Cahoon   if (succ_L(NodesAdded, N))
1765254f889dSBrendon Cahoon     for (SUnit *I : N)
1766254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
176732a40564SEugene Zelenko   if (!NewSet.empty())
1768254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1769254f889dSBrendon Cahoon 
1770254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any predecessor of a node
1771254f889dSBrendon Cahoon   // in a recurrent set.
1772254f889dSBrendon Cahoon   NewSet.clear();
1773254f889dSBrendon Cahoon   if (pred_L(NodesAdded, N))
1774254f889dSBrendon Cahoon     for (SUnit *I : N)
1775254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
177632a40564SEugene Zelenko   if (!NewSet.empty())
1777254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1778254f889dSBrendon Cahoon 
1779372ffa15SHiroshi Inoue   // Create new nodes sets with the connected nodes any remaining node that
1780254f889dSBrendon Cahoon   // has no predecessor.
17813279943aSKazu Hirata   for (SUnit &SU : SUnits) {
17823279943aSKazu Hirata     if (NodesAdded.count(&SU) == 0) {
1783254f889dSBrendon Cahoon       NewSet.clear();
17843279943aSKazu Hirata       addConnectedNodes(&SU, NewSet, NodesAdded);
178532a40564SEugene Zelenko       if (!NewSet.empty())
1786254f889dSBrendon Cahoon         NodeSets.push_back(NewSet);
1787254f889dSBrendon Cahoon     }
1788254f889dSBrendon Cahoon   }
1789254f889dSBrendon Cahoon }
1790254f889dSBrendon Cahoon 
179131f47b81SAlexey Lapshin /// Add the node to the set, and add all of its connected nodes to the set.
1792254f889dSBrendon Cahoon void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1793254f889dSBrendon Cahoon                                           SetVector<SUnit *> &NodesAdded) {
1794254f889dSBrendon Cahoon   NewSet.insert(SU);
1795254f889dSBrendon Cahoon   NodesAdded.insert(SU);
1796254f889dSBrendon Cahoon   for (auto &SI : SU->Succs) {
1797254f889dSBrendon Cahoon     SUnit *Successor = SI.getSUnit();
1798dcb77643SDavid Penry     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
1799dcb77643SDavid Penry         NodesAdded.count(Successor) == 0)
1800254f889dSBrendon Cahoon       addConnectedNodes(Successor, NewSet, NodesAdded);
1801254f889dSBrendon Cahoon   }
1802254f889dSBrendon Cahoon   for (auto &PI : SU->Preds) {
1803254f889dSBrendon Cahoon     SUnit *Predecessor = PI.getSUnit();
1804254f889dSBrendon Cahoon     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1805254f889dSBrendon Cahoon       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1806254f889dSBrendon Cahoon   }
1807254f889dSBrendon Cahoon }
1808254f889dSBrendon Cahoon 
1809254f889dSBrendon Cahoon /// Return true if Set1 contains elements in Set2. The elements in common
1810254f889dSBrendon Cahoon /// are returned in a different container.
1811254f889dSBrendon Cahoon static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1812254f889dSBrendon Cahoon                         SmallSetVector<SUnit *, 8> &Result) {
1813254f889dSBrendon Cahoon   Result.clear();
1814254f889dSBrendon Cahoon   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1815254f889dSBrendon Cahoon     SUnit *SU = Set1[i];
1816254f889dSBrendon Cahoon     if (Set2.count(SU) != 0)
1817254f889dSBrendon Cahoon       Result.insert(SU);
1818254f889dSBrendon Cahoon   }
1819254f889dSBrendon Cahoon   return !Result.empty();
1820254f889dSBrendon Cahoon }
1821254f889dSBrendon Cahoon 
1822254f889dSBrendon Cahoon /// Merge the recurrence node sets that have the same initial node.
1823254f889dSBrendon Cahoon void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1824254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1825254f889dSBrendon Cahoon        ++I) {
1826254f889dSBrendon Cahoon     NodeSet &NI = *I;
1827254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1828254f889dSBrendon Cahoon       NodeSet &NJ = *J;
1829254f889dSBrendon Cahoon       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1830254f889dSBrendon Cahoon         if (NJ.compareRecMII(NI) > 0)
1831254f889dSBrendon Cahoon           NI.setRecMII(NJ.getRecMII());
18323279943aSKazu Hirata         for (SUnit *SU : *J)
18333279943aSKazu Hirata           I->insert(SU);
1834254f889dSBrendon Cahoon         NodeSets.erase(J);
1835254f889dSBrendon Cahoon         E = NodeSets.end();
1836254f889dSBrendon Cahoon       } else {
1837254f889dSBrendon Cahoon         ++J;
1838254f889dSBrendon Cahoon       }
1839254f889dSBrendon Cahoon     }
1840254f889dSBrendon Cahoon   }
1841254f889dSBrendon Cahoon }
1842254f889dSBrendon Cahoon 
1843254f889dSBrendon Cahoon /// Remove nodes that have been scheduled in previous NodeSets.
1844254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1845254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1846254f889dSBrendon Cahoon        ++I)
1847254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1848254f889dSBrendon Cahoon       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1849254f889dSBrendon Cahoon 
185032a40564SEugene Zelenko       if (J->empty()) {
1851254f889dSBrendon Cahoon         NodeSets.erase(J);
1852254f889dSBrendon Cahoon         E = NodeSets.end();
1853254f889dSBrendon Cahoon       } else {
1854254f889dSBrendon Cahoon         ++J;
1855254f889dSBrendon Cahoon       }
1856254f889dSBrendon Cahoon     }
1857254f889dSBrendon Cahoon }
1858254f889dSBrendon Cahoon 
1859254f889dSBrendon Cahoon /// Compute an ordered list of the dependence graph nodes, which
1860254f889dSBrendon Cahoon /// indicates the order that the nodes will be scheduled.  This is a
1861254f889dSBrendon Cahoon /// two-level algorithm. First, a partial order is created, which
1862254f889dSBrendon Cahoon /// consists of a list of sets ordered from highest to lowest priority.
1863254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1864254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> R;
1865254f889dSBrendon Cahoon   NodeOrder.clear();
1866254f889dSBrendon Cahoon 
1867254f889dSBrendon Cahoon   for (auto &Nodes : NodeSets) {
1868d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1869254f889dSBrendon Cahoon     OrderKind Order;
1870254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
1871d6391209SKazu Hirata     if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
1872254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
1873254f889dSBrendon Cahoon       Order = BottomUp;
1874d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
1875d6391209SKazu Hirata     } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
1876254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
1877254f889dSBrendon Cahoon       Order = TopDown;
1878d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
1879254f889dSBrendon Cahoon     } else if (isIntersect(N, Nodes, R)) {
1880254f889dSBrendon Cahoon       // If some of the successors are in the existing node-set, then use the
1881254f889dSBrendon Cahoon       // top-down ordering.
1882254f889dSBrendon Cahoon       Order = TopDown;
1883d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
1884254f889dSBrendon Cahoon     } else if (NodeSets.size() == 1) {
1885254f889dSBrendon Cahoon       for (auto &N : Nodes)
1886254f889dSBrendon Cahoon         if (N->Succs.size() == 0)
1887254f889dSBrendon Cahoon           R.insert(N);
1888254f889dSBrendon Cahoon       Order = BottomUp;
1889d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
1890254f889dSBrendon Cahoon     } else {
1891254f889dSBrendon Cahoon       // Find the node with the highest ASAP.
1892254f889dSBrendon Cahoon       SUnit *maxASAP = nullptr;
1893254f889dSBrendon Cahoon       for (SUnit *SU : Nodes) {
1894a2122044SKrzysztof Parzyszek         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1895a2122044SKrzysztof Parzyszek             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
1896254f889dSBrendon Cahoon           maxASAP = SU;
1897254f889dSBrendon Cahoon       }
1898254f889dSBrendon Cahoon       R.insert(maxASAP);
1899254f889dSBrendon Cahoon       Order = BottomUp;
1900d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
1901254f889dSBrendon Cahoon     }
1902254f889dSBrendon Cahoon 
1903254f889dSBrendon Cahoon     while (!R.empty()) {
1904254f889dSBrendon Cahoon       if (Order == TopDown) {
1905254f889dSBrendon Cahoon         // Choose the node with the maximum height.  If more than one, choose
1906a2122044SKrzysztof Parzyszek         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
19074b8bcf00SRoorda, Jan-Willem         // choose the node with the lowest MOV.
1908254f889dSBrendon Cahoon         while (!R.empty()) {
1909254f889dSBrendon Cahoon           SUnit *maxHeight = nullptr;
1910254f889dSBrendon Cahoon           for (SUnit *I : R) {
1911cdc71612SEugene Zelenko             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
1912254f889dSBrendon Cahoon               maxHeight = I;
1913254f889dSBrendon Cahoon             else if (getHeight(I) == getHeight(maxHeight) &&
19144b8bcf00SRoorda, Jan-Willem                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
1915254f889dSBrendon Cahoon               maxHeight = I;
19164b8bcf00SRoorda, Jan-Willem             else if (getHeight(I) == getHeight(maxHeight) &&
19174b8bcf00SRoorda, Jan-Willem                      getZeroLatencyHeight(I) ==
19184b8bcf00SRoorda, Jan-Willem                          getZeroLatencyHeight(maxHeight) &&
19194b8bcf00SRoorda, Jan-Willem                      getMOV(I) < getMOV(maxHeight))
1920254f889dSBrendon Cahoon               maxHeight = I;
1921254f889dSBrendon Cahoon           }
1922254f889dSBrendon Cahoon           NodeOrder.insert(maxHeight);
1923d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
1924254f889dSBrendon Cahoon           R.remove(maxHeight);
1925254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Succs) {
1926254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1927254f889dSBrendon Cahoon               continue;
1928b7c5e0b0SKazu Hirata             if (NodeOrder.contains(I.getSUnit()))
1929254f889dSBrendon Cahoon               continue;
1930254f889dSBrendon Cahoon             if (ignoreDependence(I, false))
1931254f889dSBrendon Cahoon               continue;
1932254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1933254f889dSBrendon Cahoon           }
1934254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
1935254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Preds) {
1936254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
1937254f889dSBrendon Cahoon               continue;
1938254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1939254f889dSBrendon Cahoon               continue;
1940b7c5e0b0SKazu Hirata             if (NodeOrder.contains(I.getSUnit()))
1941254f889dSBrendon Cahoon               continue;
1942254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1943254f889dSBrendon Cahoon           }
1944254f889dSBrendon Cahoon         }
1945254f889dSBrendon Cahoon         Order = BottomUp;
1946d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
1947254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
1948254f889dSBrendon Cahoon         if (pred_L(NodeOrder, N, &Nodes))
1949254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
1950254f889dSBrendon Cahoon       } else {
1951254f889dSBrendon Cahoon         // Choose the node with the maximum depth.  If more than one, choose
19524b8bcf00SRoorda, Jan-Willem         // the node with the maximum ZeroLatencyDepth. If still more than one,
19534b8bcf00SRoorda, Jan-Willem         // choose the node with the lowest MOV.
1954254f889dSBrendon Cahoon         while (!R.empty()) {
1955254f889dSBrendon Cahoon           SUnit *maxDepth = nullptr;
1956254f889dSBrendon Cahoon           for (SUnit *I : R) {
1957cdc71612SEugene Zelenko             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
1958254f889dSBrendon Cahoon               maxDepth = I;
1959254f889dSBrendon Cahoon             else if (getDepth(I) == getDepth(maxDepth) &&
19604b8bcf00SRoorda, Jan-Willem                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
1961254f889dSBrendon Cahoon               maxDepth = I;
19624b8bcf00SRoorda, Jan-Willem             else if (getDepth(I) == getDepth(maxDepth) &&
19634b8bcf00SRoorda, Jan-Willem                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
19644b8bcf00SRoorda, Jan-Willem                      getMOV(I) < getMOV(maxDepth))
1965254f889dSBrendon Cahoon               maxDepth = I;
1966254f889dSBrendon Cahoon           }
1967254f889dSBrendon Cahoon           NodeOrder.insert(maxDepth);
1968d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
1969254f889dSBrendon Cahoon           R.remove(maxDepth);
1970254f889dSBrendon Cahoon           if (Nodes.isExceedSU(maxDepth)) {
1971254f889dSBrendon Cahoon             Order = TopDown;
1972254f889dSBrendon Cahoon             R.clear();
1973254f889dSBrendon Cahoon             R.insert(Nodes.getNode(0));
1974254f889dSBrendon Cahoon             break;
1975254f889dSBrendon Cahoon           }
1976254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Preds) {
1977254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1978254f889dSBrendon Cahoon               continue;
1979b7c5e0b0SKazu Hirata             if (NodeOrder.contains(I.getSUnit()))
1980254f889dSBrendon Cahoon               continue;
1981254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1982254f889dSBrendon Cahoon           }
1983254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
1984254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Succs) {
1985254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
1986254f889dSBrendon Cahoon               continue;
1987254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1988254f889dSBrendon Cahoon               continue;
1989b7c5e0b0SKazu Hirata             if (NodeOrder.contains(I.getSUnit()))
1990254f889dSBrendon Cahoon               continue;
1991254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1992254f889dSBrendon Cahoon           }
1993254f889dSBrendon Cahoon         }
1994254f889dSBrendon Cahoon         Order = TopDown;
1995d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
1996254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
1997254f889dSBrendon Cahoon         if (succ_L(NodeOrder, N, &Nodes))
1998254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
1999254f889dSBrendon Cahoon       }
2000254f889dSBrendon Cahoon     }
2001d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2002254f889dSBrendon Cahoon   }
2003254f889dSBrendon Cahoon 
2004d34e60caSNicola Zaghen   LLVM_DEBUG({
2005254f889dSBrendon Cahoon     dbgs() << "Node order: ";
2006254f889dSBrendon Cahoon     for (SUnit *I : NodeOrder)
2007254f889dSBrendon Cahoon       dbgs() << " " << I->NodeNum << " ";
2008254f889dSBrendon Cahoon     dbgs() << "\n";
2009254f889dSBrendon Cahoon   });
2010254f889dSBrendon Cahoon }
2011254f889dSBrendon Cahoon 
2012254f889dSBrendon Cahoon /// Process the nodes in the computed order and create the pipelined schedule
2013254f889dSBrendon Cahoon /// of the instructions, if possible. Return true if a schedule is found.
2014254f889dSBrendon Cahoon bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
201518e7bf5cSJinsong Ji 
201618e7bf5cSJinsong Ji   if (NodeOrder.empty()){
201718e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2018254f889dSBrendon Cahoon     return false;
201918e7bf5cSJinsong Ji   }
2020254f889dSBrendon Cahoon 
2021254f889dSBrendon Cahoon   bool scheduleFound = false;
2022254f889dSBrendon Cahoon   // Keep increasing II until a valid schedule is found.
2023f0ec9f1bSMarianne Mailhot-Sarrasin   for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2024254f889dSBrendon Cahoon     Schedule.reset();
2025254f889dSBrendon Cahoon     Schedule.setInitiationInterval(II);
2026d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2027254f889dSBrendon Cahoon 
2028254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2029254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NE = NodeOrder.end();
2030254f889dSBrendon Cahoon     do {
2031254f889dSBrendon Cahoon       SUnit *SU = *NI;
2032254f889dSBrendon Cahoon 
2033254f889dSBrendon Cahoon       // Compute the schedule time for the instruction, which is based
2034254f889dSBrendon Cahoon       // upon the scheduled time for any predecessors/successors.
2035254f889dSBrendon Cahoon       int EarlyStart = INT_MIN;
2036254f889dSBrendon Cahoon       int LateStart = INT_MAX;
2037254f889dSBrendon Cahoon       // These values are set when the size of the schedule window is limited
2038254f889dSBrendon Cahoon       // due to chain dependences.
2039254f889dSBrendon Cahoon       int SchedEnd = INT_MAX;
2040254f889dSBrendon Cahoon       int SchedStart = INT_MIN;
2041254f889dSBrendon Cahoon       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2042254f889dSBrendon Cahoon                             II, this);
2043d34e60caSNicola Zaghen       LLVM_DEBUG({
204418e7bf5cSJinsong Ji         dbgs() << "\n";
2045254f889dSBrendon Cahoon         dbgs() << "Inst (" << SU->NodeNum << ") ";
2046254f889dSBrendon Cahoon         SU->getInstr()->dump();
2047254f889dSBrendon Cahoon         dbgs() << "\n";
2048254f889dSBrendon Cahoon       });
2049d34e60caSNicola Zaghen       LLVM_DEBUG({
205018e7bf5cSJinsong Ji         dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
205118e7bf5cSJinsong Ji                          LateStart, SchedEnd, SchedStart);
2052254f889dSBrendon Cahoon       });
2053254f889dSBrendon Cahoon 
2054254f889dSBrendon Cahoon       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2055254f889dSBrendon Cahoon           SchedStart > LateStart)
2056254f889dSBrendon Cahoon         scheduleFound = false;
2057254f889dSBrendon Cahoon       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2058254f889dSBrendon Cahoon         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
2059254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2060254f889dSBrendon Cahoon       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2061254f889dSBrendon Cahoon         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
2062254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2063254f889dSBrendon Cahoon       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2064254f889dSBrendon Cahoon         SchedEnd =
2065254f889dSBrendon Cahoon             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
2066254f889dSBrendon Cahoon         // When scheduling a Phi it is better to start at the late cycle and go
2067254f889dSBrendon Cahoon         // backwards. The default order may insert the Phi too far away from
2068254f889dSBrendon Cahoon         // its first dependence.
2069254f889dSBrendon Cahoon         if (SU->getInstr()->isPHI())
2070254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2071254f889dSBrendon Cahoon         else
2072254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2073254f889dSBrendon Cahoon       } else {
2074254f889dSBrendon Cahoon         int FirstCycle = Schedule.getFirstCycle();
2075254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2076254f889dSBrendon Cahoon                                         FirstCycle + getASAP(SU) + II - 1, II);
2077254f889dSBrendon Cahoon       }
2078254f889dSBrendon Cahoon       // Even if we find a schedule, make sure the schedule doesn't exceed the
2079254f889dSBrendon Cahoon       // allowable number of stages. We keep trying if this happens.
2080254f889dSBrendon Cahoon       if (scheduleFound)
2081254f889dSBrendon Cahoon         if (SwpMaxStages > -1 &&
2082254f889dSBrendon Cahoon             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2083254f889dSBrendon Cahoon           scheduleFound = false;
2084254f889dSBrendon Cahoon 
2085d34e60caSNicola Zaghen       LLVM_DEBUG({
2086254f889dSBrendon Cahoon         if (!scheduleFound)
2087254f889dSBrendon Cahoon           dbgs() << "\tCan't schedule\n";
2088254f889dSBrendon Cahoon       });
2089254f889dSBrendon Cahoon     } while (++NI != NE && scheduleFound);
2090254f889dSBrendon Cahoon 
2091dcb77643SDavid Penry     // If a schedule is found, ensure non-pipelined instructions are in stage 0
2092dcb77643SDavid Penry     if (scheduleFound)
2093dcb77643SDavid Penry       scheduleFound =
2094dcb77643SDavid Penry           Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2095dcb77643SDavid Penry 
2096254f889dSBrendon Cahoon     // If a schedule is found, check if it is a valid schedule too.
2097254f889dSBrendon Cahoon     if (scheduleFound)
2098254f889dSBrendon Cahoon       scheduleFound = Schedule.isValidSchedule(this);
2099254f889dSBrendon Cahoon   }
2100254f889dSBrendon Cahoon 
2101f0ec9f1bSMarianne Mailhot-Sarrasin   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2102f0ec9f1bSMarianne Mailhot-Sarrasin                     << " (II=" << Schedule.getInitiationInterval()
210359d99731SBrendon Cahoon                     << ")\n");
2104254f889dSBrendon Cahoon 
210580b78a47SJinsong Ji   if (scheduleFound) {
2106254f889dSBrendon Cahoon     Schedule.finalizeSchedule(this);
210780b78a47SJinsong Ji     Pass.ORE->emit([&]() {
210880b78a47SJinsong Ji       return MachineOptimizationRemarkAnalysis(
210980b78a47SJinsong Ji                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2110f0ec9f1bSMarianne Mailhot-Sarrasin              << "Schedule found with Initiation Interval: "
2111f0ec9f1bSMarianne Mailhot-Sarrasin              << ore::NV("II", Schedule.getInitiationInterval())
211280b78a47SJinsong Ji              << ", MaxStageCount: "
211380b78a47SJinsong Ji              << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
211480b78a47SJinsong Ji     });
211580b78a47SJinsong Ji   } else
2116254f889dSBrendon Cahoon     Schedule.reset();
2117254f889dSBrendon Cahoon 
2118254f889dSBrendon Cahoon   return scheduleFound && Schedule.getMaxStageCount() > 0;
2119254f889dSBrendon Cahoon }
2120254f889dSBrendon Cahoon 
2121254f889dSBrendon Cahoon /// Return true if we can compute the amount the instruction changes
2122254f889dSBrendon Cahoon /// during each iteration. Set Delta to the amount of the change.
2123254f889dSBrendon Cahoon bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2124254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2125238c9d63SBjorn Pettersson   const MachineOperand *BaseOp;
2126254f889dSBrendon Cahoon   int64_t Offset;
21278fbc9258SSander de Smalen   bool OffsetIsScalable;
21288fbc9258SSander de Smalen   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
21298fbc9258SSander de Smalen     return false;
21308fbc9258SSander de Smalen 
21318fbc9258SSander de Smalen   // FIXME: This algorithm assumes instructions have fixed-size offsets.
21328fbc9258SSander de Smalen   if (OffsetIsScalable)
2133254f889dSBrendon Cahoon     return false;
2134254f889dSBrendon Cahoon 
2135d7eebd6dSFrancis Visoiu Mistrih   if (!BaseOp->isReg())
2136d7eebd6dSFrancis Visoiu Mistrih     return false;
2137d7eebd6dSFrancis Visoiu Mistrih 
21380c476111SDaniel Sanders   Register BaseReg = BaseOp->getReg();
2139d7eebd6dSFrancis Visoiu Mistrih 
2140254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
2141254f889dSBrendon Cahoon   // Check if there is a Phi. If so, get the definition in the loop.
2142254f889dSBrendon Cahoon   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2143254f889dSBrendon Cahoon   if (BaseDef && BaseDef->isPHI()) {
2144254f889dSBrendon Cahoon     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2145254f889dSBrendon Cahoon     BaseDef = MRI.getVRegDef(BaseReg);
2146254f889dSBrendon Cahoon   }
2147254f889dSBrendon Cahoon   if (!BaseDef)
2148254f889dSBrendon Cahoon     return false;
2149254f889dSBrendon Cahoon 
2150254f889dSBrendon Cahoon   int D = 0;
21518fb181caSKrzysztof Parzyszek   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2152254f889dSBrendon Cahoon     return false;
2153254f889dSBrendon Cahoon 
2154254f889dSBrendon Cahoon   Delta = D;
2155254f889dSBrendon Cahoon   return true;
2156254f889dSBrendon Cahoon }
2157254f889dSBrendon Cahoon 
2158254f889dSBrendon Cahoon /// Check if we can change the instruction to use an offset value from the
2159254f889dSBrendon Cahoon /// previous iteration. If so, return true and set the base and offset values
2160254f889dSBrendon Cahoon /// so that we can rewrite the load, if necessary.
2161254f889dSBrendon Cahoon ///   v1 = Phi(v0, v3)
2162254f889dSBrendon Cahoon ///   v2 = load v1, 0
2163254f889dSBrendon Cahoon ///   v3 = post_store v1, 4, x
2164254f889dSBrendon Cahoon /// This function enables the load to be rewritten as v2 = load v3, 4.
2165254f889dSBrendon Cahoon bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2166254f889dSBrendon Cahoon                                               unsigned &BasePos,
2167254f889dSBrendon Cahoon                                               unsigned &OffsetPos,
2168254f889dSBrendon Cahoon                                               unsigned &NewBase,
2169254f889dSBrendon Cahoon                                               int64_t &Offset) {
2170254f889dSBrendon Cahoon   // Get the load instruction.
21718fb181caSKrzysztof Parzyszek   if (TII->isPostIncrement(*MI))
2172254f889dSBrendon Cahoon     return false;
2173254f889dSBrendon Cahoon   unsigned BasePosLd, OffsetPosLd;
21748fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2175254f889dSBrendon Cahoon     return false;
21760c476111SDaniel Sanders   Register BaseReg = MI->getOperand(BasePosLd).getReg();
2177254f889dSBrendon Cahoon 
2178254f889dSBrendon Cahoon   // Look for the Phi instruction.
2179fdf9bf4fSJustin Bogner   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2180254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2181254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI())
2182254f889dSBrendon Cahoon     return false;
2183254f889dSBrendon Cahoon   // Get the register defined in the loop block.
2184254f889dSBrendon Cahoon   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2185254f889dSBrendon Cahoon   if (!PrevReg)
2186254f889dSBrendon Cahoon     return false;
2187254f889dSBrendon Cahoon 
2188254f889dSBrendon Cahoon   // Check for the post-increment load/store instruction.
2189254f889dSBrendon Cahoon   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2190254f889dSBrendon Cahoon   if (!PrevDef || PrevDef == MI)
2191254f889dSBrendon Cahoon     return false;
2192254f889dSBrendon Cahoon 
21938fb181caSKrzysztof Parzyszek   if (!TII->isPostIncrement(*PrevDef))
2194254f889dSBrendon Cahoon     return false;
2195254f889dSBrendon Cahoon 
2196254f889dSBrendon Cahoon   unsigned BasePos1 = 0, OffsetPos1 = 0;
21978fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2198254f889dSBrendon Cahoon     return false;
2199254f889dSBrendon Cahoon 
220040df8a2bSKrzysztof Parzyszek   // Make sure that the instructions do not access the same memory location in
220140df8a2bSKrzysztof Parzyszek   // the next iteration.
2202254f889dSBrendon Cahoon   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2203254f889dSBrendon Cahoon   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
220440df8a2bSKrzysztof Parzyszek   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
220540df8a2bSKrzysztof Parzyszek   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
220640df8a2bSKrzysztof Parzyszek   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
2207b0127424SMircea Trofin   MF.deleteMachineInstr(NewMI);
220840df8a2bSKrzysztof Parzyszek   if (!Disjoint)
2209254f889dSBrendon Cahoon     return false;
2210254f889dSBrendon Cahoon 
2211254f889dSBrendon Cahoon   // Set the return value once we determine that we return true.
2212254f889dSBrendon Cahoon   BasePos = BasePosLd;
2213254f889dSBrendon Cahoon   OffsetPos = OffsetPosLd;
2214254f889dSBrendon Cahoon   NewBase = PrevReg;
2215254f889dSBrendon Cahoon   Offset = StoreOffset;
2216254f889dSBrendon Cahoon   return true;
2217254f889dSBrendon Cahoon }
2218254f889dSBrendon Cahoon 
2219254f889dSBrendon Cahoon /// Apply changes to the instruction if needed. The changes are need
2220254f889dSBrendon Cahoon /// to improve the scheduling and depend up on the final schedule.
22218f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
22228f174ddeSKrzysztof Parzyszek                                          SMSchedule &Schedule) {
2223254f889dSBrendon Cahoon   SUnit *SU = getSUnit(MI);
2224254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2225254f889dSBrendon Cahoon       InstrChanges.find(SU);
2226254f889dSBrendon Cahoon   if (It != InstrChanges.end()) {
2227254f889dSBrendon Cahoon     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2228254f889dSBrendon Cahoon     unsigned BasePos, OffsetPos;
22298fb181caSKrzysztof Parzyszek     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
22308f174ddeSKrzysztof Parzyszek       return;
22310c476111SDaniel Sanders     Register BaseReg = MI->getOperand(BasePos).getReg();
2232254f889dSBrendon Cahoon     MachineInstr *LoopDef = findDefInLoop(BaseReg);
2233254f889dSBrendon Cahoon     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2234254f889dSBrendon Cahoon     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2235254f889dSBrendon Cahoon     int BaseStageNum = Schedule.stageScheduled(SU);
2236254f889dSBrendon Cahoon     int BaseCycleNum = Schedule.cycleScheduled(SU);
2237254f889dSBrendon Cahoon     if (BaseStageNum < DefStageNum) {
2238254f889dSBrendon Cahoon       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2239254f889dSBrendon Cahoon       int OffsetDiff = DefStageNum - BaseStageNum;
2240254f889dSBrendon Cahoon       if (DefCycleNum < BaseCycleNum) {
2241254f889dSBrendon Cahoon         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2242254f889dSBrendon Cahoon         if (OffsetDiff > 0)
2243254f889dSBrendon Cahoon           --OffsetDiff;
2244254f889dSBrendon Cahoon       }
2245254f889dSBrendon Cahoon       int64_t NewOffset =
2246254f889dSBrendon Cahoon           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2247254f889dSBrendon Cahoon       NewMI->getOperand(OffsetPos).setImm(NewOffset);
2248254f889dSBrendon Cahoon       SU->setInstr(NewMI);
2249254f889dSBrendon Cahoon       MISUnitMap[NewMI] = SU;
2250790a779fSJames Molloy       NewMIs[MI] = NewMI;
2251254f889dSBrendon Cahoon     }
2252254f889dSBrendon Cahoon   }
2253254f889dSBrendon Cahoon }
2254254f889dSBrendon Cahoon 
2255790a779fSJames Molloy /// Return the instruction in the loop that defines the register.
2256790a779fSJames Molloy /// If the definition is a Phi, then follow the Phi operand to
2257790a779fSJames Molloy /// the instruction in the loop.
2258c8fcffe7SMircea Trofin MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
2259790a779fSJames Molloy   SmallPtrSet<MachineInstr *, 8> Visited;
2260790a779fSJames Molloy   MachineInstr *Def = MRI.getVRegDef(Reg);
2261790a779fSJames Molloy   while (Def->isPHI()) {
2262790a779fSJames Molloy     if (!Visited.insert(Def).second)
2263790a779fSJames Molloy       break;
2264790a779fSJames Molloy     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
2265790a779fSJames Molloy       if (Def->getOperand(i + 1).getMBB() == BB) {
2266790a779fSJames Molloy         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
2267790a779fSJames Molloy         break;
2268790a779fSJames Molloy       }
2269790a779fSJames Molloy   }
2270790a779fSJames Molloy   return Def;
2271790a779fSJames Molloy }
2272790a779fSJames Molloy 
22738e1363dfSKrzysztof Parzyszek /// Return true for an order or output dependence that is loop carried
22748e1363dfSKrzysztof Parzyszek /// potentially. A dependence is loop carried if the destination defines a valu
22758e1363dfSKrzysztof Parzyszek /// that may be used or defined by the source in a subsequent iteration.
22768e1363dfSKrzysztof Parzyszek bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2277254f889dSBrendon Cahoon                                          bool isSucc) {
22788e1363dfSKrzysztof Parzyszek   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2279dcb77643SDavid Penry       Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
2280254f889dSBrendon Cahoon     return false;
2281254f889dSBrendon Cahoon 
2282254f889dSBrendon Cahoon   if (!SwpPruneLoopCarried)
2283254f889dSBrendon Cahoon     return true;
2284254f889dSBrendon Cahoon 
22858e1363dfSKrzysztof Parzyszek   if (Dep.getKind() == SDep::Output)
22868e1363dfSKrzysztof Parzyszek     return true;
22878e1363dfSKrzysztof Parzyszek 
2288254f889dSBrendon Cahoon   MachineInstr *SI = Source->getInstr();
2289254f889dSBrendon Cahoon   MachineInstr *DI = Dep.getSUnit()->getInstr();
2290254f889dSBrendon Cahoon   if (!isSucc)
2291254f889dSBrendon Cahoon     std::swap(SI, DI);
2292254f889dSBrendon Cahoon   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2293254f889dSBrendon Cahoon 
2294254f889dSBrendon Cahoon   // Assume ordered loads and stores may have a loop carried dependence.
2295254f889dSBrendon Cahoon   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
22966c5d5ce5SUlrich Weigand       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2297254f889dSBrendon Cahoon       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2298254f889dSBrendon Cahoon     return true;
2299254f889dSBrendon Cahoon 
2300254f889dSBrendon Cahoon   // Only chain dependences between a load and store can be loop carried.
2301254f889dSBrendon Cahoon   if (!DI->mayStore() || !SI->mayLoad())
2302254f889dSBrendon Cahoon     return false;
2303254f889dSBrendon Cahoon 
2304254f889dSBrendon Cahoon   unsigned DeltaS, DeltaD;
2305254f889dSBrendon Cahoon   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2306254f889dSBrendon Cahoon     return true;
2307254f889dSBrendon Cahoon 
2308238c9d63SBjorn Pettersson   const MachineOperand *BaseOpS, *BaseOpD;
2309254f889dSBrendon Cahoon   int64_t OffsetS, OffsetD;
23108fbc9258SSander de Smalen   bool OffsetSIsScalable, OffsetDIsScalable;
2311254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
23128fbc9258SSander de Smalen   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
23138fbc9258SSander de Smalen                                     TRI) ||
23148fbc9258SSander de Smalen       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
23158fbc9258SSander de Smalen                                     TRI))
2316254f889dSBrendon Cahoon     return true;
2317254f889dSBrendon Cahoon 
23188fbc9258SSander de Smalen   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
23198fbc9258SSander de Smalen          "Expected offsets to be byte offsets");
23208fbc9258SSander de Smalen 
2321d7eebd6dSFrancis Visoiu Mistrih   if (!BaseOpS->isIdenticalTo(*BaseOpD))
2322254f889dSBrendon Cahoon     return true;
2323254f889dSBrendon Cahoon 
23248c07d0c4SKrzysztof Parzyszek   // Check that the base register is incremented by a constant value for each
23258c07d0c4SKrzysztof Parzyszek   // iteration.
2326d7eebd6dSFrancis Visoiu Mistrih   MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
23278c07d0c4SKrzysztof Parzyszek   if (!Def || !Def->isPHI())
23288c07d0c4SKrzysztof Parzyszek     return true;
23298c07d0c4SKrzysztof Parzyszek   unsigned InitVal = 0;
23308c07d0c4SKrzysztof Parzyszek   unsigned LoopVal = 0;
23318c07d0c4SKrzysztof Parzyszek   getPhiRegs(*Def, BB, InitVal, LoopVal);
23328c07d0c4SKrzysztof Parzyszek   MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
23338c07d0c4SKrzysztof Parzyszek   int D = 0;
23348c07d0c4SKrzysztof Parzyszek   if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
23358c07d0c4SKrzysztof Parzyszek     return true;
23368c07d0c4SKrzysztof Parzyszek 
2337254f889dSBrendon Cahoon   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
2338254f889dSBrendon Cahoon   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
2339254f889dSBrendon Cahoon 
2340254f889dSBrendon Cahoon   // This is the main test, which checks the offset values and the loop
2341254f889dSBrendon Cahoon   // increment value to determine if the accesses may be loop carried.
234257c3d4beSBrendon Cahoon   if (AccessSizeS == MemoryLocation::UnknownSize ||
234357c3d4beSBrendon Cahoon       AccessSizeD == MemoryLocation::UnknownSize)
2344254f889dSBrendon Cahoon     return true;
234557c3d4beSBrendon Cahoon 
234657c3d4beSBrendon Cahoon   if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
234757c3d4beSBrendon Cahoon     return true;
234857c3d4beSBrendon Cahoon 
234957c3d4beSBrendon Cahoon   return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
2350254f889dSBrendon Cahoon }
2351254f889dSBrendon Cahoon 
235288391248SKrzysztof Parzyszek void SwingSchedulerDAG::postprocessDAG() {
235388391248SKrzysztof Parzyszek   for (auto &M : Mutations)
235488391248SKrzysztof Parzyszek     M->apply(this);
235588391248SKrzysztof Parzyszek }
235688391248SKrzysztof Parzyszek 
2357254f889dSBrendon Cahoon /// Try to schedule the node at the specified StartCycle and continue
2358254f889dSBrendon Cahoon /// until the node is schedule or the EndCycle is reached.  This function
2359254f889dSBrendon Cahoon /// returns true if the node is scheduled.  This routine may search either
2360254f889dSBrendon Cahoon /// forward or backward for a place to insert the instruction based upon
2361254f889dSBrendon Cahoon /// the relative values of StartCycle and EndCycle.
2362254f889dSBrendon Cahoon bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2363254f889dSBrendon Cahoon   bool forward = true;
236418e7bf5cSJinsong Ji   LLVM_DEBUG({
236518e7bf5cSJinsong Ji     dbgs() << "Trying to insert node between " << StartCycle << " and "
236618e7bf5cSJinsong Ji            << EndCycle << " II: " << II << "\n";
236718e7bf5cSJinsong Ji   });
2368254f889dSBrendon Cahoon   if (StartCycle > EndCycle)
2369254f889dSBrendon Cahoon     forward = false;
2370254f889dSBrendon Cahoon 
2371254f889dSBrendon Cahoon   // The terminating condition depends on the direction.
2372254f889dSBrendon Cahoon   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2373254f889dSBrendon Cahoon   for (int curCycle = StartCycle; curCycle != termCycle;
2374254f889dSBrendon Cahoon        forward ? ++curCycle : --curCycle) {
2375254f889dSBrendon Cahoon 
2376f6cb3bcbSJinsong Ji     // Add the already scheduled instructions at the specified cycle to the
2377f6cb3bcbSJinsong Ji     // DFA.
2378f6cb3bcbSJinsong Ji     ProcItinResources.clearResources();
2379254f889dSBrendon Cahoon     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
2380254f889dSBrendon Cahoon          checkCycle <= LastCycle; checkCycle += II) {
2381254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
2382254f889dSBrendon Cahoon 
23833279943aSKazu Hirata       for (SUnit *CI : cycleInstrs) {
23843279943aSKazu Hirata         if (ST.getInstrInfo()->isZeroCost(CI->getInstr()->getOpcode()))
2385254f889dSBrendon Cahoon           continue;
23863279943aSKazu Hirata         assert(ProcItinResources.canReserveResources(*CI->getInstr()) &&
2387254f889dSBrendon Cahoon                "These instructions have already been scheduled.");
23883279943aSKazu Hirata         ProcItinResources.reserveResources(*CI->getInstr());
2389254f889dSBrendon Cahoon       }
2390254f889dSBrendon Cahoon     }
2391254f889dSBrendon Cahoon     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2392f6cb3bcbSJinsong Ji         ProcItinResources.canReserveResources(*SU->getInstr())) {
2393d34e60caSNicola Zaghen       LLVM_DEBUG({
2394254f889dSBrendon Cahoon         dbgs() << "\tinsert at cycle " << curCycle << " ";
2395254f889dSBrendon Cahoon         SU->getInstr()->dump();
2396254f889dSBrendon Cahoon       });
2397254f889dSBrendon Cahoon 
2398254f889dSBrendon Cahoon       ScheduledInstrs[curCycle].push_back(SU);
2399254f889dSBrendon Cahoon       InstrToCycle.insert(std::make_pair(SU, curCycle));
2400254f889dSBrendon Cahoon       if (curCycle > LastCycle)
2401254f889dSBrendon Cahoon         LastCycle = curCycle;
2402254f889dSBrendon Cahoon       if (curCycle < FirstCycle)
2403254f889dSBrendon Cahoon         FirstCycle = curCycle;
2404254f889dSBrendon Cahoon       return true;
2405254f889dSBrendon Cahoon     }
2406d34e60caSNicola Zaghen     LLVM_DEBUG({
2407254f889dSBrendon Cahoon       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2408254f889dSBrendon Cahoon       SU->getInstr()->dump();
2409254f889dSBrendon Cahoon     });
2410254f889dSBrendon Cahoon   }
2411254f889dSBrendon Cahoon   return false;
2412254f889dSBrendon Cahoon }
2413254f889dSBrendon Cahoon 
2414254f889dSBrendon Cahoon // Return the cycle of the earliest scheduled instruction in the chain.
2415254f889dSBrendon Cahoon int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2416254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
2417254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
2418254f889dSBrendon Cahoon   Worklist.push_back(Dep);
2419254f889dSBrendon Cahoon   int EarlyCycle = INT_MAX;
2420254f889dSBrendon Cahoon   while (!Worklist.empty()) {
2421254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
2422254f889dSBrendon Cahoon     SUnit *PrevSU = Cur.getSUnit();
2423254f889dSBrendon Cahoon     if (Visited.count(PrevSU))
2424254f889dSBrendon Cahoon       continue;
2425254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2426254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
2427254f889dSBrendon Cahoon       continue;
2428254f889dSBrendon Cahoon     EarlyCycle = std::min(EarlyCycle, it->second);
2429254f889dSBrendon Cahoon     for (const auto &PI : PrevSU->Preds)
24304a6ebc03SLama       if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
2431254f889dSBrendon Cahoon         Worklist.push_back(PI);
2432254f889dSBrendon Cahoon     Visited.insert(PrevSU);
2433254f889dSBrendon Cahoon   }
2434254f889dSBrendon Cahoon   return EarlyCycle;
2435254f889dSBrendon Cahoon }
2436254f889dSBrendon Cahoon 
2437254f889dSBrendon Cahoon // Return the cycle of the latest scheduled instruction in the chain.
2438254f889dSBrendon Cahoon int SMSchedule::latestCycleInChain(const SDep &Dep) {
2439254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
2440254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
2441254f889dSBrendon Cahoon   Worklist.push_back(Dep);
2442254f889dSBrendon Cahoon   int LateCycle = INT_MIN;
2443254f889dSBrendon Cahoon   while (!Worklist.empty()) {
2444254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
2445254f889dSBrendon Cahoon     SUnit *SuccSU = Cur.getSUnit();
2446dcb77643SDavid Penry     if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
2447254f889dSBrendon Cahoon       continue;
2448254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2449254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
2450254f889dSBrendon Cahoon       continue;
2451254f889dSBrendon Cahoon     LateCycle = std::max(LateCycle, it->second);
2452254f889dSBrendon Cahoon     for (const auto &SI : SuccSU->Succs)
24534a6ebc03SLama       if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
2454254f889dSBrendon Cahoon         Worklist.push_back(SI);
2455254f889dSBrendon Cahoon     Visited.insert(SuccSU);
2456254f889dSBrendon Cahoon   }
2457254f889dSBrendon Cahoon   return LateCycle;
2458254f889dSBrendon Cahoon }
2459254f889dSBrendon Cahoon 
2460254f889dSBrendon Cahoon /// If an instruction has a use that spans multiple iterations, then
2461254f889dSBrendon Cahoon /// return true. These instructions are characterized by having a back-ege
2462254f889dSBrendon Cahoon /// to a Phi, which contains a reference to another Phi.
2463254f889dSBrendon Cahoon static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2464254f889dSBrendon Cahoon   for (auto &P : SU->Preds)
2465254f889dSBrendon Cahoon     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2466254f889dSBrendon Cahoon       for (auto &S : P.getSUnit()->Succs)
2467b9b75b8cSKrzysztof Parzyszek         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2468254f889dSBrendon Cahoon           return P.getSUnit();
2469254f889dSBrendon Cahoon   return nullptr;
2470254f889dSBrendon Cahoon }
2471254f889dSBrendon Cahoon 
2472254f889dSBrendon Cahoon /// Compute the scheduling start slot for the instruction.  The start slot
2473254f889dSBrendon Cahoon /// depends on any predecessor or successor nodes scheduled already.
2474254f889dSBrendon Cahoon void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2475254f889dSBrendon Cahoon                               int *MinEnd, int *MaxStart, int II,
2476254f889dSBrendon Cahoon                               SwingSchedulerDAG *DAG) {
2477254f889dSBrendon Cahoon   // Iterate over each instruction that has been scheduled already.  The start
2478c73b6d6bSHiroshi Inoue   // slot computation depends on whether the previously scheduled instruction
2479254f889dSBrendon Cahoon   // is a predecessor or successor of the specified instruction.
2480254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2481254f889dSBrendon Cahoon 
2482254f889dSBrendon Cahoon     // Iterate over each instruction in the current cycle.
2483254f889dSBrendon Cahoon     for (SUnit *I : getInstructions(cycle)) {
2484254f889dSBrendon Cahoon       // Because we're processing a DAG for the dependences, we recognize
2485254f889dSBrendon Cahoon       // the back-edge in recurrences by anti dependences.
2486254f889dSBrendon Cahoon       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2487254f889dSBrendon Cahoon         const SDep &Dep = SU->Preds[i];
2488254f889dSBrendon Cahoon         if (Dep.getSUnit() == I) {
2489254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
2490c715a5d2SKrzysztof Parzyszek             int EarlyStart = cycle + Dep.getLatency() -
2491254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2492254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
24938e1363dfSKrzysztof Parzyszek             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2494254f889dSBrendon Cahoon               int End = earliestCycleInChain(Dep) + (II - 1);
2495254f889dSBrendon Cahoon               *MinEnd = std::min(*MinEnd, End);
2496254f889dSBrendon Cahoon             }
2497254f889dSBrendon Cahoon           } else {
2498c715a5d2SKrzysztof Parzyszek             int LateStart = cycle - Dep.getLatency() +
2499254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2500254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
2501254f889dSBrendon Cahoon           }
2502254f889dSBrendon Cahoon         }
2503254f889dSBrendon Cahoon         // For instruction that requires multiple iterations, make sure that
2504254f889dSBrendon Cahoon         // the dependent instruction is not scheduled past the definition.
2505254f889dSBrendon Cahoon         SUnit *BE = multipleIterations(I, DAG);
2506254f889dSBrendon Cahoon         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2507254f889dSBrendon Cahoon             !SU->isPred(I))
2508254f889dSBrendon Cahoon           *MinLateStart = std::min(*MinLateStart, cycle);
2509254f889dSBrendon Cahoon       }
2510a2122044SKrzysztof Parzyszek       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2511254f889dSBrendon Cahoon         if (SU->Succs[i].getSUnit() == I) {
2512254f889dSBrendon Cahoon           const SDep &Dep = SU->Succs[i];
2513254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
2514c715a5d2SKrzysztof Parzyszek             int LateStart = cycle - Dep.getLatency() +
2515254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2516254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
25178e1363dfSKrzysztof Parzyszek             if (DAG->isLoopCarriedDep(SU, Dep)) {
2518254f889dSBrendon Cahoon               int Start = latestCycleInChain(Dep) + 1 - II;
2519254f889dSBrendon Cahoon               *MaxStart = std::max(*MaxStart, Start);
2520254f889dSBrendon Cahoon             }
2521254f889dSBrendon Cahoon           } else {
2522c715a5d2SKrzysztof Parzyszek             int EarlyStart = cycle + Dep.getLatency() -
2523254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2524254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2525254f889dSBrendon Cahoon           }
2526254f889dSBrendon Cahoon         }
2527254f889dSBrendon Cahoon       }
2528254f889dSBrendon Cahoon     }
2529254f889dSBrendon Cahoon   }
2530a2122044SKrzysztof Parzyszek }
2531254f889dSBrendon Cahoon 
2532254f889dSBrendon Cahoon /// Order the instructions within a cycle so that the definitions occur
2533254f889dSBrendon Cahoon /// before the uses. Returns true if the instruction is added to the start
2534254f889dSBrendon Cahoon /// of the list, or false if added to the end.
2535f13bbf1dSKrzysztof Parzyszek void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
2536254f889dSBrendon Cahoon                                  std::deque<SUnit *> &Insts) {
2537254f889dSBrendon Cahoon   MachineInstr *MI = SU->getInstr();
2538254f889dSBrendon Cahoon   bool OrderBeforeUse = false;
2539254f889dSBrendon Cahoon   bool OrderAfterDef = false;
2540254f889dSBrendon Cahoon   bool OrderBeforeDef = false;
2541254f889dSBrendon Cahoon   unsigned MoveDef = 0;
2542254f889dSBrendon Cahoon   unsigned MoveUse = 0;
2543254f889dSBrendon Cahoon   int StageInst1 = stageScheduled(SU);
2544254f889dSBrendon Cahoon 
2545254f889dSBrendon Cahoon   unsigned Pos = 0;
2546254f889dSBrendon Cahoon   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2547254f889dSBrendon Cahoon        ++I, ++Pos) {
2548c73fc74cSKazu Hirata     for (MachineOperand &MO : MI->operands()) {
25492bea69bfSDaniel Sanders       if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
2550254f889dSBrendon Cahoon         continue;
2551f13bbf1dSKrzysztof Parzyszek 
25520c476111SDaniel Sanders       Register Reg = MO.getReg();
2553254f889dSBrendon Cahoon       unsigned BasePos, OffsetPos;
25548fb181caSKrzysztof Parzyszek       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2555254f889dSBrendon Cahoon         if (MI->getOperand(BasePos).getReg() == Reg)
2556254f889dSBrendon Cahoon           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
2557254f889dSBrendon Cahoon             Reg = NewReg;
2558254f889dSBrendon Cahoon       bool Reads, Writes;
2559254f889dSBrendon Cahoon       std::tie(Reads, Writes) =
2560254f889dSBrendon Cahoon           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
2561254f889dSBrendon Cahoon       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
2562254f889dSBrendon Cahoon         OrderBeforeUse = true;
2563f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
2564254f889dSBrendon Cahoon           MoveUse = Pos;
2565254f889dSBrendon Cahoon       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
2566254f889dSBrendon Cahoon         // Add the instruction after the scheduled instruction.
2567254f889dSBrendon Cahoon         OrderAfterDef = true;
2568254f889dSBrendon Cahoon         MoveDef = Pos;
2569254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
2570254f889dSBrendon Cahoon         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
2571254f889dSBrendon Cahoon           OrderBeforeUse = true;
2572f13bbf1dSKrzysztof Parzyszek           if (MoveUse == 0)
2573254f889dSBrendon Cahoon             MoveUse = Pos;
2574254f889dSBrendon Cahoon         } else {
2575254f889dSBrendon Cahoon           OrderAfterDef = true;
2576254f889dSBrendon Cahoon           MoveDef = Pos;
2577254f889dSBrendon Cahoon         }
2578254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
2579254f889dSBrendon Cahoon         OrderBeforeUse = true;
2580f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
2581254f889dSBrendon Cahoon           MoveUse = Pos;
2582254f889dSBrendon Cahoon         if (MoveUse != 0) {
2583254f889dSBrendon Cahoon           OrderAfterDef = true;
2584254f889dSBrendon Cahoon           MoveDef = Pos - 1;
2585254f889dSBrendon Cahoon         }
2586254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
2587254f889dSBrendon Cahoon         // Add the instruction before the scheduled instruction.
2588254f889dSBrendon Cahoon         OrderBeforeUse = true;
2589f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
2590254f889dSBrendon Cahoon           MoveUse = Pos;
2591254f889dSBrendon Cahoon       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
2592254f889dSBrendon Cahoon                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
2593f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0) {
2594254f889dSBrendon Cahoon           OrderBeforeDef = true;
2595254f889dSBrendon Cahoon           MoveUse = Pos;
2596254f889dSBrendon Cahoon         }
2597254f889dSBrendon Cahoon       }
2598f13bbf1dSKrzysztof Parzyszek     }
2599254f889dSBrendon Cahoon     // Check for order dependences between instructions. Make sure the source
2600254f889dSBrendon Cahoon     // is ordered before the destination.
26018e1363dfSKrzysztof Parzyszek     for (auto &S : SU->Succs) {
26028e1363dfSKrzysztof Parzyszek       if (S.getSUnit() != *I)
26038e1363dfSKrzysztof Parzyszek         continue;
26048e1363dfSKrzysztof Parzyszek       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2605254f889dSBrendon Cahoon         OrderBeforeUse = true;
26068e1363dfSKrzysztof Parzyszek         if (Pos < MoveUse)
2607254f889dSBrendon Cahoon           MoveUse = Pos;
2608254f889dSBrendon Cahoon       }
260995770866SJinsong Ji       // We did not handle HW dependences in previous for loop,
261095770866SJinsong Ji       // and we normally set Latency = 0 for Anti deps,
261195770866SJinsong Ji       // so may have nodes in same cycle with Anti denpendent on HW regs.
261295770866SJinsong Ji       else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
261395770866SJinsong Ji         OrderBeforeUse = true;
261495770866SJinsong Ji         if ((MoveUse == 0) || (Pos < MoveUse))
261595770866SJinsong Ji           MoveUse = Pos;
261695770866SJinsong Ji       }
2617254f889dSBrendon Cahoon     }
26188e1363dfSKrzysztof Parzyszek     for (auto &P : SU->Preds) {
26198e1363dfSKrzysztof Parzyszek       if (P.getSUnit() != *I)
26208e1363dfSKrzysztof Parzyszek         continue;
26218e1363dfSKrzysztof Parzyszek       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
2622254f889dSBrendon Cahoon         OrderAfterDef = true;
2623254f889dSBrendon Cahoon         MoveDef = Pos;
2624254f889dSBrendon Cahoon       }
2625254f889dSBrendon Cahoon     }
2626254f889dSBrendon Cahoon   }
2627254f889dSBrendon Cahoon 
2628254f889dSBrendon Cahoon   // A circular dependence.
2629254f889dSBrendon Cahoon   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
2630254f889dSBrendon Cahoon     OrderBeforeUse = false;
2631254f889dSBrendon Cahoon 
2632254f889dSBrendon Cahoon   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2633254f889dSBrendon Cahoon   // to a loop-carried dependence.
2634254f889dSBrendon Cahoon   if (OrderBeforeDef)
2635254f889dSBrendon Cahoon     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
2636254f889dSBrendon Cahoon 
2637254f889dSBrendon Cahoon   // The uncommon case when the instruction order needs to be updated because
2638254f889dSBrendon Cahoon   // there is both a use and def.
2639254f889dSBrendon Cahoon   if (OrderBeforeUse && OrderAfterDef) {
2640254f889dSBrendon Cahoon     SUnit *UseSU = Insts.at(MoveUse);
2641254f889dSBrendon Cahoon     SUnit *DefSU = Insts.at(MoveDef);
2642254f889dSBrendon Cahoon     if (MoveUse > MoveDef) {
2643254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
2644254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
2645254f889dSBrendon Cahoon     } else {
2646254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
2647254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
2648254f889dSBrendon Cahoon     }
2649f13bbf1dSKrzysztof Parzyszek     orderDependence(SSD, UseSU, Insts);
2650f13bbf1dSKrzysztof Parzyszek     orderDependence(SSD, SU, Insts);
2651254f889dSBrendon Cahoon     orderDependence(SSD, DefSU, Insts);
2652f13bbf1dSKrzysztof Parzyszek     return;
2653254f889dSBrendon Cahoon   }
2654254f889dSBrendon Cahoon   // Put the new instruction first if there is a use in the list. Otherwise,
2655254f889dSBrendon Cahoon   // put it at the end of the list.
2656254f889dSBrendon Cahoon   if (OrderBeforeUse)
2657254f889dSBrendon Cahoon     Insts.push_front(SU);
2658254f889dSBrendon Cahoon   else
2659254f889dSBrendon Cahoon     Insts.push_back(SU);
2660254f889dSBrendon Cahoon }
2661254f889dSBrendon Cahoon 
2662254f889dSBrendon Cahoon /// Return true if the scheduled Phi has a loop carried operand.
2663254f889dSBrendon Cahoon bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
2664254f889dSBrendon Cahoon   if (!Phi.isPHI())
2665254f889dSBrendon Cahoon     return false;
2666c73b6d6bSHiroshi Inoue   assert(Phi.isPHI() && "Expecting a Phi.");
2667254f889dSBrendon Cahoon   SUnit *DefSU = SSD->getSUnit(&Phi);
2668254f889dSBrendon Cahoon   unsigned DefCycle = cycleScheduled(DefSU);
2669254f889dSBrendon Cahoon   int DefStage = stageScheduled(DefSU);
2670254f889dSBrendon Cahoon 
2671254f889dSBrendon Cahoon   unsigned InitVal = 0;
2672254f889dSBrendon Cahoon   unsigned LoopVal = 0;
2673254f889dSBrendon Cahoon   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
2674254f889dSBrendon Cahoon   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
2675254f889dSBrendon Cahoon   if (!UseSU)
2676254f889dSBrendon Cahoon     return true;
2677254f889dSBrendon Cahoon   if (UseSU->getInstr()->isPHI())
2678254f889dSBrendon Cahoon     return true;
2679254f889dSBrendon Cahoon   unsigned LoopCycle = cycleScheduled(UseSU);
2680254f889dSBrendon Cahoon   int LoopStage = stageScheduled(UseSU);
26813d8482a8SSimon Pilgrim   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
2682254f889dSBrendon Cahoon }
2683254f889dSBrendon Cahoon 
2684254f889dSBrendon Cahoon /// Return true if the instruction is a definition that is loop carried
2685254f889dSBrendon Cahoon /// and defines the use on the next iteration.
2686254f889dSBrendon Cahoon ///        v1 = phi(v2, v3)
2687254f889dSBrendon Cahoon ///  (Def) v3 = op v1
2688254f889dSBrendon Cahoon ///  (MO)   = v1
2689254f889dSBrendon Cahoon /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2690254f889dSBrendon Cahoon /// register.
2691254f889dSBrendon Cahoon bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
2692254f889dSBrendon Cahoon                                        MachineInstr *Def, MachineOperand &MO) {
2693254f889dSBrendon Cahoon   if (!MO.isReg())
2694254f889dSBrendon Cahoon     return false;
2695254f889dSBrendon Cahoon   if (Def->isPHI())
2696254f889dSBrendon Cahoon     return false;
2697254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
2698254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
2699254f889dSBrendon Cahoon     return false;
2700254f889dSBrendon Cahoon   if (!isLoopCarried(SSD, *Phi))
2701254f889dSBrendon Cahoon     return false;
2702254f889dSBrendon Cahoon   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
2703254f889dSBrendon Cahoon   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
2704254f889dSBrendon Cahoon     MachineOperand &DMO = Def->getOperand(i);
2705254f889dSBrendon Cahoon     if (!DMO.isReg() || !DMO.isDef())
2706254f889dSBrendon Cahoon       continue;
2707254f889dSBrendon Cahoon     if (DMO.getReg() == LoopReg)
2708254f889dSBrendon Cahoon       return true;
2709254f889dSBrendon Cahoon   }
2710254f889dSBrendon Cahoon   return false;
2711254f889dSBrendon Cahoon }
2712254f889dSBrendon Cahoon 
2713dcb77643SDavid Penry /// Determine transitive dependences of unpipelineable instructions
2714dcb77643SDavid Penry SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
2715dcb77643SDavid Penry     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
2716dcb77643SDavid Penry   SmallSet<SUnit *, 8> DoNotPipeline;
2717dcb77643SDavid Penry   SmallVector<SUnit *, 8> Worklist;
2718dcb77643SDavid Penry 
2719dcb77643SDavid Penry   for (auto &SU : SSD->SUnits)
2720dcb77643SDavid Penry     if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
2721dcb77643SDavid Penry       Worklist.push_back(&SU);
2722dcb77643SDavid Penry 
2723dcb77643SDavid Penry   while (!Worklist.empty()) {
2724dcb77643SDavid Penry     auto SU = Worklist.pop_back_val();
2725dcb77643SDavid Penry     if (DoNotPipeline.count(SU))
2726dcb77643SDavid Penry       continue;
2727dcb77643SDavid Penry     LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
2728dcb77643SDavid Penry     DoNotPipeline.insert(SU);
2729dcb77643SDavid Penry     for (auto &Dep : SU->Preds)
2730dcb77643SDavid Penry       Worklist.push_back(Dep.getSUnit());
2731dcb77643SDavid Penry     if (SU->getInstr()->isPHI())
2732dcb77643SDavid Penry       for (auto &Dep : SU->Succs)
2733dcb77643SDavid Penry         if (Dep.getKind() == SDep::Anti)
2734dcb77643SDavid Penry           Worklist.push_back(Dep.getSUnit());
2735dcb77643SDavid Penry   }
2736dcb77643SDavid Penry   return DoNotPipeline;
2737dcb77643SDavid Penry }
2738dcb77643SDavid Penry 
2739dcb77643SDavid Penry // Determine all instructions upon which any unpipelineable instruction depends
2740dcb77643SDavid Penry // and ensure that they are in stage 0.  If unable to do so, return false.
2741dcb77643SDavid Penry bool SMSchedule::normalizeNonPipelinedInstructions(
2742dcb77643SDavid Penry     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
2743dcb77643SDavid Penry   SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
2744dcb77643SDavid Penry 
2745dcb77643SDavid Penry   int NewLastCycle = INT_MIN;
2746dcb77643SDavid Penry   for (SUnit &SU : SSD->SUnits) {
2747dcb77643SDavid Penry     if (!SU.isInstr())
2748dcb77643SDavid Penry       continue;
2749dcb77643SDavid Penry     if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
2750dcb77643SDavid Penry       NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
2751dcb77643SDavid Penry       continue;
2752dcb77643SDavid Penry     }
2753dcb77643SDavid Penry 
2754dcb77643SDavid Penry     // Put the non-pipelined instruction as early as possible in the schedule
2755dcb77643SDavid Penry     int NewCycle = getFirstCycle();
2756dcb77643SDavid Penry     for (auto &Dep : SU.Preds)
2757dcb77643SDavid Penry       NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
2758dcb77643SDavid Penry 
2759dcb77643SDavid Penry     int OldCycle = InstrToCycle[&SU];
2760dcb77643SDavid Penry     if (OldCycle != NewCycle) {
2761dcb77643SDavid Penry       InstrToCycle[&SU] = NewCycle;
2762dcb77643SDavid Penry       auto &OldS = getInstructions(OldCycle);
2763dcb77643SDavid Penry       OldS.erase(std::remove(OldS.begin(), OldS.end(), &SU), OldS.end());
2764dcb77643SDavid Penry       getInstructions(NewCycle).emplace_back(&SU);
2765dcb77643SDavid Penry       LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
2766dcb77643SDavid Penry                         << ") is not pipelined; moving from cycle " << OldCycle
2767dcb77643SDavid Penry                         << " to " << NewCycle << " Instr:" << *SU.getInstr());
2768dcb77643SDavid Penry     }
2769dcb77643SDavid Penry     NewLastCycle = std::max(NewLastCycle, NewCycle);
2770dcb77643SDavid Penry   }
2771dcb77643SDavid Penry   LastCycle = NewLastCycle;
2772dcb77643SDavid Penry   return true;
2773dcb77643SDavid Penry }
2774dcb77643SDavid Penry 
2775254f889dSBrendon Cahoon // Check if the generated schedule is valid. This function checks if
2776254f889dSBrendon Cahoon // an instruction that uses a physical register is scheduled in a
2777254f889dSBrendon Cahoon // different stage than the definition. The pipeliner does not handle
2778254f889dSBrendon Cahoon // physical register values that may cross a basic block boundary.
2779dcb77643SDavid Penry // Furthermore, if a physical def/use pair is assigned to the same
2780dcb77643SDavid Penry // cycle, orderDependence does not guarantee def/use ordering, so that
2781dcb77643SDavid Penry // case should be considered invalid.  (The test checks for both
2782dcb77643SDavid Penry // earlier and same-cycle use to be more robust.)
2783254f889dSBrendon Cahoon bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
27843279943aSKazu Hirata   for (SUnit &SU : SSD->SUnits) {
2785254f889dSBrendon Cahoon     if (!SU.hasPhysRegDefs)
2786254f889dSBrendon Cahoon       continue;
2787254f889dSBrendon Cahoon     int StageDef = stageScheduled(&SU);
2788dcb77643SDavid Penry     int CycleDef = InstrToCycle[&SU];
2789254f889dSBrendon Cahoon     assert(StageDef != -1 && "Instruction should have been scheduled.");
2790254f889dSBrendon Cahoon     for (auto &SI : SU.Succs)
2791dcb77643SDavid Penry       if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
2792dcb77643SDavid Penry         if (Register::isPhysicalRegister(SI.getReg())) {
2793254f889dSBrendon Cahoon           if (stageScheduled(SI.getSUnit()) != StageDef)
2794254f889dSBrendon Cahoon             return false;
2795dcb77643SDavid Penry           if (InstrToCycle[SI.getSUnit()] <= CycleDef)
2796dcb77643SDavid Penry             return false;
2797dcb77643SDavid Penry         }
2798254f889dSBrendon Cahoon   }
2799254f889dSBrendon Cahoon   return true;
2800254f889dSBrendon Cahoon }
2801254f889dSBrendon Cahoon 
28024b8bcf00SRoorda, Jan-Willem /// A property of the node order in swing-modulo-scheduling is
28034b8bcf00SRoorda, Jan-Willem /// that for nodes outside circuits the following holds:
28044b8bcf00SRoorda, Jan-Willem /// none of them is scheduled after both a successor and a
28054b8bcf00SRoorda, Jan-Willem /// predecessor.
28064b8bcf00SRoorda, Jan-Willem /// The method below checks whether the property is met.
28074b8bcf00SRoorda, Jan-Willem /// If not, debug information is printed and statistics information updated.
28084b8bcf00SRoorda, Jan-Willem /// Note that we do not use an assert statement.
28094b8bcf00SRoorda, Jan-Willem /// The reason is that although an invalid node oder may prevent
28104b8bcf00SRoorda, Jan-Willem /// the pipeliner from finding a pipelined schedule for arbitrary II,
28114b8bcf00SRoorda, Jan-Willem /// it does not lead to the generation of incorrect code.
28124b8bcf00SRoorda, Jan-Willem void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
28134b8bcf00SRoorda, Jan-Willem 
28144b8bcf00SRoorda, Jan-Willem   // a sorted vector that maps each SUnit to its index in the NodeOrder
28154b8bcf00SRoorda, Jan-Willem   typedef std::pair<SUnit *, unsigned> UnitIndex;
28164b8bcf00SRoorda, Jan-Willem   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
28174b8bcf00SRoorda, Jan-Willem 
28184b8bcf00SRoorda, Jan-Willem   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
28194b8bcf00SRoorda, Jan-Willem     Indices.push_back(std::make_pair(NodeOrder[i], i));
28204b8bcf00SRoorda, Jan-Willem 
28214b8bcf00SRoorda, Jan-Willem   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
28224b8bcf00SRoorda, Jan-Willem     return std::get<0>(i1) < std::get<0>(i2);
28234b8bcf00SRoorda, Jan-Willem   };
28244b8bcf00SRoorda, Jan-Willem 
28254b8bcf00SRoorda, Jan-Willem   // sort, so that we can perform a binary search
28260cac726aSFangrui Song   llvm::sort(Indices, CompareKey);
28274b8bcf00SRoorda, Jan-Willem 
28284b8bcf00SRoorda, Jan-Willem   bool Valid = true;
2829febf70a9SDavid L Kreitzer   (void)Valid;
28304b8bcf00SRoorda, Jan-Willem   // for each SUnit in the NodeOrder, check whether
28314b8bcf00SRoorda, Jan-Willem   // it appears after both a successor and a predecessor
28324b8bcf00SRoorda, Jan-Willem   // of the SUnit. If this is the case, and the SUnit
28334b8bcf00SRoorda, Jan-Willem   // is not part of circuit, then the NodeOrder is not
28344b8bcf00SRoorda, Jan-Willem   // valid.
28354b8bcf00SRoorda, Jan-Willem   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
28364b8bcf00SRoorda, Jan-Willem     SUnit *SU = NodeOrder[i];
28374b8bcf00SRoorda, Jan-Willem     unsigned Index = i;
28384b8bcf00SRoorda, Jan-Willem 
28394b8bcf00SRoorda, Jan-Willem     bool PredBefore = false;
28404b8bcf00SRoorda, Jan-Willem     bool SuccBefore = false;
28414b8bcf00SRoorda, Jan-Willem 
28424b8bcf00SRoorda, Jan-Willem     SUnit *Succ;
28434b8bcf00SRoorda, Jan-Willem     SUnit *Pred;
2844febf70a9SDavid L Kreitzer     (void)Succ;
2845febf70a9SDavid L Kreitzer     (void)Pred;
28464b8bcf00SRoorda, Jan-Willem 
28474b8bcf00SRoorda, Jan-Willem     for (SDep &PredEdge : SU->Preds) {
28484b8bcf00SRoorda, Jan-Willem       SUnit *PredSU = PredEdge.getSUnit();
2849dc8de603SFangrui Song       unsigned PredIndex = std::get<1>(
2850dc8de603SFangrui Song           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
28514b8bcf00SRoorda, Jan-Willem       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
28524b8bcf00SRoorda, Jan-Willem         PredBefore = true;
28534b8bcf00SRoorda, Jan-Willem         Pred = PredSU;
28544b8bcf00SRoorda, Jan-Willem         break;
28554b8bcf00SRoorda, Jan-Willem       }
28564b8bcf00SRoorda, Jan-Willem     }
28574b8bcf00SRoorda, Jan-Willem 
28584b8bcf00SRoorda, Jan-Willem     for (SDep &SuccEdge : SU->Succs) {
28594b8bcf00SRoorda, Jan-Willem       SUnit *SuccSU = SuccEdge.getSUnit();
28601c884458SJinsong Ji       // Do not process a boundary node, it was not included in NodeOrder,
28611c884458SJinsong Ji       // hence not in Indices either, call to std::lower_bound() below will
28621c884458SJinsong Ji       // return Indices.end().
28631c884458SJinsong Ji       if (SuccSU->isBoundaryNode())
28641c884458SJinsong Ji         continue;
2865dc8de603SFangrui Song       unsigned SuccIndex = std::get<1>(
2866dc8de603SFangrui Song           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
28674b8bcf00SRoorda, Jan-Willem       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
28684b8bcf00SRoorda, Jan-Willem         SuccBefore = true;
28694b8bcf00SRoorda, Jan-Willem         Succ = SuccSU;
28704b8bcf00SRoorda, Jan-Willem         break;
28714b8bcf00SRoorda, Jan-Willem       }
28724b8bcf00SRoorda, Jan-Willem     }
28734b8bcf00SRoorda, Jan-Willem 
28744b8bcf00SRoorda, Jan-Willem     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
28754b8bcf00SRoorda, Jan-Willem       // instructions in circuits are allowed to be scheduled
28764b8bcf00SRoorda, Jan-Willem       // after both a successor and predecessor.
2877dc8de603SFangrui Song       bool InCircuit = llvm::any_of(
2878dc8de603SFangrui Song           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
28794b8bcf00SRoorda, Jan-Willem       if (InCircuit)
2880d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
28814b8bcf00SRoorda, Jan-Willem       else {
28824b8bcf00SRoorda, Jan-Willem         Valid = false;
28834b8bcf00SRoorda, Jan-Willem         NumNodeOrderIssues++;
2884d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Predecessor ";);
28854b8bcf00SRoorda, Jan-Willem       }
2886d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
2887d34e60caSNicola Zaghen                         << " are scheduled before node " << SU->NodeNum
2888d34e60caSNicola Zaghen                         << "\n";);
28894b8bcf00SRoorda, Jan-Willem     }
28904b8bcf00SRoorda, Jan-Willem   }
28914b8bcf00SRoorda, Jan-Willem 
2892d34e60caSNicola Zaghen   LLVM_DEBUG({
28934b8bcf00SRoorda, Jan-Willem     if (!Valid)
28944b8bcf00SRoorda, Jan-Willem       dbgs() << "Invalid node order found!\n";
28954b8bcf00SRoorda, Jan-Willem   });
28964b8bcf00SRoorda, Jan-Willem }
28974b8bcf00SRoorda, Jan-Willem 
28988f174ddeSKrzysztof Parzyszek /// Attempt to fix the degenerate cases when the instruction serialization
28998f174ddeSKrzysztof Parzyszek /// causes the register lifetimes to overlap. For example,
29008f174ddeSKrzysztof Parzyszek ///   p' = store_pi(p, b)
29018f174ddeSKrzysztof Parzyszek ///      = load p, offset
29028f174ddeSKrzysztof Parzyszek /// In this case p and p' overlap, which means that two registers are needed.
29038f174ddeSKrzysztof Parzyszek /// Instead, this function changes the load to use p' and updates the offset.
29048f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
29058f174ddeSKrzysztof Parzyszek   unsigned OverlapReg = 0;
29068f174ddeSKrzysztof Parzyszek   unsigned NewBaseReg = 0;
29078f174ddeSKrzysztof Parzyszek   for (SUnit *SU : Instrs) {
29088f174ddeSKrzysztof Parzyszek     MachineInstr *MI = SU->getInstr();
29098f174ddeSKrzysztof Parzyszek     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
29108f174ddeSKrzysztof Parzyszek       const MachineOperand &MO = MI->getOperand(i);
29118f174ddeSKrzysztof Parzyszek       // Look for an instruction that uses p. The instruction occurs in the
29128f174ddeSKrzysztof Parzyszek       // same cycle but occurs later in the serialized order.
29138f174ddeSKrzysztof Parzyszek       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
29148f174ddeSKrzysztof Parzyszek         // Check that the instruction appears in the InstrChanges structure,
29158f174ddeSKrzysztof Parzyszek         // which contains instructions that can have the offset updated.
29168f174ddeSKrzysztof Parzyszek         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
29178f174ddeSKrzysztof Parzyszek           InstrChanges.find(SU);
29188f174ddeSKrzysztof Parzyszek         if (It != InstrChanges.end()) {
29198f174ddeSKrzysztof Parzyszek           unsigned BasePos, OffsetPos;
29208f174ddeSKrzysztof Parzyszek           // Update the base register and adjust the offset.
29218f174ddeSKrzysztof Parzyszek           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
292212bdcab5SKrzysztof Parzyszek             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
292312bdcab5SKrzysztof Parzyszek             NewMI->getOperand(BasePos).setReg(NewBaseReg);
292412bdcab5SKrzysztof Parzyszek             int64_t NewOffset =
292512bdcab5SKrzysztof Parzyszek                 MI->getOperand(OffsetPos).getImm() - It->second.second;
292612bdcab5SKrzysztof Parzyszek             NewMI->getOperand(OffsetPos).setImm(NewOffset);
292712bdcab5SKrzysztof Parzyszek             SU->setInstr(NewMI);
292812bdcab5SKrzysztof Parzyszek             MISUnitMap[NewMI] = SU;
2929790a779fSJames Molloy             NewMIs[MI] = NewMI;
29308f174ddeSKrzysztof Parzyszek           }
29318f174ddeSKrzysztof Parzyszek         }
29328f174ddeSKrzysztof Parzyszek         OverlapReg = 0;
29338f174ddeSKrzysztof Parzyszek         NewBaseReg = 0;
29348f174ddeSKrzysztof Parzyszek         break;
29358f174ddeSKrzysztof Parzyszek       }
29368f174ddeSKrzysztof Parzyszek       // Look for an instruction of the form p' = op(p), which uses and defines
29378f174ddeSKrzysztof Parzyszek       // two virtual registers that get allocated to the same physical register.
29388f174ddeSKrzysztof Parzyszek       unsigned TiedUseIdx = 0;
29398f174ddeSKrzysztof Parzyszek       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
29408f174ddeSKrzysztof Parzyszek         // OverlapReg is p in the example above.
29418f174ddeSKrzysztof Parzyszek         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
29428f174ddeSKrzysztof Parzyszek         // NewBaseReg is p' in the example above.
29438f174ddeSKrzysztof Parzyszek         NewBaseReg = MI->getOperand(i).getReg();
29448f174ddeSKrzysztof Parzyszek         break;
29458f174ddeSKrzysztof Parzyszek       }
29468f174ddeSKrzysztof Parzyszek     }
29478f174ddeSKrzysztof Parzyszek   }
29488f174ddeSKrzysztof Parzyszek }
29498f174ddeSKrzysztof Parzyszek 
2950254f889dSBrendon Cahoon /// After the schedule has been formed, call this function to combine
2951254f889dSBrendon Cahoon /// the instructions from the different stages/cycles.  That is, this
2952254f889dSBrendon Cahoon /// function creates a schedule that represents a single iteration.
2953254f889dSBrendon Cahoon void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
2954254f889dSBrendon Cahoon   // Move all instructions to the first stage from later stages.
2955254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2956254f889dSBrendon Cahoon     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
2957254f889dSBrendon Cahoon          ++stage) {
2958254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs =
2959254f889dSBrendon Cahoon           ScheduledInstrs[cycle + (stage * InitiationInterval)];
2960bb6447a7SKazu Hirata       for (SUnit *SU : llvm::reverse(cycleInstrs))
2961bb6447a7SKazu Hirata         ScheduledInstrs[cycle].push_front(SU);
2962254f889dSBrendon Cahoon     }
2963254f889dSBrendon Cahoon   }
2964254f889dSBrendon Cahoon 
2965254f889dSBrendon Cahoon   // Erase all the elements in the later stages. Only one iteration should
2966254f889dSBrendon Cahoon   // remain in the scheduled list, and it contains all the instructions.
2967254f889dSBrendon Cahoon   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
2968254f889dSBrendon Cahoon     ScheduledInstrs.erase(cycle);
2969254f889dSBrendon Cahoon 
2970254f889dSBrendon Cahoon   // Change the registers in instruction as specified in the InstrChanges
2971254f889dSBrendon Cahoon   // map. We need to use the new registers to create the correct order.
2972ca2f5389SKazu Hirata   for (const SUnit &SU : SSD->SUnits)
2973ca2f5389SKazu Hirata     SSD->applyInstrChange(SU.getInstr(), *this);
2974254f889dSBrendon Cahoon 
2975254f889dSBrendon Cahoon   // Reorder the instructions in each cycle to fix and improve the
2976254f889dSBrendon Cahoon   // generated code.
2977254f889dSBrendon Cahoon   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
2978254f889dSBrendon Cahoon     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
2979f13bbf1dSKrzysztof Parzyszek     std::deque<SUnit *> newOrderPhi;
29803279943aSKazu Hirata     for (SUnit *SU : cycleInstrs) {
2981f13bbf1dSKrzysztof Parzyszek       if (SU->getInstr()->isPHI())
2982f13bbf1dSKrzysztof Parzyszek         newOrderPhi.push_back(SU);
2983254f889dSBrendon Cahoon     }
2984254f889dSBrendon Cahoon     std::deque<SUnit *> newOrderI;
29853279943aSKazu Hirata     for (SUnit *SU : cycleInstrs) {
2986f13bbf1dSKrzysztof Parzyszek       if (!SU->getInstr()->isPHI())
2987254f889dSBrendon Cahoon         orderDependence(SSD, SU, newOrderI);
2988254f889dSBrendon Cahoon     }
2989254f889dSBrendon Cahoon     // Replace the old order with the new order.
2990f13bbf1dSKrzysztof Parzyszek     cycleInstrs.swap(newOrderPhi);
29911e3ed091SKazu Hirata     llvm::append_range(cycleInstrs, newOrderI);
29928f174ddeSKrzysztof Parzyszek     SSD->fixupRegisterOverlaps(cycleInstrs);
2993254f889dSBrendon Cahoon   }
2994254f889dSBrendon Cahoon 
2995d34e60caSNicola Zaghen   LLVM_DEBUG(dump(););
2996254f889dSBrendon Cahoon }
2997254f889dSBrendon Cahoon 
2998fa2e3583SAdrian Prantl void NodeSet::print(raw_ostream &os) const {
2999fa2e3583SAdrian Prantl   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3000fa2e3583SAdrian Prantl      << " depth " << MaxDepth << " col " << Colocate << "\n";
3001fa2e3583SAdrian Prantl   for (const auto &I : Nodes)
3002fa2e3583SAdrian Prantl     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
3003fa2e3583SAdrian Prantl   os << "\n";
3004fa2e3583SAdrian Prantl }
3005fa2e3583SAdrian Prantl 
3006615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3007254f889dSBrendon Cahoon /// Print the schedule information to the given output.
3008254f889dSBrendon Cahoon void SMSchedule::print(raw_ostream &os) const {
3009254f889dSBrendon Cahoon   // Iterate over each cycle.
3010254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3011254f889dSBrendon Cahoon     // Iterate over each instruction in the cycle.
3012254f889dSBrendon Cahoon     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3013254f889dSBrendon Cahoon     for (SUnit *CI : cycleInstrs->second) {
3014254f889dSBrendon Cahoon       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3015254f889dSBrendon Cahoon       os << "(" << CI->NodeNum << ") ";
3016254f889dSBrendon Cahoon       CI->getInstr()->print(os);
3017254f889dSBrendon Cahoon       os << "\n";
3018254f889dSBrendon Cahoon     }
3019254f889dSBrendon Cahoon   }
3020254f889dSBrendon Cahoon }
3021254f889dSBrendon Cahoon 
3022254f889dSBrendon Cahoon /// Utility function used for debugging to print the schedule.
30238c209aa8SMatthias Braun LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3024fa2e3583SAdrian Prantl LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3025fa2e3583SAdrian Prantl 
30268c209aa8SMatthias Braun #endif
3027fa2e3583SAdrian Prantl 
3028f6cb3bcbSJinsong Ji void ResourceManager::initProcResourceVectors(
3029f6cb3bcbSJinsong Ji     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3030f6cb3bcbSJinsong Ji   unsigned ProcResourceID = 0;
3031fa2e3583SAdrian Prantl 
3032f6cb3bcbSJinsong Ji   // We currently limit the resource kinds to 64 and below so that we can use
3033f6cb3bcbSJinsong Ji   // uint64_t for Masks
3034f6cb3bcbSJinsong Ji   assert(SM.getNumProcResourceKinds() < 64 &&
3035f6cb3bcbSJinsong Ji          "Too many kinds of resources, unsupported");
3036f6cb3bcbSJinsong Ji   // Create a unique bitmask for every processor resource unit.
3037f6cb3bcbSJinsong Ji   // Skip resource at index 0, since it always references 'InvalidUnit'.
3038f6cb3bcbSJinsong Ji   Masks.resize(SM.getNumProcResourceKinds());
3039f6cb3bcbSJinsong Ji   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3040f6cb3bcbSJinsong Ji     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3041f6cb3bcbSJinsong Ji     if (Desc.SubUnitsIdxBegin)
3042f6cb3bcbSJinsong Ji       continue;
3043f6cb3bcbSJinsong Ji     Masks[I] = 1ULL << ProcResourceID;
3044f6cb3bcbSJinsong Ji     ProcResourceID++;
3045f6cb3bcbSJinsong Ji   }
3046f6cb3bcbSJinsong Ji   // Create a unique bitmask for every processor resource group.
3047f6cb3bcbSJinsong Ji   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3048f6cb3bcbSJinsong Ji     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3049f6cb3bcbSJinsong Ji     if (!Desc.SubUnitsIdxBegin)
3050f6cb3bcbSJinsong Ji       continue;
3051f6cb3bcbSJinsong Ji     Masks[I] = 1ULL << ProcResourceID;
3052f6cb3bcbSJinsong Ji     for (unsigned U = 0; U < Desc.NumUnits; ++U)
3053f6cb3bcbSJinsong Ji       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3054f6cb3bcbSJinsong Ji     ProcResourceID++;
3055f6cb3bcbSJinsong Ji   }
3056f6cb3bcbSJinsong Ji   LLVM_DEBUG({
3057ba43840bSJinsong Ji     if (SwpShowResMask) {
3058f6cb3bcbSJinsong Ji       dbgs() << "ProcResourceDesc:\n";
3059f6cb3bcbSJinsong Ji       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3060f6cb3bcbSJinsong Ji         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3061f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3062ba43840bSJinsong Ji                          ProcResource->Name, I, Masks[I],
3063ba43840bSJinsong Ji                          ProcResource->NumUnits);
3064f6cb3bcbSJinsong Ji       }
3065f6cb3bcbSJinsong Ji       dbgs() << " -----------------\n";
3066ba43840bSJinsong Ji     }
3067f6cb3bcbSJinsong Ji   });
3068f6cb3bcbSJinsong Ji }
3069f6cb3bcbSJinsong Ji 
3070f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3071f6cb3bcbSJinsong Ji 
3072ba43840bSJinsong Ji   LLVM_DEBUG({
3073ba43840bSJinsong Ji     if (SwpDebugResource)
3074ba43840bSJinsong Ji       dbgs() << "canReserveResources:\n";
3075ba43840bSJinsong Ji   });
3076f6cb3bcbSJinsong Ji   if (UseDFA)
3077f6cb3bcbSJinsong Ji     return DFAResources->canReserveResources(MID);
3078f6cb3bcbSJinsong Ji 
3079f6cb3bcbSJinsong Ji   unsigned InsnClass = MID->getSchedClass();
3080f6cb3bcbSJinsong Ji   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3081f6cb3bcbSJinsong Ji   if (!SCDesc->isValid()) {
3082f6cb3bcbSJinsong Ji     LLVM_DEBUG({
3083f6cb3bcbSJinsong Ji       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
308467c14d5cSThomas Preud'homme       dbgs() << "isPseudo:" << MID->isPseudo() << "\n";
3085f6cb3bcbSJinsong Ji     });
3086f6cb3bcbSJinsong Ji     return true;
3087f6cb3bcbSJinsong Ji   }
3088f6cb3bcbSJinsong Ji 
3089f6cb3bcbSJinsong Ji   const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
3090f6cb3bcbSJinsong Ji   const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
3091f6cb3bcbSJinsong Ji   for (; I != E; ++I) {
3092f6cb3bcbSJinsong Ji     if (!I->Cycles)
3093f6cb3bcbSJinsong Ji       continue;
3094f6cb3bcbSJinsong Ji     const MCProcResourceDesc *ProcResource =
3095f6cb3bcbSJinsong Ji         SM.getProcResource(I->ProcResourceIdx);
3096f6cb3bcbSJinsong Ji     unsigned NumUnits = ProcResource->NumUnits;
3097f6cb3bcbSJinsong Ji     LLVM_DEBUG({
3098ba43840bSJinsong Ji       if (SwpDebugResource)
3099f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3100f6cb3bcbSJinsong Ji                          ProcResource->Name, I->ProcResourceIdx,
3101f6cb3bcbSJinsong Ji                          ProcResourceCount[I->ProcResourceIdx], NumUnits,
3102f6cb3bcbSJinsong Ji                          I->Cycles);
3103f6cb3bcbSJinsong Ji     });
3104f6cb3bcbSJinsong Ji     if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
3105f6cb3bcbSJinsong Ji       return false;
3106f6cb3bcbSJinsong Ji   }
3107ba43840bSJinsong Ji   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
3108f6cb3bcbSJinsong Ji   return true;
3109f6cb3bcbSJinsong Ji }
3110f6cb3bcbSJinsong Ji 
3111f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MCInstrDesc *MID) {
3112ba43840bSJinsong Ji   LLVM_DEBUG({
3113ba43840bSJinsong Ji     if (SwpDebugResource)
3114ba43840bSJinsong Ji       dbgs() << "reserveResources:\n";
3115ba43840bSJinsong Ji   });
3116f6cb3bcbSJinsong Ji   if (UseDFA)
3117f6cb3bcbSJinsong Ji     return DFAResources->reserveResources(MID);
3118f6cb3bcbSJinsong Ji 
3119f6cb3bcbSJinsong Ji   unsigned InsnClass = MID->getSchedClass();
3120f6cb3bcbSJinsong Ji   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3121f6cb3bcbSJinsong Ji   if (!SCDesc->isValid()) {
3122f6cb3bcbSJinsong Ji     LLVM_DEBUG({
3123f6cb3bcbSJinsong Ji       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
312467c14d5cSThomas Preud'homme       dbgs() << "isPseudo:" << MID->isPseudo() << "\n";
3125f6cb3bcbSJinsong Ji     });
3126f6cb3bcbSJinsong Ji     return;
3127f6cb3bcbSJinsong Ji   }
3128f6cb3bcbSJinsong Ji   for (const MCWriteProcResEntry &PRE :
3129f6cb3bcbSJinsong Ji        make_range(STI->getWriteProcResBegin(SCDesc),
3130f6cb3bcbSJinsong Ji                   STI->getWriteProcResEnd(SCDesc))) {
3131f6cb3bcbSJinsong Ji     if (!PRE.Cycles)
3132f6cb3bcbSJinsong Ji       continue;
3133f6cb3bcbSJinsong Ji     ++ProcResourceCount[PRE.ProcResourceIdx];
3134f6cb3bcbSJinsong Ji     LLVM_DEBUG({
3135ba43840bSJinsong Ji       if (SwpDebugResource) {
3136c77aff7eSRichard Trieu         const MCProcResourceDesc *ProcResource =
3137c77aff7eSRichard Trieu             SM.getProcResource(PRE.ProcResourceIdx);
3138f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3139f6cb3bcbSJinsong Ji                          ProcResource->Name, PRE.ProcResourceIdx,
3140e8698eadSRichard Trieu                          ProcResourceCount[PRE.ProcResourceIdx],
3141e8698eadSRichard Trieu                          ProcResource->NumUnits, PRE.Cycles);
3142ba43840bSJinsong Ji       }
3143f6cb3bcbSJinsong Ji     });
3144f6cb3bcbSJinsong Ji   }
3145ba43840bSJinsong Ji   LLVM_DEBUG({
3146ba43840bSJinsong Ji     if (SwpDebugResource)
3147ba43840bSJinsong Ji       dbgs() << "reserveResources: done!\n\n";
3148ba43840bSJinsong Ji   });
3149f6cb3bcbSJinsong Ji }
3150f6cb3bcbSJinsong Ji 
3151f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
3152f6cb3bcbSJinsong Ji   return canReserveResources(&MI.getDesc());
3153f6cb3bcbSJinsong Ji }
3154f6cb3bcbSJinsong Ji 
3155f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MachineInstr &MI) {
3156f6cb3bcbSJinsong Ji   return reserveResources(&MI.getDesc());
3157f6cb3bcbSJinsong Ji }
3158f6cb3bcbSJinsong Ji 
3159f6cb3bcbSJinsong Ji void ResourceManager::clearResources() {
3160f6cb3bcbSJinsong Ji   if (UseDFA)
3161f6cb3bcbSJinsong Ji     return DFAResources->clearResources();
3162f6cb3bcbSJinsong Ji   std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
3163f6cb3bcbSJinsong Ji }
3164