1790a779fSJames Molloy //===- ModuloSchedule.cpp - Software pipeline schedule expansion ----------===//
2790a779fSJames Molloy //
3790a779fSJames Molloy // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4790a779fSJames Molloy // See https://llvm.org/LICENSE.txt for license information.
5790a779fSJames Molloy // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6790a779fSJames Molloy //
7790a779fSJames Molloy //===----------------------------------------------------------------------===//
8790a779fSJames Molloy 
9790a779fSJames Molloy #include "llvm/CodeGen/ModuloSchedule.h"
10*93549957SJames Molloy #include "llvm/Support/raw_ostream.h"
11*93549957SJames Molloy #include "llvm/ADT/StringExtras.h"
12790a779fSJames Molloy #include "llvm/CodeGen/LiveIntervals.h"
13790a779fSJames Molloy #include "llvm/CodeGen/MachineInstrBuilder.h"
14790a779fSJames Molloy #include "llvm/CodeGen/TargetInstrInfo.h"
15*93549957SJames Molloy #include "llvm/MC/MCContext.h"
16790a779fSJames Molloy #include "llvm/Support/Debug.h"
17790a779fSJames Molloy 
18790a779fSJames Molloy #define DEBUG_TYPE "pipeliner"
19790a779fSJames Molloy using namespace llvm;
20790a779fSJames Molloy 
21*93549957SJames Molloy //===----------------------------------------------------------------------===//
22*93549957SJames Molloy // ModuloScheduleExpander implementation
23*93549957SJames Molloy //===----------------------------------------------------------------------===//
24*93549957SJames Molloy 
25790a779fSJames Molloy /// Return the register values for  the operands of a Phi instruction.
26790a779fSJames Molloy /// This function assume the instruction is a Phi.
27790a779fSJames Molloy static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
28790a779fSJames Molloy                        unsigned &InitVal, unsigned &LoopVal) {
29790a779fSJames Molloy   assert(Phi.isPHI() && "Expecting a Phi.");
30790a779fSJames Molloy 
31790a779fSJames Molloy   InitVal = 0;
32790a779fSJames Molloy   LoopVal = 0;
33790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
34790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() != Loop)
35790a779fSJames Molloy       InitVal = Phi.getOperand(i).getReg();
36790a779fSJames Molloy     else
37790a779fSJames Molloy       LoopVal = Phi.getOperand(i).getReg();
38790a779fSJames Molloy 
39790a779fSJames Molloy   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
40790a779fSJames Molloy }
41790a779fSJames Molloy 
42790a779fSJames Molloy /// Return the Phi register value that comes from the incoming block.
43790a779fSJames Molloy static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
44790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
45790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
46790a779fSJames Molloy       return Phi.getOperand(i).getReg();
47790a779fSJames Molloy   return 0;
48790a779fSJames Molloy }
49790a779fSJames Molloy 
50790a779fSJames Molloy /// Return the Phi register value that comes the loop block.
51790a779fSJames Molloy static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
52790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
53790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
54790a779fSJames Molloy       return Phi.getOperand(i).getReg();
55790a779fSJames Molloy   return 0;
56790a779fSJames Molloy }
57790a779fSJames Molloy 
58790a779fSJames Molloy void ModuloScheduleExpander::expand() {
59790a779fSJames Molloy   BB = Schedule.getLoop()->getTopBlock();
60790a779fSJames Molloy   Preheader = *BB->pred_begin();
61790a779fSJames Molloy   if (Preheader == BB)
62790a779fSJames Molloy     Preheader = *std::next(BB->pred_begin());
63790a779fSJames Molloy 
64790a779fSJames Molloy   // Iterate over the definitions in each instruction, and compute the
65790a779fSJames Molloy   // stage difference for each use.  Keep the maximum value.
66790a779fSJames Molloy   for (MachineInstr *MI : Schedule.getInstructions()) {
67790a779fSJames Molloy     int DefStage = Schedule.getStage(MI);
68790a779fSJames Molloy     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
69790a779fSJames Molloy       MachineOperand &Op = MI->getOperand(i);
70790a779fSJames Molloy       if (!Op.isReg() || !Op.isDef())
71790a779fSJames Molloy         continue;
72790a779fSJames Molloy 
73790a779fSJames Molloy       Register Reg = Op.getReg();
74790a779fSJames Molloy       unsigned MaxDiff = 0;
75790a779fSJames Molloy       bool PhiIsSwapped = false;
76790a779fSJames Molloy       for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
77790a779fSJames Molloy                                              EI = MRI.use_end();
78790a779fSJames Molloy            UI != EI; ++UI) {
79790a779fSJames Molloy         MachineOperand &UseOp = *UI;
80790a779fSJames Molloy         MachineInstr *UseMI = UseOp.getParent();
81790a779fSJames Molloy         int UseStage = Schedule.getStage(UseMI);
82790a779fSJames Molloy         unsigned Diff = 0;
83790a779fSJames Molloy         if (UseStage != -1 && UseStage >= DefStage)
84790a779fSJames Molloy           Diff = UseStage - DefStage;
85790a779fSJames Molloy         if (MI->isPHI()) {
86790a779fSJames Molloy           if (isLoopCarried(*MI))
87790a779fSJames Molloy             ++Diff;
88790a779fSJames Molloy           else
89790a779fSJames Molloy             PhiIsSwapped = true;
90790a779fSJames Molloy         }
91790a779fSJames Molloy         MaxDiff = std::max(Diff, MaxDiff);
92790a779fSJames Molloy       }
93790a779fSJames Molloy       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
94790a779fSJames Molloy     }
95790a779fSJames Molloy   }
96790a779fSJames Molloy 
97790a779fSJames Molloy   generatePipelinedLoop();
98790a779fSJames Molloy }
99790a779fSJames Molloy 
100790a779fSJames Molloy void ModuloScheduleExpander::generatePipelinedLoop() {
101790a779fSJames Molloy   // Create a new basic block for the kernel and add it to the CFG.
102790a779fSJames Molloy   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
103790a779fSJames Molloy 
104790a779fSJames Molloy   unsigned MaxStageCount = Schedule.getNumStages() - 1;
105790a779fSJames Molloy 
106790a779fSJames Molloy   // Remember the registers that are used in different stages. The index is
107790a779fSJames Molloy   // the iteration, or stage, that the instruction is scheduled in.  This is
108790a779fSJames Molloy   // a map between register names in the original block and the names created
109790a779fSJames Molloy   // in each stage of the pipelined loop.
110790a779fSJames Molloy   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
111790a779fSJames Molloy   InstrMapTy InstrMap;
112790a779fSJames Molloy 
113790a779fSJames Molloy   SmallVector<MachineBasicBlock *, 4> PrologBBs;
114790a779fSJames Molloy 
115790a779fSJames Molloy   // Generate the prolog instructions that set up the pipeline.
116790a779fSJames Molloy   generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
117790a779fSJames Molloy   MF.insert(BB->getIterator(), KernelBB);
118790a779fSJames Molloy 
119790a779fSJames Molloy   // Rearrange the instructions to generate the new, pipelined loop,
120790a779fSJames Molloy   // and update register names as needed.
121790a779fSJames Molloy   for (MachineInstr *CI : Schedule.getInstructions()) {
122790a779fSJames Molloy     if (CI->isPHI())
123790a779fSJames Molloy       continue;
124790a779fSJames Molloy     unsigned StageNum = Schedule.getStage(CI);
125790a779fSJames Molloy     MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
126790a779fSJames Molloy     updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
127790a779fSJames Molloy     KernelBB->push_back(NewMI);
128790a779fSJames Molloy     InstrMap[NewMI] = CI;
129790a779fSJames Molloy   }
130790a779fSJames Molloy 
131790a779fSJames Molloy   // Copy any terminator instructions to the new kernel, and update
132790a779fSJames Molloy   // names as needed.
133790a779fSJames Molloy   for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
134790a779fSJames Molloy                                    E = BB->instr_end();
135790a779fSJames Molloy        I != E; ++I) {
136790a779fSJames Molloy     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
137790a779fSJames Molloy     updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
138790a779fSJames Molloy     KernelBB->push_back(NewMI);
139790a779fSJames Molloy     InstrMap[NewMI] = &*I;
140790a779fSJames Molloy   }
141790a779fSJames Molloy 
142790a779fSJames Molloy   KernelBB->transferSuccessors(BB);
143790a779fSJames Molloy   KernelBB->replaceSuccessor(BB, KernelBB);
144790a779fSJames Molloy 
145790a779fSJames Molloy   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
146790a779fSJames Molloy                        InstrMap, MaxStageCount, MaxStageCount, false);
147790a779fSJames Molloy   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, InstrMap,
148790a779fSJames Molloy                MaxStageCount, MaxStageCount, false);
149790a779fSJames Molloy 
150790a779fSJames Molloy   LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
151790a779fSJames Molloy 
152790a779fSJames Molloy   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
153790a779fSJames Molloy   // Generate the epilog instructions to complete the pipeline.
154790a779fSJames Molloy   generateEpilog(MaxStageCount, KernelBB, VRMap, EpilogBBs, PrologBBs);
155790a779fSJames Molloy 
156790a779fSJames Molloy   // We need this step because the register allocation doesn't handle some
157790a779fSJames Molloy   // situations well, so we insert copies to help out.
158790a779fSJames Molloy   splitLifetimes(KernelBB, EpilogBBs);
159790a779fSJames Molloy 
160790a779fSJames Molloy   // Remove dead instructions due to loop induction variables.
161790a779fSJames Molloy   removeDeadInstructions(KernelBB, EpilogBBs);
162790a779fSJames Molloy 
163790a779fSJames Molloy   // Add branches between prolog and epilog blocks.
164790a779fSJames Molloy   addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
165790a779fSJames Molloy 
166790a779fSJames Molloy   // Remove the original loop since it's no longer referenced.
167790a779fSJames Molloy   for (auto &I : *BB)
168790a779fSJames Molloy     LIS.RemoveMachineInstrFromMaps(I);
169790a779fSJames Molloy   BB->clear();
170790a779fSJames Molloy   BB->eraseFromParent();
171790a779fSJames Molloy 
172790a779fSJames Molloy   delete[] VRMap;
173790a779fSJames Molloy }
174790a779fSJames Molloy 
175790a779fSJames Molloy /// Generate the pipeline prolog code.
176790a779fSJames Molloy void ModuloScheduleExpander::generateProlog(unsigned LastStage,
177790a779fSJames Molloy                                             MachineBasicBlock *KernelBB,
178790a779fSJames Molloy                                             ValueMapTy *VRMap,
179790a779fSJames Molloy                                             MBBVectorTy &PrologBBs) {
180790a779fSJames Molloy   MachineBasicBlock *PredBB = Preheader;
181790a779fSJames Molloy   InstrMapTy InstrMap;
182790a779fSJames Molloy 
183790a779fSJames Molloy   // Generate a basic block for each stage, not including the last stage,
184790a779fSJames Molloy   // which will be generated in the kernel. Each basic block may contain
185790a779fSJames Molloy   // instructions from multiple stages/iterations.
186790a779fSJames Molloy   for (unsigned i = 0; i < LastStage; ++i) {
187790a779fSJames Molloy     // Create and insert the prolog basic block prior to the original loop
188790a779fSJames Molloy     // basic block.  The original loop is removed later.
189790a779fSJames Molloy     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
190790a779fSJames Molloy     PrologBBs.push_back(NewBB);
191790a779fSJames Molloy     MF.insert(BB->getIterator(), NewBB);
192790a779fSJames Molloy     NewBB->transferSuccessors(PredBB);
193790a779fSJames Molloy     PredBB->addSuccessor(NewBB);
194790a779fSJames Molloy     PredBB = NewBB;
195790a779fSJames Molloy 
196790a779fSJames Molloy     // Generate instructions for each appropriate stage. Process instructions
197790a779fSJames Molloy     // in original program order.
198790a779fSJames Molloy     for (int StageNum = i; StageNum >= 0; --StageNum) {
199790a779fSJames Molloy       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
200790a779fSJames Molloy                                        BBE = BB->getFirstTerminator();
201790a779fSJames Molloy            BBI != BBE; ++BBI) {
202790a779fSJames Molloy         if (Schedule.getStage(&*BBI) == StageNum) {
203790a779fSJames Molloy           if (BBI->isPHI())
204790a779fSJames Molloy             continue;
205790a779fSJames Molloy           MachineInstr *NewMI =
206790a779fSJames Molloy               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
207790a779fSJames Molloy           updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
208790a779fSJames Molloy           NewBB->push_back(NewMI);
209790a779fSJames Molloy           InstrMap[NewMI] = &*BBI;
210790a779fSJames Molloy         }
211790a779fSJames Molloy       }
212790a779fSJames Molloy     }
213790a779fSJames Molloy     rewritePhiValues(NewBB, i, VRMap, InstrMap);
214790a779fSJames Molloy     LLVM_DEBUG({
215790a779fSJames Molloy       dbgs() << "prolog:\n";
216790a779fSJames Molloy       NewBB->dump();
217790a779fSJames Molloy     });
218790a779fSJames Molloy   }
219790a779fSJames Molloy 
220790a779fSJames Molloy   PredBB->replaceSuccessor(BB, KernelBB);
221790a779fSJames Molloy 
222790a779fSJames Molloy   // Check if we need to remove the branch from the preheader to the original
223790a779fSJames Molloy   // loop, and replace it with a branch to the new loop.
224790a779fSJames Molloy   unsigned numBranches = TII->removeBranch(*Preheader);
225790a779fSJames Molloy   if (numBranches) {
226790a779fSJames Molloy     SmallVector<MachineOperand, 0> Cond;
227790a779fSJames Molloy     TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
228790a779fSJames Molloy   }
229790a779fSJames Molloy }
230790a779fSJames Molloy 
231790a779fSJames Molloy /// Generate the pipeline epilog code. The epilog code finishes the iterations
232790a779fSJames Molloy /// that were started in either the prolog or the kernel.  We create a basic
233790a779fSJames Molloy /// block for each stage that needs to complete.
234790a779fSJames Molloy void ModuloScheduleExpander::generateEpilog(unsigned LastStage,
235790a779fSJames Molloy                                             MachineBasicBlock *KernelBB,
236790a779fSJames Molloy                                             ValueMapTy *VRMap,
237790a779fSJames Molloy                                             MBBVectorTy &EpilogBBs,
238790a779fSJames Molloy                                             MBBVectorTy &PrologBBs) {
239790a779fSJames Molloy   // We need to change the branch from the kernel to the first epilog block, so
240790a779fSJames Molloy   // this call to analyze branch uses the kernel rather than the original BB.
241790a779fSJames Molloy   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
242790a779fSJames Molloy   SmallVector<MachineOperand, 4> Cond;
243790a779fSJames Molloy   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
244790a779fSJames Molloy   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
245790a779fSJames Molloy   if (checkBranch)
246790a779fSJames Molloy     return;
247790a779fSJames Molloy 
248790a779fSJames Molloy   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
249790a779fSJames Molloy   if (*LoopExitI == KernelBB)
250790a779fSJames Molloy     ++LoopExitI;
251790a779fSJames Molloy   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
252790a779fSJames Molloy   MachineBasicBlock *LoopExitBB = *LoopExitI;
253790a779fSJames Molloy 
254790a779fSJames Molloy   MachineBasicBlock *PredBB = KernelBB;
255790a779fSJames Molloy   MachineBasicBlock *EpilogStart = LoopExitBB;
256790a779fSJames Molloy   InstrMapTy InstrMap;
257790a779fSJames Molloy 
258790a779fSJames Molloy   // Generate a basic block for each stage, not including the last stage,
259790a779fSJames Molloy   // which was generated for the kernel.  Each basic block may contain
260790a779fSJames Molloy   // instructions from multiple stages/iterations.
261790a779fSJames Molloy   int EpilogStage = LastStage + 1;
262790a779fSJames Molloy   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
263790a779fSJames Molloy     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
264790a779fSJames Molloy     EpilogBBs.push_back(NewBB);
265790a779fSJames Molloy     MF.insert(BB->getIterator(), NewBB);
266790a779fSJames Molloy 
267790a779fSJames Molloy     PredBB->replaceSuccessor(LoopExitBB, NewBB);
268790a779fSJames Molloy     NewBB->addSuccessor(LoopExitBB);
269790a779fSJames Molloy 
270790a779fSJames Molloy     if (EpilogStart == LoopExitBB)
271790a779fSJames Molloy       EpilogStart = NewBB;
272790a779fSJames Molloy 
273790a779fSJames Molloy     // Add instructions to the epilog depending on the current block.
274790a779fSJames Molloy     // Process instructions in original program order.
275790a779fSJames Molloy     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
276790a779fSJames Molloy       for (auto &BBI : *BB) {
277790a779fSJames Molloy         if (BBI.isPHI())
278790a779fSJames Molloy           continue;
279790a779fSJames Molloy         MachineInstr *In = &BBI;
280790a779fSJames Molloy         if ((unsigned)Schedule.getStage(In) == StageNum) {
281790a779fSJames Molloy           // Instructions with memoperands in the epilog are updated with
282790a779fSJames Molloy           // conservative values.
283790a779fSJames Molloy           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
284790a779fSJames Molloy           updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
285790a779fSJames Molloy           NewBB->push_back(NewMI);
286790a779fSJames Molloy           InstrMap[NewMI] = In;
287790a779fSJames Molloy         }
288790a779fSJames Molloy       }
289790a779fSJames Molloy     }
290790a779fSJames Molloy     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
291790a779fSJames Molloy                          InstrMap, LastStage, EpilogStage, i == 1);
292790a779fSJames Molloy     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, InstrMap,
293790a779fSJames Molloy                  LastStage, EpilogStage, i == 1);
294790a779fSJames Molloy     PredBB = NewBB;
295790a779fSJames Molloy 
296790a779fSJames Molloy     LLVM_DEBUG({
297790a779fSJames Molloy       dbgs() << "epilog:\n";
298790a779fSJames Molloy       NewBB->dump();
299790a779fSJames Molloy     });
300790a779fSJames Molloy   }
301790a779fSJames Molloy 
302790a779fSJames Molloy   // Fix any Phi nodes in the loop exit block.
303790a779fSJames Molloy   LoopExitBB->replacePhiUsesWith(BB, PredBB);
304790a779fSJames Molloy 
305790a779fSJames Molloy   // Create a branch to the new epilog from the kernel.
306790a779fSJames Molloy   // Remove the original branch and add a new branch to the epilog.
307790a779fSJames Molloy   TII->removeBranch(*KernelBB);
308790a779fSJames Molloy   TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
309790a779fSJames Molloy   // Add a branch to the loop exit.
310790a779fSJames Molloy   if (EpilogBBs.size() > 0) {
311790a779fSJames Molloy     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
312790a779fSJames Molloy     SmallVector<MachineOperand, 4> Cond1;
313790a779fSJames Molloy     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
314790a779fSJames Molloy   }
315790a779fSJames Molloy }
316790a779fSJames Molloy 
317790a779fSJames Molloy /// Replace all uses of FromReg that appear outside the specified
318790a779fSJames Molloy /// basic block with ToReg.
319790a779fSJames Molloy static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
320790a779fSJames Molloy                                     MachineBasicBlock *MBB,
321790a779fSJames Molloy                                     MachineRegisterInfo &MRI,
322790a779fSJames Molloy                                     LiveIntervals &LIS) {
323790a779fSJames Molloy   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
324790a779fSJames Molloy                                          E = MRI.use_end();
325790a779fSJames Molloy        I != E;) {
326790a779fSJames Molloy     MachineOperand &O = *I;
327790a779fSJames Molloy     ++I;
328790a779fSJames Molloy     if (O.getParent()->getParent() != MBB)
329790a779fSJames Molloy       O.setReg(ToReg);
330790a779fSJames Molloy   }
331790a779fSJames Molloy   if (!LIS.hasInterval(ToReg))
332790a779fSJames Molloy     LIS.createEmptyInterval(ToReg);
333790a779fSJames Molloy }
334790a779fSJames Molloy 
335790a779fSJames Molloy /// Return true if the register has a use that occurs outside the
336790a779fSJames Molloy /// specified loop.
337790a779fSJames Molloy static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
338790a779fSJames Molloy                             MachineRegisterInfo &MRI) {
339790a779fSJames Molloy   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
340790a779fSJames Molloy                                          E = MRI.use_end();
341790a779fSJames Molloy        I != E; ++I)
342790a779fSJames Molloy     if (I->getParent()->getParent() != BB)
343790a779fSJames Molloy       return true;
344790a779fSJames Molloy   return false;
345790a779fSJames Molloy }
346790a779fSJames Molloy 
347790a779fSJames Molloy /// Generate Phis for the specific block in the generated pipelined code.
348790a779fSJames Molloy /// This function looks at the Phis from the original code to guide the
349790a779fSJames Molloy /// creation of new Phis.
350790a779fSJames Molloy void ModuloScheduleExpander::generateExistingPhis(
351790a779fSJames Molloy     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
352790a779fSJames Molloy     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
353790a779fSJames Molloy     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
354790a779fSJames Molloy   // Compute the stage number for the initial value of the Phi, which
355790a779fSJames Molloy   // comes from the prolog. The prolog to use depends on to which kernel/
356790a779fSJames Molloy   // epilog that we're adding the Phi.
357790a779fSJames Molloy   unsigned PrologStage = 0;
358790a779fSJames Molloy   unsigned PrevStage = 0;
359790a779fSJames Molloy   bool InKernel = (LastStageNum == CurStageNum);
360790a779fSJames Molloy   if (InKernel) {
361790a779fSJames Molloy     PrologStage = LastStageNum - 1;
362790a779fSJames Molloy     PrevStage = CurStageNum;
363790a779fSJames Molloy   } else {
364790a779fSJames Molloy     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
365790a779fSJames Molloy     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
366790a779fSJames Molloy   }
367790a779fSJames Molloy 
368790a779fSJames Molloy   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
369790a779fSJames Molloy                                    BBE = BB->getFirstNonPHI();
370790a779fSJames Molloy        BBI != BBE; ++BBI) {
371790a779fSJames Molloy     Register Def = BBI->getOperand(0).getReg();
372790a779fSJames Molloy 
373790a779fSJames Molloy     unsigned InitVal = 0;
374790a779fSJames Molloy     unsigned LoopVal = 0;
375790a779fSJames Molloy     getPhiRegs(*BBI, BB, InitVal, LoopVal);
376790a779fSJames Molloy 
377790a779fSJames Molloy     unsigned PhiOp1 = 0;
378790a779fSJames Molloy     // The Phi value from the loop body typically is defined in the loop, but
379790a779fSJames Molloy     // not always. So, we need to check if the value is defined in the loop.
380790a779fSJames Molloy     unsigned PhiOp2 = LoopVal;
381790a779fSJames Molloy     if (VRMap[LastStageNum].count(LoopVal))
382790a779fSJames Molloy       PhiOp2 = VRMap[LastStageNum][LoopVal];
383790a779fSJames Molloy 
384790a779fSJames Molloy     int StageScheduled = Schedule.getStage(&*BBI);
385790a779fSJames Molloy     int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
386790a779fSJames Molloy     unsigned NumStages = getStagesForReg(Def, CurStageNum);
387790a779fSJames Molloy     if (NumStages == 0) {
388790a779fSJames Molloy       // We don't need to generate a Phi anymore, but we need to rename any uses
389790a779fSJames Molloy       // of the Phi value.
390790a779fSJames Molloy       unsigned NewReg = VRMap[PrevStage][LoopVal];
391790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
392790a779fSJames Molloy                             InitVal, NewReg);
393790a779fSJames Molloy       if (VRMap[CurStageNum].count(LoopVal))
394790a779fSJames Molloy         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
395790a779fSJames Molloy     }
396790a779fSJames Molloy     // Adjust the number of Phis needed depending on the number of prologs left,
397790a779fSJames Molloy     // and the distance from where the Phi is first scheduled. The number of
398790a779fSJames Molloy     // Phis cannot exceed the number of prolog stages. Each stage can
399790a779fSJames Molloy     // potentially define two values.
400790a779fSJames Molloy     unsigned MaxPhis = PrologStage + 2;
401790a779fSJames Molloy     if (!InKernel && (int)PrologStage <= LoopValStage)
402790a779fSJames Molloy       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
403790a779fSJames Molloy     unsigned NumPhis = std::min(NumStages, MaxPhis);
404790a779fSJames Molloy 
405790a779fSJames Molloy     unsigned NewReg = 0;
406790a779fSJames Molloy     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
407790a779fSJames Molloy     // In the epilog, we may need to look back one stage to get the correct
408790a779fSJames Molloy     // Phi name because the epilog and prolog blocks execute the same stage.
409790a779fSJames Molloy     // The correct name is from the previous block only when the Phi has
410790a779fSJames Molloy     // been completely scheduled prior to the epilog, and Phi value is not
411790a779fSJames Molloy     // needed in multiple stages.
412790a779fSJames Molloy     int StageDiff = 0;
413790a779fSJames Molloy     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
414790a779fSJames Molloy         NumPhis == 1)
415790a779fSJames Molloy       StageDiff = 1;
416790a779fSJames Molloy     // Adjust the computations below when the phi and the loop definition
417790a779fSJames Molloy     // are scheduled in different stages.
418790a779fSJames Molloy     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
419790a779fSJames Molloy       StageDiff = StageScheduled - LoopValStage;
420790a779fSJames Molloy     for (unsigned np = 0; np < NumPhis; ++np) {
421790a779fSJames Molloy       // If the Phi hasn't been scheduled, then use the initial Phi operand
422790a779fSJames Molloy       // value. Otherwise, use the scheduled version of the instruction. This
423790a779fSJames Molloy       // is a little complicated when a Phi references another Phi.
424790a779fSJames Molloy       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
425790a779fSJames Molloy         PhiOp1 = InitVal;
426790a779fSJames Molloy       // Check if the Phi has already been scheduled in a prolog stage.
427790a779fSJames Molloy       else if (PrologStage >= AccessStage + StageDiff + np &&
428790a779fSJames Molloy                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
429790a779fSJames Molloy         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
430790a779fSJames Molloy       // Check if the Phi has already been scheduled, but the loop instruction
431790a779fSJames Molloy       // is either another Phi, or doesn't occur in the loop.
432790a779fSJames Molloy       else if (PrologStage >= AccessStage + StageDiff + np) {
433790a779fSJames Molloy         // If the Phi references another Phi, we need to examine the other
434790a779fSJames Molloy         // Phi to get the correct value.
435790a779fSJames Molloy         PhiOp1 = LoopVal;
436790a779fSJames Molloy         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
437790a779fSJames Molloy         int Indirects = 1;
438790a779fSJames Molloy         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
439790a779fSJames Molloy           int PhiStage = Schedule.getStage(InstOp1);
440790a779fSJames Molloy           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
441790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, BB);
442790a779fSJames Molloy           else
443790a779fSJames Molloy             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
444790a779fSJames Molloy           InstOp1 = MRI.getVRegDef(PhiOp1);
445790a779fSJames Molloy           int PhiOpStage = Schedule.getStage(InstOp1);
446790a779fSJames Molloy           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
447790a779fSJames Molloy           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
448790a779fSJames Molloy               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
449790a779fSJames Molloy             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
450790a779fSJames Molloy             break;
451790a779fSJames Molloy           }
452790a779fSJames Molloy           ++Indirects;
453790a779fSJames Molloy         }
454790a779fSJames Molloy       } else
455790a779fSJames Molloy         PhiOp1 = InitVal;
456790a779fSJames Molloy       // If this references a generated Phi in the kernel, get the Phi operand
457790a779fSJames Molloy       // from the incoming block.
458790a779fSJames Molloy       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
459790a779fSJames Molloy         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
460790a779fSJames Molloy           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
461790a779fSJames Molloy 
462790a779fSJames Molloy       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
463790a779fSJames Molloy       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
464790a779fSJames Molloy       // In the epilog, a map lookup is needed to get the value from the kernel,
465790a779fSJames Molloy       // or previous epilog block. How is does this depends on if the
466790a779fSJames Molloy       // instruction is scheduled in the previous block.
467790a779fSJames Molloy       if (!InKernel) {
468790a779fSJames Molloy         int StageDiffAdj = 0;
469790a779fSJames Molloy         if (LoopValStage != -1 && StageScheduled > LoopValStage)
470790a779fSJames Molloy           StageDiffAdj = StageScheduled - LoopValStage;
471790a779fSJames Molloy         // Use the loop value defined in the kernel, unless the kernel
472790a779fSJames Molloy         // contains the last definition of the Phi.
473790a779fSJames Molloy         if (np == 0 && PrevStage == LastStageNum &&
474790a779fSJames Molloy             (StageScheduled != 0 || LoopValStage != 0) &&
475790a779fSJames Molloy             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
476790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
477790a779fSJames Molloy         // Use the value defined by the Phi. We add one because we switch
478790a779fSJames Molloy         // from looking at the loop value to the Phi definition.
479790a779fSJames Molloy         else if (np > 0 && PrevStage == LastStageNum &&
480790a779fSJames Molloy                  VRMap[PrevStage - np + 1].count(Def))
481790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np + 1][Def];
482790a779fSJames Molloy         // Use the loop value defined in the kernel.
483790a779fSJames Molloy         else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
484790a779fSJames Molloy                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
485790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
486790a779fSJames Molloy         // Use the value defined by the Phi, unless we're generating the first
487790a779fSJames Molloy         // epilog and the Phi refers to a Phi in a different stage.
488790a779fSJames Molloy         else if (VRMap[PrevStage - np].count(Def) &&
489790a779fSJames Molloy                  (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
490790a779fSJames Molloy                   (LoopValStage == StageScheduled)))
491790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np][Def];
492790a779fSJames Molloy       }
493790a779fSJames Molloy 
494790a779fSJames Molloy       // Check if we can reuse an existing Phi. This occurs when a Phi
495790a779fSJames Molloy       // references another Phi, and the other Phi is scheduled in an
496790a779fSJames Molloy       // earlier stage. We can try to reuse an existing Phi up until the last
497790a779fSJames Molloy       // stage of the current Phi.
498790a779fSJames Molloy       if (LoopDefIsPhi) {
499790a779fSJames Molloy         if (static_cast<int>(PrologStage - np) >= StageScheduled) {
500790a779fSJames Molloy           int LVNumStages = getStagesForPhi(LoopVal);
501790a779fSJames Molloy           int StageDiff = (StageScheduled - LoopValStage);
502790a779fSJames Molloy           LVNumStages -= StageDiff;
503790a779fSJames Molloy           // Make sure the loop value Phi has been processed already.
504790a779fSJames Molloy           if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
505790a779fSJames Molloy             NewReg = PhiOp2;
506790a779fSJames Molloy             unsigned ReuseStage = CurStageNum;
507790a779fSJames Molloy             if (isLoopCarried(*PhiInst))
508790a779fSJames Molloy               ReuseStage -= LVNumStages;
509790a779fSJames Molloy             // Check if the Phi to reuse has been generated yet. If not, then
510790a779fSJames Molloy             // there is nothing to reuse.
511790a779fSJames Molloy             if (VRMap[ReuseStage - np].count(LoopVal)) {
512790a779fSJames Molloy               NewReg = VRMap[ReuseStage - np][LoopVal];
513790a779fSJames Molloy 
514790a779fSJames Molloy               rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
515790a779fSJames Molloy                                     Def, NewReg);
516790a779fSJames Molloy               // Update the map with the new Phi name.
517790a779fSJames Molloy               VRMap[CurStageNum - np][Def] = NewReg;
518790a779fSJames Molloy               PhiOp2 = NewReg;
519790a779fSJames Molloy               if (VRMap[LastStageNum - np - 1].count(LoopVal))
520790a779fSJames Molloy                 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
521790a779fSJames Molloy 
522790a779fSJames Molloy               if (IsLast && np == NumPhis - 1)
523790a779fSJames Molloy                 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
524790a779fSJames Molloy               continue;
525790a779fSJames Molloy             }
526790a779fSJames Molloy           }
527790a779fSJames Molloy         }
528790a779fSJames Molloy         if (InKernel && StageDiff > 0 &&
529790a779fSJames Molloy             VRMap[CurStageNum - StageDiff - np].count(LoopVal))
530790a779fSJames Molloy           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
531790a779fSJames Molloy       }
532790a779fSJames Molloy 
533790a779fSJames Molloy       const TargetRegisterClass *RC = MRI.getRegClass(Def);
534790a779fSJames Molloy       NewReg = MRI.createVirtualRegister(RC);
535790a779fSJames Molloy 
536790a779fSJames Molloy       MachineInstrBuilder NewPhi =
537790a779fSJames Molloy           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
538790a779fSJames Molloy                   TII->get(TargetOpcode::PHI), NewReg);
539790a779fSJames Molloy       NewPhi.addReg(PhiOp1).addMBB(BB1);
540790a779fSJames Molloy       NewPhi.addReg(PhiOp2).addMBB(BB2);
541790a779fSJames Molloy       if (np == 0)
542790a779fSJames Molloy         InstrMap[NewPhi] = &*BBI;
543790a779fSJames Molloy 
544790a779fSJames Molloy       // We define the Phis after creating the new pipelined code, so
545790a779fSJames Molloy       // we need to rename the Phi values in scheduled instructions.
546790a779fSJames Molloy 
547790a779fSJames Molloy       unsigned PrevReg = 0;
548790a779fSJames Molloy       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
549790a779fSJames Molloy         PrevReg = VRMap[PrevStage - np][LoopVal];
550790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
551790a779fSJames Molloy                             NewReg, PrevReg);
552790a779fSJames Molloy       // If the Phi has been scheduled, use the new name for rewriting.
553790a779fSJames Molloy       if (VRMap[CurStageNum - np].count(Def)) {
554790a779fSJames Molloy         unsigned R = VRMap[CurStageNum - np][Def];
555790a779fSJames Molloy         rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
556790a779fSJames Molloy                               NewReg);
557790a779fSJames Molloy       }
558790a779fSJames Molloy 
559790a779fSJames Molloy       // Check if we need to rename any uses that occurs after the loop. The
560790a779fSJames Molloy       // register to replace depends on whether the Phi is scheduled in the
561790a779fSJames Molloy       // epilog.
562790a779fSJames Molloy       if (IsLast && np == NumPhis - 1)
563790a779fSJames Molloy         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
564790a779fSJames Molloy 
565790a779fSJames Molloy       // In the kernel, a dependent Phi uses the value from this Phi.
566790a779fSJames Molloy       if (InKernel)
567790a779fSJames Molloy         PhiOp2 = NewReg;
568790a779fSJames Molloy 
569790a779fSJames Molloy       // Update the map with the new Phi name.
570790a779fSJames Molloy       VRMap[CurStageNum - np][Def] = NewReg;
571790a779fSJames Molloy     }
572790a779fSJames Molloy 
573790a779fSJames Molloy     while (NumPhis++ < NumStages) {
574790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
575790a779fSJames Molloy                             NewReg, 0);
576790a779fSJames Molloy     }
577790a779fSJames Molloy 
578790a779fSJames Molloy     // Check if we need to rename a Phi that has been eliminated due to
579790a779fSJames Molloy     // scheduling.
580790a779fSJames Molloy     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
581790a779fSJames Molloy       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
582790a779fSJames Molloy   }
583790a779fSJames Molloy }
584790a779fSJames Molloy 
585790a779fSJames Molloy /// Generate Phis for the specified block in the generated pipelined code.
586790a779fSJames Molloy /// These are new Phis needed because the definition is scheduled after the
587790a779fSJames Molloy /// use in the pipelined sequence.
588790a779fSJames Molloy void ModuloScheduleExpander::generatePhis(
589790a779fSJames Molloy     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
590790a779fSJames Molloy     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
591790a779fSJames Molloy     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
592790a779fSJames Molloy   // Compute the stage number that contains the initial Phi value, and
593790a779fSJames Molloy   // the Phi from the previous stage.
594790a779fSJames Molloy   unsigned PrologStage = 0;
595790a779fSJames Molloy   unsigned PrevStage = 0;
596790a779fSJames Molloy   unsigned StageDiff = CurStageNum - LastStageNum;
597790a779fSJames Molloy   bool InKernel = (StageDiff == 0);
598790a779fSJames Molloy   if (InKernel) {
599790a779fSJames Molloy     PrologStage = LastStageNum - 1;
600790a779fSJames Molloy     PrevStage = CurStageNum;
601790a779fSJames Molloy   } else {
602790a779fSJames Molloy     PrologStage = LastStageNum - StageDiff;
603790a779fSJames Molloy     PrevStage = LastStageNum + StageDiff - 1;
604790a779fSJames Molloy   }
605790a779fSJames Molloy 
606790a779fSJames Molloy   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
607790a779fSJames Molloy                                    BBE = BB->instr_end();
608790a779fSJames Molloy        BBI != BBE; ++BBI) {
609790a779fSJames Molloy     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
610790a779fSJames Molloy       MachineOperand &MO = BBI->getOperand(i);
611790a779fSJames Molloy       if (!MO.isReg() || !MO.isDef() ||
612790a779fSJames Molloy           !Register::isVirtualRegister(MO.getReg()))
613790a779fSJames Molloy         continue;
614790a779fSJames Molloy 
615790a779fSJames Molloy       int StageScheduled = Schedule.getStage(&*BBI);
616790a779fSJames Molloy       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
617790a779fSJames Molloy       Register Def = MO.getReg();
618790a779fSJames Molloy       unsigned NumPhis = getStagesForReg(Def, CurStageNum);
619790a779fSJames Molloy       // An instruction scheduled in stage 0 and is used after the loop
620790a779fSJames Molloy       // requires a phi in the epilog for the last definition from either
621790a779fSJames Molloy       // the kernel or prolog.
622790a779fSJames Molloy       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
623790a779fSJames Molloy           hasUseAfterLoop(Def, BB, MRI))
624790a779fSJames Molloy         NumPhis = 1;
625790a779fSJames Molloy       if (!InKernel && (unsigned)StageScheduled > PrologStage)
626790a779fSJames Molloy         continue;
627790a779fSJames Molloy 
628790a779fSJames Molloy       unsigned PhiOp2 = VRMap[PrevStage][Def];
629790a779fSJames Molloy       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
630790a779fSJames Molloy         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
631790a779fSJames Molloy           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
632790a779fSJames Molloy       // The number of Phis can't exceed the number of prolog stages. The
633790a779fSJames Molloy       // prolog stage number is zero based.
634790a779fSJames Molloy       if (NumPhis > PrologStage + 1 - StageScheduled)
635790a779fSJames Molloy         NumPhis = PrologStage + 1 - StageScheduled;
636790a779fSJames Molloy       for (unsigned np = 0; np < NumPhis; ++np) {
637790a779fSJames Molloy         unsigned PhiOp1 = VRMap[PrologStage][Def];
638790a779fSJames Molloy         if (np <= PrologStage)
639790a779fSJames Molloy           PhiOp1 = VRMap[PrologStage - np][Def];
640790a779fSJames Molloy         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
641790a779fSJames Molloy           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
642790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
643790a779fSJames Molloy           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
644790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
645790a779fSJames Molloy         }
646790a779fSJames Molloy         if (!InKernel)
647790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np][Def];
648790a779fSJames Molloy 
649790a779fSJames Molloy         const TargetRegisterClass *RC = MRI.getRegClass(Def);
650790a779fSJames Molloy         Register NewReg = MRI.createVirtualRegister(RC);
651790a779fSJames Molloy 
652790a779fSJames Molloy         MachineInstrBuilder NewPhi =
653790a779fSJames Molloy             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
654790a779fSJames Molloy                     TII->get(TargetOpcode::PHI), NewReg);
655790a779fSJames Molloy         NewPhi.addReg(PhiOp1).addMBB(BB1);
656790a779fSJames Molloy         NewPhi.addReg(PhiOp2).addMBB(BB2);
657790a779fSJames Molloy         if (np == 0)
658790a779fSJames Molloy           InstrMap[NewPhi] = &*BBI;
659790a779fSJames Molloy 
660790a779fSJames Molloy         // Rewrite uses and update the map. The actions depend upon whether
661790a779fSJames Molloy         // we generating code for the kernel or epilog blocks.
662790a779fSJames Molloy         if (InKernel) {
663790a779fSJames Molloy           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
664790a779fSJames Molloy                                 NewReg);
665790a779fSJames Molloy           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
666790a779fSJames Molloy                                 NewReg);
667790a779fSJames Molloy 
668790a779fSJames Molloy           PhiOp2 = NewReg;
669790a779fSJames Molloy           VRMap[PrevStage - np - 1][Def] = NewReg;
670790a779fSJames Molloy         } else {
671790a779fSJames Molloy           VRMap[CurStageNum - np][Def] = NewReg;
672790a779fSJames Molloy           if (np == NumPhis - 1)
673790a779fSJames Molloy             rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
674790a779fSJames Molloy                                   NewReg);
675790a779fSJames Molloy         }
676790a779fSJames Molloy         if (IsLast && np == NumPhis - 1)
677790a779fSJames Molloy           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
678790a779fSJames Molloy       }
679790a779fSJames Molloy     }
680790a779fSJames Molloy   }
681790a779fSJames Molloy }
682790a779fSJames Molloy 
683790a779fSJames Molloy /// Remove instructions that generate values with no uses.
684790a779fSJames Molloy /// Typically, these are induction variable operations that generate values
685790a779fSJames Molloy /// used in the loop itself.  A dead instruction has a definition with
686790a779fSJames Molloy /// no uses, or uses that occur in the original loop only.
687790a779fSJames Molloy void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
688790a779fSJames Molloy                                                     MBBVectorTy &EpilogBBs) {
689790a779fSJames Molloy   // For each epilog block, check that the value defined by each instruction
690790a779fSJames Molloy   // is used.  If not, delete it.
691790a779fSJames Molloy   for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
692790a779fSJames Molloy                                      MBE = EpilogBBs.rend();
693790a779fSJames Molloy        MBB != MBE; ++MBB)
694790a779fSJames Molloy     for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
695790a779fSJames Molloy                                                    ME = (*MBB)->instr_rend();
696790a779fSJames Molloy          MI != ME;) {
697790a779fSJames Molloy       // From DeadMachineInstructionElem. Don't delete inline assembly.
698790a779fSJames Molloy       if (MI->isInlineAsm()) {
699790a779fSJames Molloy         ++MI;
700790a779fSJames Molloy         continue;
701790a779fSJames Molloy       }
702790a779fSJames Molloy       bool SawStore = false;
703790a779fSJames Molloy       // Check if it's safe to remove the instruction due to side effects.
704790a779fSJames Molloy       // We can, and want to, remove Phis here.
705790a779fSJames Molloy       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
706790a779fSJames Molloy         ++MI;
707790a779fSJames Molloy         continue;
708790a779fSJames Molloy       }
709790a779fSJames Molloy       bool used = true;
710790a779fSJames Molloy       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
711790a779fSJames Molloy                                       MOE = MI->operands_end();
712790a779fSJames Molloy            MOI != MOE; ++MOI) {
713790a779fSJames Molloy         if (!MOI->isReg() || !MOI->isDef())
714790a779fSJames Molloy           continue;
715790a779fSJames Molloy         Register reg = MOI->getReg();
716790a779fSJames Molloy         // Assume physical registers are used, unless they are marked dead.
717790a779fSJames Molloy         if (Register::isPhysicalRegister(reg)) {
718790a779fSJames Molloy           used = !MOI->isDead();
719790a779fSJames Molloy           if (used)
720790a779fSJames Molloy             break;
721790a779fSJames Molloy           continue;
722790a779fSJames Molloy         }
723790a779fSJames Molloy         unsigned realUses = 0;
724790a779fSJames Molloy         for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
725790a779fSJames Molloy                                                EI = MRI.use_end();
726790a779fSJames Molloy              UI != EI; ++UI) {
727790a779fSJames Molloy           // Check if there are any uses that occur only in the original
728790a779fSJames Molloy           // loop.  If so, that's not a real use.
729790a779fSJames Molloy           if (UI->getParent()->getParent() != BB) {
730790a779fSJames Molloy             realUses++;
731790a779fSJames Molloy             used = true;
732790a779fSJames Molloy             break;
733790a779fSJames Molloy           }
734790a779fSJames Molloy         }
735790a779fSJames Molloy         if (realUses > 0)
736790a779fSJames Molloy           break;
737790a779fSJames Molloy         used = false;
738790a779fSJames Molloy       }
739790a779fSJames Molloy       if (!used) {
740790a779fSJames Molloy         LIS.RemoveMachineInstrFromMaps(*MI);
741790a779fSJames Molloy         MI++->eraseFromParent();
742790a779fSJames Molloy         continue;
743790a779fSJames Molloy       }
744790a779fSJames Molloy       ++MI;
745790a779fSJames Molloy     }
746790a779fSJames Molloy   // In the kernel block, check if we can remove a Phi that generates a value
747790a779fSJames Molloy   // used in an instruction removed in the epilog block.
748790a779fSJames Molloy   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
749790a779fSJames Molloy                                    BBE = KernelBB->getFirstNonPHI();
750790a779fSJames Molloy        BBI != BBE;) {
751790a779fSJames Molloy     MachineInstr *MI = &*BBI;
752790a779fSJames Molloy     ++BBI;
753790a779fSJames Molloy     Register reg = MI->getOperand(0).getReg();
754790a779fSJames Molloy     if (MRI.use_begin(reg) == MRI.use_end()) {
755790a779fSJames Molloy       LIS.RemoveMachineInstrFromMaps(*MI);
756790a779fSJames Molloy       MI->eraseFromParent();
757790a779fSJames Molloy     }
758790a779fSJames Molloy   }
759790a779fSJames Molloy }
760790a779fSJames Molloy 
761790a779fSJames Molloy /// For loop carried definitions, we split the lifetime of a virtual register
762790a779fSJames Molloy /// that has uses past the definition in the next iteration. A copy with a new
763790a779fSJames Molloy /// virtual register is inserted before the definition, which helps with
764790a779fSJames Molloy /// generating a better register assignment.
765790a779fSJames Molloy ///
766790a779fSJames Molloy ///   v1 = phi(a, v2)     v1 = phi(a, v2)
767790a779fSJames Molloy ///   v2 = phi(b, v3)     v2 = phi(b, v3)
768790a779fSJames Molloy ///   v3 = ..             v4 = copy v1
769790a779fSJames Molloy ///   .. = V1             v3 = ..
770790a779fSJames Molloy ///                       .. = v4
771790a779fSJames Molloy void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
772790a779fSJames Molloy                                             MBBVectorTy &EpilogBBs) {
773790a779fSJames Molloy   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
774790a779fSJames Molloy   for (auto &PHI : KernelBB->phis()) {
775790a779fSJames Molloy     Register Def = PHI.getOperand(0).getReg();
776790a779fSJames Molloy     // Check for any Phi definition that used as an operand of another Phi
777790a779fSJames Molloy     // in the same block.
778790a779fSJames Molloy     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
779790a779fSJames Molloy                                                  E = MRI.use_instr_end();
780790a779fSJames Molloy          I != E; ++I) {
781790a779fSJames Molloy       if (I->isPHI() && I->getParent() == KernelBB) {
782790a779fSJames Molloy         // Get the loop carried definition.
783790a779fSJames Molloy         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
784790a779fSJames Molloy         if (!LCDef)
785790a779fSJames Molloy           continue;
786790a779fSJames Molloy         MachineInstr *MI = MRI.getVRegDef(LCDef);
787790a779fSJames Molloy         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
788790a779fSJames Molloy           continue;
789790a779fSJames Molloy         // Search through the rest of the block looking for uses of the Phi
790790a779fSJames Molloy         // definition. If one occurs, then split the lifetime.
791790a779fSJames Molloy         unsigned SplitReg = 0;
792790a779fSJames Molloy         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
793790a779fSJames Molloy                                     KernelBB->instr_end()))
794790a779fSJames Molloy           if (BBJ.readsRegister(Def)) {
795790a779fSJames Molloy             // We split the lifetime when we find the first use.
796790a779fSJames Molloy             if (SplitReg == 0) {
797790a779fSJames Molloy               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
798790a779fSJames Molloy               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
799790a779fSJames Molloy                       TII->get(TargetOpcode::COPY), SplitReg)
800790a779fSJames Molloy                   .addReg(Def);
801790a779fSJames Molloy             }
802790a779fSJames Molloy             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
803790a779fSJames Molloy           }
804790a779fSJames Molloy         if (!SplitReg)
805790a779fSJames Molloy           continue;
806790a779fSJames Molloy         // Search through each of the epilog blocks for any uses to be renamed.
807790a779fSJames Molloy         for (auto &Epilog : EpilogBBs)
808790a779fSJames Molloy           for (auto &I : *Epilog)
809790a779fSJames Molloy             if (I.readsRegister(Def))
810790a779fSJames Molloy               I.substituteRegister(Def, SplitReg, 0, *TRI);
811790a779fSJames Molloy         break;
812790a779fSJames Molloy       }
813790a779fSJames Molloy     }
814790a779fSJames Molloy   }
815790a779fSJames Molloy }
816790a779fSJames Molloy 
817790a779fSJames Molloy /// Remove the incoming block from the Phis in a basic block.
818790a779fSJames Molloy static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
819790a779fSJames Molloy   for (MachineInstr &MI : *BB) {
820790a779fSJames Molloy     if (!MI.isPHI())
821790a779fSJames Molloy       break;
822790a779fSJames Molloy     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
823790a779fSJames Molloy       if (MI.getOperand(i + 1).getMBB() == Incoming) {
824790a779fSJames Molloy         MI.RemoveOperand(i + 1);
825790a779fSJames Molloy         MI.RemoveOperand(i);
826790a779fSJames Molloy         break;
827790a779fSJames Molloy       }
828790a779fSJames Molloy   }
829790a779fSJames Molloy }
830790a779fSJames Molloy 
831790a779fSJames Molloy /// Create branches from each prolog basic block to the appropriate epilog
832790a779fSJames Molloy /// block.  These edges are needed if the loop ends before reaching the
833790a779fSJames Molloy /// kernel.
834790a779fSJames Molloy void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
835790a779fSJames Molloy                                          MBBVectorTy &PrologBBs,
836790a779fSJames Molloy                                          MachineBasicBlock *KernelBB,
837790a779fSJames Molloy                                          MBBVectorTy &EpilogBBs,
838790a779fSJames Molloy                                          ValueMapTy *VRMap) {
839790a779fSJames Molloy   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
840790a779fSJames Molloy   MachineInstr *IndVar;
841790a779fSJames Molloy   MachineInstr *Cmp;
842790a779fSJames Molloy   if (TII->analyzeLoop(*Schedule.getLoop(), IndVar, Cmp))
843790a779fSJames Molloy     llvm_unreachable("Must be able to analyze loop!");
844790a779fSJames Molloy   MachineBasicBlock *LastPro = KernelBB;
845790a779fSJames Molloy   MachineBasicBlock *LastEpi = KernelBB;
846790a779fSJames Molloy 
847790a779fSJames Molloy   // Start from the blocks connected to the kernel and work "out"
848790a779fSJames Molloy   // to the first prolog and the last epilog blocks.
849790a779fSJames Molloy   SmallVector<MachineInstr *, 4> PrevInsts;
850790a779fSJames Molloy   unsigned MaxIter = PrologBBs.size() - 1;
851790a779fSJames Molloy   unsigned LC = UINT_MAX;
852790a779fSJames Molloy   unsigned LCMin = UINT_MAX;
853790a779fSJames Molloy   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
854790a779fSJames Molloy     // Add branches to the prolog that go to the corresponding
855790a779fSJames Molloy     // epilog, and the fall-thru prolog/kernel block.
856790a779fSJames Molloy     MachineBasicBlock *Prolog = PrologBBs[j];
857790a779fSJames Molloy     MachineBasicBlock *Epilog = EpilogBBs[i];
858790a779fSJames Molloy     // We've executed one iteration, so decrement the loop count and check for
859790a779fSJames Molloy     // the loop end.
860790a779fSJames Molloy     SmallVector<MachineOperand, 4> Cond;
861790a779fSJames Molloy     // Check if the LOOP0 has already been removed. If so, then there is no need
862790a779fSJames Molloy     // to reduce the trip count.
863790a779fSJames Molloy     if (LC != 0)
864790a779fSJames Molloy       LC = TII->reduceLoopCount(*Prolog, PreheaderBB, IndVar, *Cmp, Cond,
865790a779fSJames Molloy                                 PrevInsts, j, MaxIter);
866790a779fSJames Molloy 
867790a779fSJames Molloy     // Record the value of the first trip count, which is used to determine if
868790a779fSJames Molloy     // branches and blocks can be removed for constant trip counts.
869790a779fSJames Molloy     if (LCMin == UINT_MAX)
870790a779fSJames Molloy       LCMin = LC;
871790a779fSJames Molloy 
872790a779fSJames Molloy     unsigned numAdded = 0;
873790a779fSJames Molloy     if (Register::isVirtualRegister(LC)) {
874790a779fSJames Molloy       Prolog->addSuccessor(Epilog);
875790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
876790a779fSJames Molloy     } else if (j >= LCMin) {
877790a779fSJames Molloy       Prolog->addSuccessor(Epilog);
878790a779fSJames Molloy       Prolog->removeSuccessor(LastPro);
879790a779fSJames Molloy       LastEpi->removeSuccessor(Epilog);
880790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
881790a779fSJames Molloy       removePhis(Epilog, LastEpi);
882790a779fSJames Molloy       // Remove the blocks that are no longer referenced.
883790a779fSJames Molloy       if (LastPro != LastEpi) {
884790a779fSJames Molloy         LastEpi->clear();
885790a779fSJames Molloy         LastEpi->eraseFromParent();
886790a779fSJames Molloy       }
887790a779fSJames Molloy       LastPro->clear();
888790a779fSJames Molloy       LastPro->eraseFromParent();
889790a779fSJames Molloy     } else {
890790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
891790a779fSJames Molloy       removePhis(Epilog, Prolog);
892790a779fSJames Molloy     }
893790a779fSJames Molloy     LastPro = Prolog;
894790a779fSJames Molloy     LastEpi = Epilog;
895790a779fSJames Molloy     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
896790a779fSJames Molloy                                                    E = Prolog->instr_rend();
897790a779fSJames Molloy          I != E && numAdded > 0; ++I, --numAdded)
898790a779fSJames Molloy       updateInstruction(&*I, false, j, 0, VRMap);
899790a779fSJames Molloy   }
900790a779fSJames Molloy }
901790a779fSJames Molloy 
902790a779fSJames Molloy /// Return true if we can compute the amount the instruction changes
903790a779fSJames Molloy /// during each iteration. Set Delta to the amount of the change.
904790a779fSJames Molloy bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
905790a779fSJames Molloy   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
906790a779fSJames Molloy   const MachineOperand *BaseOp;
907790a779fSJames Molloy   int64_t Offset;
908790a779fSJames Molloy   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
909790a779fSJames Molloy     return false;
910790a779fSJames Molloy 
911790a779fSJames Molloy   if (!BaseOp->isReg())
912790a779fSJames Molloy     return false;
913790a779fSJames Molloy 
914790a779fSJames Molloy   Register BaseReg = BaseOp->getReg();
915790a779fSJames Molloy 
916790a779fSJames Molloy   MachineRegisterInfo &MRI = MF.getRegInfo();
917790a779fSJames Molloy   // Check if there is a Phi. If so, get the definition in the loop.
918790a779fSJames Molloy   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
919790a779fSJames Molloy   if (BaseDef && BaseDef->isPHI()) {
920790a779fSJames Molloy     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
921790a779fSJames Molloy     BaseDef = MRI.getVRegDef(BaseReg);
922790a779fSJames Molloy   }
923790a779fSJames Molloy   if (!BaseDef)
924790a779fSJames Molloy     return false;
925790a779fSJames Molloy 
926790a779fSJames Molloy   int D = 0;
927790a779fSJames Molloy   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
928790a779fSJames Molloy     return false;
929790a779fSJames Molloy 
930790a779fSJames Molloy   Delta = D;
931790a779fSJames Molloy   return true;
932790a779fSJames Molloy }
933790a779fSJames Molloy 
934790a779fSJames Molloy /// Update the memory operand with a new offset when the pipeliner
935790a779fSJames Molloy /// generates a new copy of the instruction that refers to a
936790a779fSJames Molloy /// different memory location.
937790a779fSJames Molloy void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
938790a779fSJames Molloy                                                MachineInstr &OldMI,
939790a779fSJames Molloy                                                unsigned Num) {
940790a779fSJames Molloy   if (Num == 0)
941790a779fSJames Molloy     return;
942790a779fSJames Molloy   // If the instruction has memory operands, then adjust the offset
943790a779fSJames Molloy   // when the instruction appears in different stages.
944790a779fSJames Molloy   if (NewMI.memoperands_empty())
945790a779fSJames Molloy     return;
946790a779fSJames Molloy   SmallVector<MachineMemOperand *, 2> NewMMOs;
947790a779fSJames Molloy   for (MachineMemOperand *MMO : NewMI.memoperands()) {
948790a779fSJames Molloy     // TODO: Figure out whether isAtomic is really necessary (see D57601).
949790a779fSJames Molloy     if (MMO->isVolatile() || MMO->isAtomic() ||
950790a779fSJames Molloy         (MMO->isInvariant() && MMO->isDereferenceable()) ||
951790a779fSJames Molloy         (!MMO->getValue())) {
952790a779fSJames Molloy       NewMMOs.push_back(MMO);
953790a779fSJames Molloy       continue;
954790a779fSJames Molloy     }
955790a779fSJames Molloy     unsigned Delta;
956790a779fSJames Molloy     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
957790a779fSJames Molloy       int64_t AdjOffset = Delta * Num;
958790a779fSJames Molloy       NewMMOs.push_back(
959790a779fSJames Molloy           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
960790a779fSJames Molloy     } else {
961790a779fSJames Molloy       NewMMOs.push_back(
962790a779fSJames Molloy           MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
963790a779fSJames Molloy     }
964790a779fSJames Molloy   }
965790a779fSJames Molloy   NewMI.setMemRefs(MF, NewMMOs);
966790a779fSJames Molloy }
967790a779fSJames Molloy 
968790a779fSJames Molloy /// Clone the instruction for the new pipelined loop and update the
969790a779fSJames Molloy /// memory operands, if needed.
970790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
971790a779fSJames Molloy                                                  unsigned CurStageNum,
972790a779fSJames Molloy                                                  unsigned InstStageNum) {
973790a779fSJames Molloy   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
974790a779fSJames Molloy   // Check for tied operands in inline asm instructions. This should be handled
975790a779fSJames Molloy   // elsewhere, but I'm not sure of the best solution.
976790a779fSJames Molloy   if (OldMI->isInlineAsm())
977790a779fSJames Molloy     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
978790a779fSJames Molloy       const auto &MO = OldMI->getOperand(i);
979790a779fSJames Molloy       if (MO.isReg() && MO.isUse())
980790a779fSJames Molloy         break;
981790a779fSJames Molloy       unsigned UseIdx;
982790a779fSJames Molloy       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
983790a779fSJames Molloy         NewMI->tieOperands(i, UseIdx);
984790a779fSJames Molloy     }
985790a779fSJames Molloy   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
986790a779fSJames Molloy   return NewMI;
987790a779fSJames Molloy }
988790a779fSJames Molloy 
989790a779fSJames Molloy /// Clone the instruction for the new pipelined loop. If needed, this
990790a779fSJames Molloy /// function updates the instruction using the values saved in the
991790a779fSJames Molloy /// InstrChanges structure.
992790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
993790a779fSJames Molloy     MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
994790a779fSJames Molloy   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
995790a779fSJames Molloy   auto It = InstrChanges.find(OldMI);
996790a779fSJames Molloy   if (It != InstrChanges.end()) {
997790a779fSJames Molloy     std::pair<unsigned, int64_t> RegAndOffset = It->second;
998790a779fSJames Molloy     unsigned BasePos, OffsetPos;
999790a779fSJames Molloy     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
1000790a779fSJames Molloy       return nullptr;
1001790a779fSJames Molloy     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
1002790a779fSJames Molloy     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
1003790a779fSJames Molloy     if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
1004790a779fSJames Molloy       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
1005790a779fSJames Molloy     NewMI->getOperand(OffsetPos).setImm(NewOffset);
1006790a779fSJames Molloy   }
1007790a779fSJames Molloy   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
1008790a779fSJames Molloy   return NewMI;
1009790a779fSJames Molloy }
1010790a779fSJames Molloy 
1011790a779fSJames Molloy /// Update the machine instruction with new virtual registers.  This
1012790a779fSJames Molloy /// function may change the defintions and/or uses.
1013790a779fSJames Molloy void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
1014790a779fSJames Molloy                                                bool LastDef,
1015790a779fSJames Molloy                                                unsigned CurStageNum,
1016790a779fSJames Molloy                                                unsigned InstrStageNum,
1017790a779fSJames Molloy                                                ValueMapTy *VRMap) {
1018790a779fSJames Molloy   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
1019790a779fSJames Molloy     MachineOperand &MO = NewMI->getOperand(i);
1020790a779fSJames Molloy     if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
1021790a779fSJames Molloy       continue;
1022790a779fSJames Molloy     Register reg = MO.getReg();
1023790a779fSJames Molloy     if (MO.isDef()) {
1024790a779fSJames Molloy       // Create a new virtual register for the definition.
1025790a779fSJames Molloy       const TargetRegisterClass *RC = MRI.getRegClass(reg);
1026790a779fSJames Molloy       Register NewReg = MRI.createVirtualRegister(RC);
1027790a779fSJames Molloy       MO.setReg(NewReg);
1028790a779fSJames Molloy       VRMap[CurStageNum][reg] = NewReg;
1029790a779fSJames Molloy       if (LastDef)
1030790a779fSJames Molloy         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
1031790a779fSJames Molloy     } else if (MO.isUse()) {
1032790a779fSJames Molloy       MachineInstr *Def = MRI.getVRegDef(reg);
1033790a779fSJames Molloy       // Compute the stage that contains the last definition for instruction.
1034790a779fSJames Molloy       int DefStageNum = Schedule.getStage(Def);
1035790a779fSJames Molloy       unsigned StageNum = CurStageNum;
1036790a779fSJames Molloy       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
1037790a779fSJames Molloy         // Compute the difference in stages between the defintion and the use.
1038790a779fSJames Molloy         unsigned StageDiff = (InstrStageNum - DefStageNum);
1039790a779fSJames Molloy         // Make an adjustment to get the last definition.
1040790a779fSJames Molloy         StageNum -= StageDiff;
1041790a779fSJames Molloy       }
1042790a779fSJames Molloy       if (VRMap[StageNum].count(reg))
1043790a779fSJames Molloy         MO.setReg(VRMap[StageNum][reg]);
1044790a779fSJames Molloy     }
1045790a779fSJames Molloy   }
1046790a779fSJames Molloy }
1047790a779fSJames Molloy 
1048790a779fSJames Molloy /// Return the instruction in the loop that defines the register.
1049790a779fSJames Molloy /// If the definition is a Phi, then follow the Phi operand to
1050790a779fSJames Molloy /// the instruction in the loop.
1051790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::findDefInLoop(unsigned Reg) {
1052790a779fSJames Molloy   SmallPtrSet<MachineInstr *, 8> Visited;
1053790a779fSJames Molloy   MachineInstr *Def = MRI.getVRegDef(Reg);
1054790a779fSJames Molloy   while (Def->isPHI()) {
1055790a779fSJames Molloy     if (!Visited.insert(Def).second)
1056790a779fSJames Molloy       break;
1057790a779fSJames Molloy     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
1058790a779fSJames Molloy       if (Def->getOperand(i + 1).getMBB() == BB) {
1059790a779fSJames Molloy         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
1060790a779fSJames Molloy         break;
1061790a779fSJames Molloy       }
1062790a779fSJames Molloy   }
1063790a779fSJames Molloy   return Def;
1064790a779fSJames Molloy }
1065790a779fSJames Molloy 
1066790a779fSJames Molloy /// Return the new name for the value from the previous stage.
1067790a779fSJames Molloy unsigned ModuloScheduleExpander::getPrevMapVal(
1068790a779fSJames Molloy     unsigned StageNum, unsigned PhiStage, unsigned LoopVal, unsigned LoopStage,
1069790a779fSJames Molloy     ValueMapTy *VRMap, MachineBasicBlock *BB) {
1070790a779fSJames Molloy   unsigned PrevVal = 0;
1071790a779fSJames Molloy   if (StageNum > PhiStage) {
1072790a779fSJames Molloy     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
1073790a779fSJames Molloy     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
1074790a779fSJames Molloy       // The name is defined in the previous stage.
1075790a779fSJames Molloy       PrevVal = VRMap[StageNum - 1][LoopVal];
1076790a779fSJames Molloy     else if (VRMap[StageNum].count(LoopVal))
1077790a779fSJames Molloy       // The previous name is defined in the current stage when the instruction
1078790a779fSJames Molloy       // order is swapped.
1079790a779fSJames Molloy       PrevVal = VRMap[StageNum][LoopVal];
1080790a779fSJames Molloy     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
1081790a779fSJames Molloy       // The loop value hasn't yet been scheduled.
1082790a779fSJames Molloy       PrevVal = LoopVal;
1083790a779fSJames Molloy     else if (StageNum == PhiStage + 1)
1084790a779fSJames Molloy       // The loop value is another phi, which has not been scheduled.
1085790a779fSJames Molloy       PrevVal = getInitPhiReg(*LoopInst, BB);
1086790a779fSJames Molloy     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
1087790a779fSJames Molloy       // The loop value is another phi, which has been scheduled.
1088790a779fSJames Molloy       PrevVal =
1089790a779fSJames Molloy           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
1090790a779fSJames Molloy                         LoopStage, VRMap, BB);
1091790a779fSJames Molloy   }
1092790a779fSJames Molloy   return PrevVal;
1093790a779fSJames Molloy }
1094790a779fSJames Molloy 
1095790a779fSJames Molloy /// Rewrite the Phi values in the specified block to use the mappings
1096790a779fSJames Molloy /// from the initial operand. Once the Phi is scheduled, we switch
1097790a779fSJames Molloy /// to using the loop value instead of the Phi value, so those names
1098790a779fSJames Molloy /// do not need to be rewritten.
1099790a779fSJames Molloy void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
1100790a779fSJames Molloy                                               unsigned StageNum,
1101790a779fSJames Molloy                                               ValueMapTy *VRMap,
1102790a779fSJames Molloy                                               InstrMapTy &InstrMap) {
1103790a779fSJames Molloy   for (auto &PHI : BB->phis()) {
1104790a779fSJames Molloy     unsigned InitVal = 0;
1105790a779fSJames Molloy     unsigned LoopVal = 0;
1106790a779fSJames Molloy     getPhiRegs(PHI, BB, InitVal, LoopVal);
1107790a779fSJames Molloy     Register PhiDef = PHI.getOperand(0).getReg();
1108790a779fSJames Molloy 
1109790a779fSJames Molloy     unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
1110790a779fSJames Molloy     unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
1111790a779fSJames Molloy     unsigned NumPhis = getStagesForPhi(PhiDef);
1112790a779fSJames Molloy     if (NumPhis > StageNum)
1113790a779fSJames Molloy       NumPhis = StageNum;
1114790a779fSJames Molloy     for (unsigned np = 0; np <= NumPhis; ++np) {
1115790a779fSJames Molloy       unsigned NewVal =
1116790a779fSJames Molloy           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
1117790a779fSJames Molloy       if (!NewVal)
1118790a779fSJames Molloy         NewVal = InitVal;
1119790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
1120790a779fSJames Molloy                             NewVal);
1121790a779fSJames Molloy     }
1122790a779fSJames Molloy   }
1123790a779fSJames Molloy }
1124790a779fSJames Molloy 
1125790a779fSJames Molloy /// Rewrite a previously scheduled instruction to use the register value
1126790a779fSJames Molloy /// from the new instruction. Make sure the instruction occurs in the
1127790a779fSJames Molloy /// basic block, and we don't change the uses in the new instruction.
1128790a779fSJames Molloy void ModuloScheduleExpander::rewriteScheduledInstr(
1129790a779fSJames Molloy     MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
1130790a779fSJames Molloy     unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, unsigned NewReg,
1131790a779fSJames Molloy     unsigned PrevReg) {
1132790a779fSJames Molloy   bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
1133790a779fSJames Molloy   int StagePhi = Schedule.getStage(Phi) + PhiNum;
1134790a779fSJames Molloy   // Rewrite uses that have been scheduled already to use the new
1135790a779fSJames Molloy   // Phi register.
1136790a779fSJames Molloy   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
1137790a779fSJames Molloy                                          EI = MRI.use_end();
1138790a779fSJames Molloy        UI != EI;) {
1139790a779fSJames Molloy     MachineOperand &UseOp = *UI;
1140790a779fSJames Molloy     MachineInstr *UseMI = UseOp.getParent();
1141790a779fSJames Molloy     ++UI;
1142790a779fSJames Molloy     if (UseMI->getParent() != BB)
1143790a779fSJames Molloy       continue;
1144790a779fSJames Molloy     if (UseMI->isPHI()) {
1145790a779fSJames Molloy       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
1146790a779fSJames Molloy         continue;
1147790a779fSJames Molloy       if (getLoopPhiReg(*UseMI, BB) != OldReg)
1148790a779fSJames Molloy         continue;
1149790a779fSJames Molloy     }
1150790a779fSJames Molloy     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
1151790a779fSJames Molloy     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
1152790a779fSJames Molloy     MachineInstr *OrigMI = OrigInstr->second;
1153790a779fSJames Molloy     int StageSched = Schedule.getStage(OrigMI);
1154790a779fSJames Molloy     int CycleSched = Schedule.getCycle(OrigMI);
1155790a779fSJames Molloy     unsigned ReplaceReg = 0;
1156790a779fSJames Molloy     // This is the stage for the scheduled instruction.
1157790a779fSJames Molloy     if (StagePhi == StageSched && Phi->isPHI()) {
1158790a779fSJames Molloy       int CyclePhi = Schedule.getCycle(Phi);
1159790a779fSJames Molloy       if (PrevReg && InProlog)
1160790a779fSJames Molloy         ReplaceReg = PrevReg;
1161790a779fSJames Molloy       else if (PrevReg && !isLoopCarried(*Phi) &&
1162790a779fSJames Molloy                (CyclePhi <= CycleSched || OrigMI->isPHI()))
1163790a779fSJames Molloy         ReplaceReg = PrevReg;
1164790a779fSJames Molloy       else
1165790a779fSJames Molloy         ReplaceReg = NewReg;
1166790a779fSJames Molloy     }
1167790a779fSJames Molloy     // The scheduled instruction occurs before the scheduled Phi, and the
1168790a779fSJames Molloy     // Phi is not loop carried.
1169790a779fSJames Molloy     if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
1170790a779fSJames Molloy       ReplaceReg = NewReg;
1171790a779fSJames Molloy     if (StagePhi > StageSched && Phi->isPHI())
1172790a779fSJames Molloy       ReplaceReg = NewReg;
1173790a779fSJames Molloy     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
1174790a779fSJames Molloy       ReplaceReg = NewReg;
1175790a779fSJames Molloy     if (ReplaceReg) {
1176790a779fSJames Molloy       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
1177790a779fSJames Molloy       UseOp.setReg(ReplaceReg);
1178790a779fSJames Molloy     }
1179790a779fSJames Molloy   }
1180790a779fSJames Molloy }
1181790a779fSJames Molloy 
1182790a779fSJames Molloy bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
1183790a779fSJames Molloy   if (!Phi.isPHI())
1184790a779fSJames Molloy     return false;
1185790a779fSJames Molloy   unsigned DefCycle = Schedule.getCycle(&Phi);
1186790a779fSJames Molloy   int DefStage = Schedule.getStage(&Phi);
1187790a779fSJames Molloy 
1188790a779fSJames Molloy   unsigned InitVal = 0;
1189790a779fSJames Molloy   unsigned LoopVal = 0;
1190790a779fSJames Molloy   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
1191790a779fSJames Molloy   MachineInstr *Use = MRI.getVRegDef(LoopVal);
1192790a779fSJames Molloy   if (!Use || Use->isPHI())
1193790a779fSJames Molloy     return true;
1194790a779fSJames Molloy   unsigned LoopCycle = Schedule.getCycle(Use);
1195790a779fSJames Molloy   int LoopStage = Schedule.getStage(Use);
1196790a779fSJames Molloy   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
1197790a779fSJames Molloy }
1198*93549957SJames Molloy 
1199*93549957SJames Molloy //===----------------------------------------------------------------------===//
1200*93549957SJames Molloy // ModuloScheduleTestPass implementation
1201*93549957SJames Molloy //===----------------------------------------------------------------------===//
1202*93549957SJames Molloy // This pass constructs a ModuloSchedule from its module and runs
1203*93549957SJames Molloy // ModuloScheduleExpander.
1204*93549957SJames Molloy //
1205*93549957SJames Molloy // The module is expected to contain a single-block analyzable loop.
1206*93549957SJames Molloy // The total order of instructions is taken from the loop as-is.
1207*93549957SJames Molloy // Instructions are expected to be annotated with a PostInstrSymbol.
1208*93549957SJames Molloy // This PostInstrSymbol must have the following format:
1209*93549957SJames Molloy //  "Stage=%d Cycle=%d".
1210*93549957SJames Molloy //===----------------------------------------------------------------------===//
1211*93549957SJames Molloy 
1212*93549957SJames Molloy class ModuloScheduleTest : public MachineFunctionPass {
1213*93549957SJames Molloy public:
1214*93549957SJames Molloy   static char ID;
1215*93549957SJames Molloy 
1216*93549957SJames Molloy   ModuloScheduleTest() : MachineFunctionPass(ID) {
1217*93549957SJames Molloy     initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
1218*93549957SJames Molloy   }
1219*93549957SJames Molloy 
1220*93549957SJames Molloy   bool runOnMachineFunction(MachineFunction &MF) override;
1221*93549957SJames Molloy   void runOnLoop(MachineFunction &MF, MachineLoop &L);
1222*93549957SJames Molloy 
1223*93549957SJames Molloy   void getAnalysisUsage(AnalysisUsage &AU) const override {
1224*93549957SJames Molloy     AU.addRequired<MachineLoopInfo>();
1225*93549957SJames Molloy     AU.addRequired<LiveIntervals>();
1226*93549957SJames Molloy     MachineFunctionPass::getAnalysisUsage(AU);
1227*93549957SJames Molloy   }
1228*93549957SJames Molloy };
1229*93549957SJames Molloy 
1230*93549957SJames Molloy char ModuloScheduleTest::ID = 0;
1231*93549957SJames Molloy 
1232*93549957SJames Molloy INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
1233*93549957SJames Molloy                       "Modulo Schedule test pass", false, false)
1234*93549957SJames Molloy INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1235*93549957SJames Molloy INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1236*93549957SJames Molloy INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
1237*93549957SJames Molloy                     "Modulo Schedule test pass", false, false)
1238*93549957SJames Molloy 
1239*93549957SJames Molloy bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
1240*93549957SJames Molloy   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
1241*93549957SJames Molloy   for (auto *L : MLI) {
1242*93549957SJames Molloy     if (L->getTopBlock() != L->getBottomBlock())
1243*93549957SJames Molloy       continue;
1244*93549957SJames Molloy     runOnLoop(MF, *L);
1245*93549957SJames Molloy     return false;
1246*93549957SJames Molloy   }
1247*93549957SJames Molloy   return false;
1248*93549957SJames Molloy }
1249*93549957SJames Molloy 
1250*93549957SJames Molloy static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
1251*93549957SJames Molloy   std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
1252*93549957SJames Molloy   std::pair<StringRef, StringRef> StageTokenAndValue =
1253*93549957SJames Molloy       getToken(StageAndCycle.first, "-");
1254*93549957SJames Molloy   std::pair<StringRef, StringRef> CycleTokenAndValue =
1255*93549957SJames Molloy       getToken(StageAndCycle.second, "-");
1256*93549957SJames Molloy   if (StageTokenAndValue.first != "Stage" ||
1257*93549957SJames Molloy       CycleTokenAndValue.first != "_Cycle") {
1258*93549957SJames Molloy     llvm_unreachable(
1259*93549957SJames Molloy         "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
1260*93549957SJames Molloy     return;
1261*93549957SJames Molloy   }
1262*93549957SJames Molloy 
1263*93549957SJames Molloy   StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
1264*93549957SJames Molloy   CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
1265*93549957SJames Molloy 
1266*93549957SJames Molloy   dbgs() << "  Stage=" << Stage << ", Cycle=" << Cycle << "\n";
1267*93549957SJames Molloy }
1268*93549957SJames Molloy 
1269*93549957SJames Molloy void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
1270*93549957SJames Molloy   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
1271*93549957SJames Molloy   MachineBasicBlock *BB = L.getTopBlock();
1272*93549957SJames Molloy   dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
1273*93549957SJames Molloy 
1274*93549957SJames Molloy   DenseMap<MachineInstr *, int> Cycle, Stage;
1275*93549957SJames Molloy   std::vector<MachineInstr *> Instrs;
1276*93549957SJames Molloy   for (MachineInstr &MI : *BB) {
1277*93549957SJames Molloy     if (MI.isTerminator())
1278*93549957SJames Molloy       continue;
1279*93549957SJames Molloy     Instrs.push_back(&MI);
1280*93549957SJames Molloy     if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
1281*93549957SJames Molloy       dbgs() << "Parsing post-instr symbol for " << MI;
1282*93549957SJames Molloy       parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
1283*93549957SJames Molloy     }
1284*93549957SJames Molloy   }
1285*93549957SJames Molloy 
1286*93549957SJames Molloy   ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle), std::move(Stage));
1287*93549957SJames Molloy   ModuloScheduleExpander MSE(
1288*93549957SJames Molloy       MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
1289*93549957SJames Molloy   MSE.expand();
1290*93549957SJames Molloy }
1291*93549957SJames Molloy 
1292*93549957SJames Molloy //===----------------------------------------------------------------------===//
1293*93549957SJames Molloy // ModuloScheduleTestAnnotater implementation
1294*93549957SJames Molloy //===----------------------------------------------------------------------===//
1295*93549957SJames Molloy 
1296*93549957SJames Molloy void ModuloScheduleTestAnnotater::annotate() {
1297*93549957SJames Molloy   for (MachineInstr *MI : S.getInstructions()) {
1298*93549957SJames Molloy     SmallVector<char, 16> SV;
1299*93549957SJames Molloy     raw_svector_ostream OS(SV);
1300*93549957SJames Molloy     OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
1301*93549957SJames Molloy     MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
1302*93549957SJames Molloy     MI->setPostInstrSymbol(MF, Sym);
1303*93549957SJames Molloy   }
1304*93549957SJames Molloy }
1305