xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/ModuloSchedule.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===- ModuloSchedule.cpp - Software pipeline schedule expansion ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/CodeGen/ModuloSchedule.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/Analysis/MemoryLocation.h"
12 #include "llvm/CodeGen/LiveIntervals.h"
13 #include "llvm/CodeGen/MachineInstrBuilder.h"
14 #include "llvm/CodeGen/MachineRegisterInfo.h"
15 #include "llvm/InitializePasses.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 #define DEBUG_TYPE "pipeliner"
22 using namespace llvm;
23 
24 void ModuloSchedule::print(raw_ostream &OS) {
25   for (MachineInstr *MI : ScheduledInstrs)
26     OS << "[stage " << getStage(MI) << " @" << getCycle(MI) << "c] " << *MI;
27 }
28 
29 //===----------------------------------------------------------------------===//
30 // ModuloScheduleExpander implementation
31 //===----------------------------------------------------------------------===//
32 
33 /// Return the register values for  the operands of a Phi instruction.
34 /// This function assume the instruction is a Phi.
35 static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
36                        unsigned &InitVal, unsigned &LoopVal) {
37   assert(Phi.isPHI() && "Expecting a Phi.");
38 
39   InitVal = 0;
40   LoopVal = 0;
41   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
42     if (Phi.getOperand(i + 1).getMBB() != Loop)
43       InitVal = Phi.getOperand(i).getReg();
44     else
45       LoopVal = Phi.getOperand(i).getReg();
46 
47   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
48 }
49 
50 /// Return the Phi register value that comes from the incoming block.
51 static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
52   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
53     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
54       return Phi.getOperand(i).getReg();
55   return 0;
56 }
57 
58 /// Return the Phi register value that comes the loop block.
59 static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
60   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
61     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
62       return Phi.getOperand(i).getReg();
63   return 0;
64 }
65 
66 void ModuloScheduleExpander::expand() {
67   BB = Schedule.getLoop()->getTopBlock();
68   Preheader = *BB->pred_begin();
69   if (Preheader == BB)
70     Preheader = *std::next(BB->pred_begin());
71 
72   // Iterate over the definitions in each instruction, and compute the
73   // stage difference for each use.  Keep the maximum value.
74   for (MachineInstr *MI : Schedule.getInstructions()) {
75     int DefStage = Schedule.getStage(MI);
76     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
77       MachineOperand &Op = MI->getOperand(i);
78       if (!Op.isReg() || !Op.isDef())
79         continue;
80 
81       Register Reg = Op.getReg();
82       unsigned MaxDiff = 0;
83       bool PhiIsSwapped = false;
84       for (MachineOperand &UseOp : MRI.use_operands(Reg)) {
85         MachineInstr *UseMI = UseOp.getParent();
86         int UseStage = Schedule.getStage(UseMI);
87         unsigned Diff = 0;
88         if (UseStage != -1 && UseStage >= DefStage)
89           Diff = UseStage - DefStage;
90         if (MI->isPHI()) {
91           if (isLoopCarried(*MI))
92             ++Diff;
93           else
94             PhiIsSwapped = true;
95         }
96         MaxDiff = std::max(Diff, MaxDiff);
97       }
98       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
99     }
100   }
101 
102   generatePipelinedLoop();
103 }
104 
105 void ModuloScheduleExpander::generatePipelinedLoop() {
106   LoopInfo = TII->analyzeLoopForPipelining(BB);
107   assert(LoopInfo && "Must be able to analyze loop!");
108 
109   // Create a new basic block for the kernel and add it to the CFG.
110   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
111 
112   unsigned MaxStageCount = Schedule.getNumStages() - 1;
113 
114   // Remember the registers that are used in different stages. The index is
115   // the iteration, or stage, that the instruction is scheduled in.  This is
116   // a map between register names in the original block and the names created
117   // in each stage of the pipelined loop.
118   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
119   InstrMapTy InstrMap;
120 
121   SmallVector<MachineBasicBlock *, 4> PrologBBs;
122 
123   // Generate the prolog instructions that set up the pipeline.
124   generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
125   MF.insert(BB->getIterator(), KernelBB);
126 
127   // Rearrange the instructions to generate the new, pipelined loop,
128   // and update register names as needed.
129   for (MachineInstr *CI : Schedule.getInstructions()) {
130     if (CI->isPHI())
131       continue;
132     unsigned StageNum = Schedule.getStage(CI);
133     MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
134     updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
135     KernelBB->push_back(NewMI);
136     InstrMap[NewMI] = CI;
137   }
138 
139   // Copy any terminator instructions to the new kernel, and update
140   // names as needed.
141   for (MachineInstr &MI : BB->terminators()) {
142     MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
143     updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
144     KernelBB->push_back(NewMI);
145     InstrMap[NewMI] = &MI;
146   }
147 
148   NewKernel = KernelBB;
149   KernelBB->transferSuccessors(BB);
150   KernelBB->replaceSuccessor(BB, KernelBB);
151 
152   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
153                        InstrMap, MaxStageCount, MaxStageCount, false);
154   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, InstrMap,
155                MaxStageCount, MaxStageCount, false);
156 
157   LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
158 
159   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
160   // Generate the epilog instructions to complete the pipeline.
161   generateEpilog(MaxStageCount, KernelBB, VRMap, EpilogBBs, PrologBBs);
162 
163   // We need this step because the register allocation doesn't handle some
164   // situations well, so we insert copies to help out.
165   splitLifetimes(KernelBB, EpilogBBs);
166 
167   // Remove dead instructions due to loop induction variables.
168   removeDeadInstructions(KernelBB, EpilogBBs);
169 
170   // Add branches between prolog and epilog blocks.
171   addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
172 
173   delete[] VRMap;
174 }
175 
176 void ModuloScheduleExpander::cleanup() {
177   // Remove the original loop since it's no longer referenced.
178   for (auto &I : *BB)
179     LIS.RemoveMachineInstrFromMaps(I);
180   BB->clear();
181   BB->eraseFromParent();
182 }
183 
184 /// Generate the pipeline prolog code.
185 void ModuloScheduleExpander::generateProlog(unsigned LastStage,
186                                             MachineBasicBlock *KernelBB,
187                                             ValueMapTy *VRMap,
188                                             MBBVectorTy &PrologBBs) {
189   MachineBasicBlock *PredBB = Preheader;
190   InstrMapTy InstrMap;
191 
192   // Generate a basic block for each stage, not including the last stage,
193   // which will be generated in the kernel. Each basic block may contain
194   // instructions from multiple stages/iterations.
195   for (unsigned i = 0; i < LastStage; ++i) {
196     // Create and insert the prolog basic block prior to the original loop
197     // basic block.  The original loop is removed later.
198     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
199     PrologBBs.push_back(NewBB);
200     MF.insert(BB->getIterator(), NewBB);
201     NewBB->transferSuccessors(PredBB);
202     PredBB->addSuccessor(NewBB);
203     PredBB = NewBB;
204 
205     // Generate instructions for each appropriate stage. Process instructions
206     // in original program order.
207     for (int StageNum = i; StageNum >= 0; --StageNum) {
208       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
209                                        BBE = BB->getFirstTerminator();
210            BBI != BBE; ++BBI) {
211         if (Schedule.getStage(&*BBI) == StageNum) {
212           if (BBI->isPHI())
213             continue;
214           MachineInstr *NewMI =
215               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
216           updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
217           NewBB->push_back(NewMI);
218           InstrMap[NewMI] = &*BBI;
219         }
220       }
221     }
222     rewritePhiValues(NewBB, i, VRMap, InstrMap);
223     LLVM_DEBUG({
224       dbgs() << "prolog:\n";
225       NewBB->dump();
226     });
227   }
228 
229   PredBB->replaceSuccessor(BB, KernelBB);
230 
231   // Check if we need to remove the branch from the preheader to the original
232   // loop, and replace it with a branch to the new loop.
233   unsigned numBranches = TII->removeBranch(*Preheader);
234   if (numBranches) {
235     SmallVector<MachineOperand, 0> Cond;
236     TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
237   }
238 }
239 
240 /// Generate the pipeline epilog code. The epilog code finishes the iterations
241 /// that were started in either the prolog or the kernel.  We create a basic
242 /// block for each stage that needs to complete.
243 void ModuloScheduleExpander::generateEpilog(unsigned LastStage,
244                                             MachineBasicBlock *KernelBB,
245                                             ValueMapTy *VRMap,
246                                             MBBVectorTy &EpilogBBs,
247                                             MBBVectorTy &PrologBBs) {
248   // We need to change the branch from the kernel to the first epilog block, so
249   // this call to analyze branch uses the kernel rather than the original BB.
250   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
251   SmallVector<MachineOperand, 4> Cond;
252   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
253   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
254   if (checkBranch)
255     return;
256 
257   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
258   if (*LoopExitI == KernelBB)
259     ++LoopExitI;
260   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
261   MachineBasicBlock *LoopExitBB = *LoopExitI;
262 
263   MachineBasicBlock *PredBB = KernelBB;
264   MachineBasicBlock *EpilogStart = LoopExitBB;
265   InstrMapTy InstrMap;
266 
267   // Generate a basic block for each stage, not including the last stage,
268   // which was generated for the kernel.  Each basic block may contain
269   // instructions from multiple stages/iterations.
270   int EpilogStage = LastStage + 1;
271   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
272     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
273     EpilogBBs.push_back(NewBB);
274     MF.insert(BB->getIterator(), NewBB);
275 
276     PredBB->replaceSuccessor(LoopExitBB, NewBB);
277     NewBB->addSuccessor(LoopExitBB);
278 
279     if (EpilogStart == LoopExitBB)
280       EpilogStart = NewBB;
281 
282     // Add instructions to the epilog depending on the current block.
283     // Process instructions in original program order.
284     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
285       for (auto &BBI : *BB) {
286         if (BBI.isPHI())
287           continue;
288         MachineInstr *In = &BBI;
289         if ((unsigned)Schedule.getStage(In) == StageNum) {
290           // Instructions with memoperands in the epilog are updated with
291           // conservative values.
292           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
293           updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
294           NewBB->push_back(NewMI);
295           InstrMap[NewMI] = In;
296         }
297       }
298     }
299     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
300                          InstrMap, LastStage, EpilogStage, i == 1);
301     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, InstrMap,
302                  LastStage, EpilogStage, i == 1);
303     PredBB = NewBB;
304 
305     LLVM_DEBUG({
306       dbgs() << "epilog:\n";
307       NewBB->dump();
308     });
309   }
310 
311   // Fix any Phi nodes in the loop exit block.
312   LoopExitBB->replacePhiUsesWith(BB, PredBB);
313 
314   // Create a branch to the new epilog from the kernel.
315   // Remove the original branch and add a new branch to the epilog.
316   TII->removeBranch(*KernelBB);
317   TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
318   // Add a branch to the loop exit.
319   if (EpilogBBs.size() > 0) {
320     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
321     SmallVector<MachineOperand, 4> Cond1;
322     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
323   }
324 }
325 
326 /// Replace all uses of FromReg that appear outside the specified
327 /// basic block with ToReg.
328 static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
329                                     MachineBasicBlock *MBB,
330                                     MachineRegisterInfo &MRI,
331                                     LiveIntervals &LIS) {
332   for (MachineOperand &O :
333        llvm::make_early_inc_range(MRI.use_operands(FromReg)))
334     if (O.getParent()->getParent() != MBB)
335       O.setReg(ToReg);
336   if (!LIS.hasInterval(ToReg))
337     LIS.createEmptyInterval(ToReg);
338 }
339 
340 /// Return true if the register has a use that occurs outside the
341 /// specified loop.
342 static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
343                             MachineRegisterInfo &MRI) {
344   for (const MachineOperand &MO : MRI.use_operands(Reg))
345     if (MO.getParent()->getParent() != BB)
346       return true;
347   return false;
348 }
349 
350 /// Generate Phis for the specific block in the generated pipelined code.
351 /// This function looks at the Phis from the original code to guide the
352 /// creation of new Phis.
353 void ModuloScheduleExpander::generateExistingPhis(
354     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
355     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
356     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
357   // Compute the stage number for the initial value of the Phi, which
358   // comes from the prolog. The prolog to use depends on to which kernel/
359   // epilog that we're adding the Phi.
360   unsigned PrologStage = 0;
361   unsigned PrevStage = 0;
362   bool InKernel = (LastStageNum == CurStageNum);
363   if (InKernel) {
364     PrologStage = LastStageNum - 1;
365     PrevStage = CurStageNum;
366   } else {
367     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
368     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
369   }
370 
371   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
372                                    BBE = BB->getFirstNonPHI();
373        BBI != BBE; ++BBI) {
374     Register Def = BBI->getOperand(0).getReg();
375 
376     unsigned InitVal = 0;
377     unsigned LoopVal = 0;
378     getPhiRegs(*BBI, BB, InitVal, LoopVal);
379 
380     unsigned PhiOp1 = 0;
381     // The Phi value from the loop body typically is defined in the loop, but
382     // not always. So, we need to check if the value is defined in the loop.
383     unsigned PhiOp2 = LoopVal;
384     if (VRMap[LastStageNum].count(LoopVal))
385       PhiOp2 = VRMap[LastStageNum][LoopVal];
386 
387     int StageScheduled = Schedule.getStage(&*BBI);
388     int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
389     unsigned NumStages = getStagesForReg(Def, CurStageNum);
390     if (NumStages == 0) {
391       // We don't need to generate a Phi anymore, but we need to rename any uses
392       // of the Phi value.
393       unsigned NewReg = VRMap[PrevStage][LoopVal];
394       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
395                             InitVal, NewReg);
396       if (VRMap[CurStageNum].count(LoopVal))
397         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
398     }
399     // Adjust the number of Phis needed depending on the number of prologs left,
400     // and the distance from where the Phi is first scheduled. The number of
401     // Phis cannot exceed the number of prolog stages. Each stage can
402     // potentially define two values.
403     unsigned MaxPhis = PrologStage + 2;
404     if (!InKernel && (int)PrologStage <= LoopValStage)
405       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
406     unsigned NumPhis = std::min(NumStages, MaxPhis);
407 
408     unsigned NewReg = 0;
409     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
410     // In the epilog, we may need to look back one stage to get the correct
411     // Phi name, because the epilog and prolog blocks execute the same stage.
412     // The correct name is from the previous block only when the Phi has
413     // been completely scheduled prior to the epilog, and Phi value is not
414     // needed in multiple stages.
415     int StageDiff = 0;
416     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
417         NumPhis == 1)
418       StageDiff = 1;
419     // Adjust the computations below when the phi and the loop definition
420     // are scheduled in different stages.
421     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
422       StageDiff = StageScheduled - LoopValStage;
423     for (unsigned np = 0; np < NumPhis; ++np) {
424       // If the Phi hasn't been scheduled, then use the initial Phi operand
425       // value. Otherwise, use the scheduled version of the instruction. This
426       // is a little complicated when a Phi references another Phi.
427       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
428         PhiOp1 = InitVal;
429       // Check if the Phi has already been scheduled in a prolog stage.
430       else if (PrologStage >= AccessStage + StageDiff + np &&
431                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
432         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
433       // Check if the Phi has already been scheduled, but the loop instruction
434       // is either another Phi, or doesn't occur in the loop.
435       else if (PrologStage >= AccessStage + StageDiff + np) {
436         // If the Phi references another Phi, we need to examine the other
437         // Phi to get the correct value.
438         PhiOp1 = LoopVal;
439         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
440         int Indirects = 1;
441         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
442           int PhiStage = Schedule.getStage(InstOp1);
443           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
444             PhiOp1 = getInitPhiReg(*InstOp1, BB);
445           else
446             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
447           InstOp1 = MRI.getVRegDef(PhiOp1);
448           int PhiOpStage = Schedule.getStage(InstOp1);
449           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
450           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
451               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
452             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
453             break;
454           }
455           ++Indirects;
456         }
457       } else
458         PhiOp1 = InitVal;
459       // If this references a generated Phi in the kernel, get the Phi operand
460       // from the incoming block.
461       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
462         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
463           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
464 
465       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
466       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
467       // In the epilog, a map lookup is needed to get the value from the kernel,
468       // or previous epilog block. How is does this depends on if the
469       // instruction is scheduled in the previous block.
470       if (!InKernel) {
471         int StageDiffAdj = 0;
472         if (LoopValStage != -1 && StageScheduled > LoopValStage)
473           StageDiffAdj = StageScheduled - LoopValStage;
474         // Use the loop value defined in the kernel, unless the kernel
475         // contains the last definition of the Phi.
476         if (np == 0 && PrevStage == LastStageNum &&
477             (StageScheduled != 0 || LoopValStage != 0) &&
478             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
479           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
480         // Use the value defined by the Phi. We add one because we switch
481         // from looking at the loop value to the Phi definition.
482         else if (np > 0 && PrevStage == LastStageNum &&
483                  VRMap[PrevStage - np + 1].count(Def))
484           PhiOp2 = VRMap[PrevStage - np + 1][Def];
485         // Use the loop value defined in the kernel.
486         else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
487                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
488           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
489         // Use the value defined by the Phi, unless we're generating the first
490         // epilog and the Phi refers to a Phi in a different stage.
491         else if (VRMap[PrevStage - np].count(Def) &&
492                  (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
493                   (LoopValStage == StageScheduled)))
494           PhiOp2 = VRMap[PrevStage - np][Def];
495       }
496 
497       // Check if we can reuse an existing Phi. This occurs when a Phi
498       // references another Phi, and the other Phi is scheduled in an
499       // earlier stage. We can try to reuse an existing Phi up until the last
500       // stage of the current Phi.
501       if (LoopDefIsPhi) {
502         if (static_cast<int>(PrologStage - np) >= StageScheduled) {
503           int LVNumStages = getStagesForPhi(LoopVal);
504           int StageDiff = (StageScheduled - LoopValStage);
505           LVNumStages -= StageDiff;
506           // Make sure the loop value Phi has been processed already.
507           if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
508             NewReg = PhiOp2;
509             unsigned ReuseStage = CurStageNum;
510             if (isLoopCarried(*PhiInst))
511               ReuseStage -= LVNumStages;
512             // Check if the Phi to reuse has been generated yet. If not, then
513             // there is nothing to reuse.
514             if (VRMap[ReuseStage - np].count(LoopVal)) {
515               NewReg = VRMap[ReuseStage - np][LoopVal];
516 
517               rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
518                                     Def, NewReg);
519               // Update the map with the new Phi name.
520               VRMap[CurStageNum - np][Def] = NewReg;
521               PhiOp2 = NewReg;
522               if (VRMap[LastStageNum - np - 1].count(LoopVal))
523                 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
524 
525               if (IsLast && np == NumPhis - 1)
526                 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
527               continue;
528             }
529           }
530         }
531         if (InKernel && StageDiff > 0 &&
532             VRMap[CurStageNum - StageDiff - np].count(LoopVal))
533           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
534       }
535 
536       const TargetRegisterClass *RC = MRI.getRegClass(Def);
537       NewReg = MRI.createVirtualRegister(RC);
538 
539       MachineInstrBuilder NewPhi =
540           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
541                   TII->get(TargetOpcode::PHI), NewReg);
542       NewPhi.addReg(PhiOp1).addMBB(BB1);
543       NewPhi.addReg(PhiOp2).addMBB(BB2);
544       if (np == 0)
545         InstrMap[NewPhi] = &*BBI;
546 
547       // We define the Phis after creating the new pipelined code, so
548       // we need to rename the Phi values in scheduled instructions.
549 
550       unsigned PrevReg = 0;
551       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
552         PrevReg = VRMap[PrevStage - np][LoopVal];
553       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
554                             NewReg, PrevReg);
555       // If the Phi has been scheduled, use the new name for rewriting.
556       if (VRMap[CurStageNum - np].count(Def)) {
557         unsigned R = VRMap[CurStageNum - np][Def];
558         rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
559                               NewReg);
560       }
561 
562       // Check if we need to rename any uses that occurs after the loop. The
563       // register to replace depends on whether the Phi is scheduled in the
564       // epilog.
565       if (IsLast && np == NumPhis - 1)
566         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
567 
568       // In the kernel, a dependent Phi uses the value from this Phi.
569       if (InKernel)
570         PhiOp2 = NewReg;
571 
572       // Update the map with the new Phi name.
573       VRMap[CurStageNum - np][Def] = NewReg;
574     }
575 
576     while (NumPhis++ < NumStages) {
577       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
578                             NewReg, 0);
579     }
580 
581     // Check if we need to rename a Phi that has been eliminated due to
582     // scheduling.
583     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
584       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
585   }
586 }
587 
588 /// Generate Phis for the specified block in the generated pipelined code.
589 /// These are new Phis needed because the definition is scheduled after the
590 /// use in the pipelined sequence.
591 void ModuloScheduleExpander::generatePhis(
592     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
593     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
594     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
595   // Compute the stage number that contains the initial Phi value, and
596   // the Phi from the previous stage.
597   unsigned PrologStage = 0;
598   unsigned PrevStage = 0;
599   unsigned StageDiff = CurStageNum - LastStageNum;
600   bool InKernel = (StageDiff == 0);
601   if (InKernel) {
602     PrologStage = LastStageNum - 1;
603     PrevStage = CurStageNum;
604   } else {
605     PrologStage = LastStageNum - StageDiff;
606     PrevStage = LastStageNum + StageDiff - 1;
607   }
608 
609   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
610                                    BBE = BB->instr_end();
611        BBI != BBE; ++BBI) {
612     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
613       MachineOperand &MO = BBI->getOperand(i);
614       if (!MO.isReg() || !MO.isDef() ||
615           !Register::isVirtualRegister(MO.getReg()))
616         continue;
617 
618       int StageScheduled = Schedule.getStage(&*BBI);
619       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
620       Register Def = MO.getReg();
621       unsigned NumPhis = getStagesForReg(Def, CurStageNum);
622       // An instruction scheduled in stage 0 and is used after the loop
623       // requires a phi in the epilog for the last definition from either
624       // the kernel or prolog.
625       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
626           hasUseAfterLoop(Def, BB, MRI))
627         NumPhis = 1;
628       if (!InKernel && (unsigned)StageScheduled > PrologStage)
629         continue;
630 
631       unsigned PhiOp2 = VRMap[PrevStage][Def];
632       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
633         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
634           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
635       // The number of Phis can't exceed the number of prolog stages. The
636       // prolog stage number is zero based.
637       if (NumPhis > PrologStage + 1 - StageScheduled)
638         NumPhis = PrologStage + 1 - StageScheduled;
639       for (unsigned np = 0; np < NumPhis; ++np) {
640         unsigned PhiOp1 = VRMap[PrologStage][Def];
641         if (np <= PrologStage)
642           PhiOp1 = VRMap[PrologStage - np][Def];
643         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
644           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
645             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
646           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
647             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
648         }
649         if (!InKernel)
650           PhiOp2 = VRMap[PrevStage - np][Def];
651 
652         const TargetRegisterClass *RC = MRI.getRegClass(Def);
653         Register NewReg = MRI.createVirtualRegister(RC);
654 
655         MachineInstrBuilder NewPhi =
656             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
657                     TII->get(TargetOpcode::PHI), NewReg);
658         NewPhi.addReg(PhiOp1).addMBB(BB1);
659         NewPhi.addReg(PhiOp2).addMBB(BB2);
660         if (np == 0)
661           InstrMap[NewPhi] = &*BBI;
662 
663         // Rewrite uses and update the map. The actions depend upon whether
664         // we generating code for the kernel or epilog blocks.
665         if (InKernel) {
666           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
667                                 NewReg);
668           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
669                                 NewReg);
670 
671           PhiOp2 = NewReg;
672           VRMap[PrevStage - np - 1][Def] = NewReg;
673         } else {
674           VRMap[CurStageNum - np][Def] = NewReg;
675           if (np == NumPhis - 1)
676             rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
677                                   NewReg);
678         }
679         if (IsLast && np == NumPhis - 1)
680           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
681       }
682     }
683   }
684 }
685 
686 /// Remove instructions that generate values with no uses.
687 /// Typically, these are induction variable operations that generate values
688 /// used in the loop itself.  A dead instruction has a definition with
689 /// no uses, or uses that occur in the original loop only.
690 void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
691                                                     MBBVectorTy &EpilogBBs) {
692   // For each epilog block, check that the value defined by each instruction
693   // is used.  If not, delete it.
694   for (MachineBasicBlock *MBB : llvm::reverse(EpilogBBs))
695     for (MachineBasicBlock::reverse_instr_iterator MI = MBB->instr_rbegin(),
696                                                    ME = MBB->instr_rend();
697          MI != ME;) {
698       // From DeadMachineInstructionElem. Don't delete inline assembly.
699       if (MI->isInlineAsm()) {
700         ++MI;
701         continue;
702       }
703       bool SawStore = false;
704       // Check if it's safe to remove the instruction due to side effects.
705       // We can, and want to, remove Phis here.
706       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
707         ++MI;
708         continue;
709       }
710       bool used = true;
711       for (const MachineOperand &MO : MI->operands()) {
712         if (!MO.isReg() || !MO.isDef())
713           continue;
714         Register reg = MO.getReg();
715         // Assume physical registers are used, unless they are marked dead.
716         if (Register::isPhysicalRegister(reg)) {
717           used = !MO.isDead();
718           if (used)
719             break;
720           continue;
721         }
722         unsigned realUses = 0;
723         for (const MachineOperand &U : MRI.use_operands(reg)) {
724           // Check if there are any uses that occur only in the original
725           // loop.  If so, that's not a real use.
726           if (U.getParent()->getParent() != BB) {
727             realUses++;
728             used = true;
729             break;
730           }
731         }
732         if (realUses > 0)
733           break;
734         used = false;
735       }
736       if (!used) {
737         LIS.RemoveMachineInstrFromMaps(*MI);
738         MI++->eraseFromParent();
739         continue;
740       }
741       ++MI;
742     }
743   // In the kernel block, check if we can remove a Phi that generates a value
744   // used in an instruction removed in the epilog block.
745   for (MachineInstr &MI : llvm::make_early_inc_range(KernelBB->phis())) {
746     Register reg = MI.getOperand(0).getReg();
747     if (MRI.use_begin(reg) == MRI.use_end()) {
748       LIS.RemoveMachineInstrFromMaps(MI);
749       MI.eraseFromParent();
750     }
751   }
752 }
753 
754 /// For loop carried definitions, we split the lifetime of a virtual register
755 /// that has uses past the definition in the next iteration. A copy with a new
756 /// virtual register is inserted before the definition, which helps with
757 /// generating a better register assignment.
758 ///
759 ///   v1 = phi(a, v2)     v1 = phi(a, v2)
760 ///   v2 = phi(b, v3)     v2 = phi(b, v3)
761 ///   v3 = ..             v4 = copy v1
762 ///   .. = V1             v3 = ..
763 ///                       .. = v4
764 void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
765                                             MBBVectorTy &EpilogBBs) {
766   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
767   for (auto &PHI : KernelBB->phis()) {
768     Register Def = PHI.getOperand(0).getReg();
769     // Check for any Phi definition that used as an operand of another Phi
770     // in the same block.
771     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
772                                                  E = MRI.use_instr_end();
773          I != E; ++I) {
774       if (I->isPHI() && I->getParent() == KernelBB) {
775         // Get the loop carried definition.
776         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
777         if (!LCDef)
778           continue;
779         MachineInstr *MI = MRI.getVRegDef(LCDef);
780         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
781           continue;
782         // Search through the rest of the block looking for uses of the Phi
783         // definition. If one occurs, then split the lifetime.
784         unsigned SplitReg = 0;
785         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
786                                     KernelBB->instr_end()))
787           if (BBJ.readsRegister(Def)) {
788             // We split the lifetime when we find the first use.
789             if (SplitReg == 0) {
790               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
791               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
792                       TII->get(TargetOpcode::COPY), SplitReg)
793                   .addReg(Def);
794             }
795             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
796           }
797         if (!SplitReg)
798           continue;
799         // Search through each of the epilog blocks for any uses to be renamed.
800         for (auto &Epilog : EpilogBBs)
801           for (auto &I : *Epilog)
802             if (I.readsRegister(Def))
803               I.substituteRegister(Def, SplitReg, 0, *TRI);
804         break;
805       }
806     }
807   }
808 }
809 
810 /// Remove the incoming block from the Phis in a basic block.
811 static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
812   for (MachineInstr &MI : *BB) {
813     if (!MI.isPHI())
814       break;
815     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
816       if (MI.getOperand(i + 1).getMBB() == Incoming) {
817         MI.RemoveOperand(i + 1);
818         MI.RemoveOperand(i);
819         break;
820       }
821   }
822 }
823 
824 /// Create branches from each prolog basic block to the appropriate epilog
825 /// block.  These edges are needed if the loop ends before reaching the
826 /// kernel.
827 void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
828                                          MBBVectorTy &PrologBBs,
829                                          MachineBasicBlock *KernelBB,
830                                          MBBVectorTy &EpilogBBs,
831                                          ValueMapTy *VRMap) {
832   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
833   MachineBasicBlock *LastPro = KernelBB;
834   MachineBasicBlock *LastEpi = KernelBB;
835 
836   // Start from the blocks connected to the kernel and work "out"
837   // to the first prolog and the last epilog blocks.
838   SmallVector<MachineInstr *, 4> PrevInsts;
839   unsigned MaxIter = PrologBBs.size() - 1;
840   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
841     // Add branches to the prolog that go to the corresponding
842     // epilog, and the fall-thru prolog/kernel block.
843     MachineBasicBlock *Prolog = PrologBBs[j];
844     MachineBasicBlock *Epilog = EpilogBBs[i];
845 
846     SmallVector<MachineOperand, 4> Cond;
847     Optional<bool> StaticallyGreater =
848         LoopInfo->createTripCountGreaterCondition(j + 1, *Prolog, Cond);
849     unsigned numAdded = 0;
850     if (!StaticallyGreater.hasValue()) {
851       Prolog->addSuccessor(Epilog);
852       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
853     } else if (*StaticallyGreater == false) {
854       Prolog->addSuccessor(Epilog);
855       Prolog->removeSuccessor(LastPro);
856       LastEpi->removeSuccessor(Epilog);
857       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
858       removePhis(Epilog, LastEpi);
859       // Remove the blocks that are no longer referenced.
860       if (LastPro != LastEpi) {
861         LastEpi->clear();
862         LastEpi->eraseFromParent();
863       }
864       if (LastPro == KernelBB) {
865         LoopInfo->disposed();
866         NewKernel = nullptr;
867       }
868       LastPro->clear();
869       LastPro->eraseFromParent();
870     } else {
871       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
872       removePhis(Epilog, Prolog);
873     }
874     LastPro = Prolog;
875     LastEpi = Epilog;
876     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
877                                                    E = Prolog->instr_rend();
878          I != E && numAdded > 0; ++I, --numAdded)
879       updateInstruction(&*I, false, j, 0, VRMap);
880   }
881 
882   if (NewKernel) {
883     LoopInfo->setPreheader(PrologBBs[MaxIter]);
884     LoopInfo->adjustTripCount(-(MaxIter + 1));
885   }
886 }
887 
888 /// Return true if we can compute the amount the instruction changes
889 /// during each iteration. Set Delta to the amount of the change.
890 bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
891   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
892   const MachineOperand *BaseOp;
893   int64_t Offset;
894   bool OffsetIsScalable;
895   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
896     return false;
897 
898   // FIXME: This algorithm assumes instructions have fixed-size offsets.
899   if (OffsetIsScalable)
900     return false;
901 
902   if (!BaseOp->isReg())
903     return false;
904 
905   Register BaseReg = BaseOp->getReg();
906 
907   MachineRegisterInfo &MRI = MF.getRegInfo();
908   // Check if there is a Phi. If so, get the definition in the loop.
909   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
910   if (BaseDef && BaseDef->isPHI()) {
911     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
912     BaseDef = MRI.getVRegDef(BaseReg);
913   }
914   if (!BaseDef)
915     return false;
916 
917   int D = 0;
918   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
919     return false;
920 
921   Delta = D;
922   return true;
923 }
924 
925 /// Update the memory operand with a new offset when the pipeliner
926 /// generates a new copy of the instruction that refers to a
927 /// different memory location.
928 void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
929                                                MachineInstr &OldMI,
930                                                unsigned Num) {
931   if (Num == 0)
932     return;
933   // If the instruction has memory operands, then adjust the offset
934   // when the instruction appears in different stages.
935   if (NewMI.memoperands_empty())
936     return;
937   SmallVector<MachineMemOperand *, 2> NewMMOs;
938   for (MachineMemOperand *MMO : NewMI.memoperands()) {
939     // TODO: Figure out whether isAtomic is really necessary (see D57601).
940     if (MMO->isVolatile() || MMO->isAtomic() ||
941         (MMO->isInvariant() && MMO->isDereferenceable()) ||
942         (!MMO->getValue())) {
943       NewMMOs.push_back(MMO);
944       continue;
945     }
946     unsigned Delta;
947     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
948       int64_t AdjOffset = Delta * Num;
949       NewMMOs.push_back(
950           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
951     } else {
952       NewMMOs.push_back(
953           MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
954     }
955   }
956   NewMI.setMemRefs(MF, NewMMOs);
957 }
958 
959 /// Clone the instruction for the new pipelined loop and update the
960 /// memory operands, if needed.
961 MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
962                                                  unsigned CurStageNum,
963                                                  unsigned InstStageNum) {
964   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
965   // Check for tied operands in inline asm instructions. This should be handled
966   // elsewhere, but I'm not sure of the best solution.
967   if (OldMI->isInlineAsm())
968     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
969       const auto &MO = OldMI->getOperand(i);
970       if (MO.isReg() && MO.isUse())
971         break;
972       unsigned UseIdx;
973       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
974         NewMI->tieOperands(i, UseIdx);
975     }
976   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
977   return NewMI;
978 }
979 
980 /// Clone the instruction for the new pipelined loop. If needed, this
981 /// function updates the instruction using the values saved in the
982 /// InstrChanges structure.
983 MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
984     MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
985   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
986   auto It = InstrChanges.find(OldMI);
987   if (It != InstrChanges.end()) {
988     std::pair<unsigned, int64_t> RegAndOffset = It->second;
989     unsigned BasePos, OffsetPos;
990     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
991       return nullptr;
992     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
993     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
994     if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
995       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
996     NewMI->getOperand(OffsetPos).setImm(NewOffset);
997   }
998   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
999   return NewMI;
1000 }
1001 
1002 /// Update the machine instruction with new virtual registers.  This
1003 /// function may change the defintions and/or uses.
1004 void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
1005                                                bool LastDef,
1006                                                unsigned CurStageNum,
1007                                                unsigned InstrStageNum,
1008                                                ValueMapTy *VRMap) {
1009   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
1010     MachineOperand &MO = NewMI->getOperand(i);
1011     if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
1012       continue;
1013     Register reg = MO.getReg();
1014     if (MO.isDef()) {
1015       // Create a new virtual register for the definition.
1016       const TargetRegisterClass *RC = MRI.getRegClass(reg);
1017       Register NewReg = MRI.createVirtualRegister(RC);
1018       MO.setReg(NewReg);
1019       VRMap[CurStageNum][reg] = NewReg;
1020       if (LastDef)
1021         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
1022     } else if (MO.isUse()) {
1023       MachineInstr *Def = MRI.getVRegDef(reg);
1024       // Compute the stage that contains the last definition for instruction.
1025       int DefStageNum = Schedule.getStage(Def);
1026       unsigned StageNum = CurStageNum;
1027       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
1028         // Compute the difference in stages between the defintion and the use.
1029         unsigned StageDiff = (InstrStageNum - DefStageNum);
1030         // Make an adjustment to get the last definition.
1031         StageNum -= StageDiff;
1032       }
1033       if (VRMap[StageNum].count(reg))
1034         MO.setReg(VRMap[StageNum][reg]);
1035     }
1036   }
1037 }
1038 
1039 /// Return the instruction in the loop that defines the register.
1040 /// If the definition is a Phi, then follow the Phi operand to
1041 /// the instruction in the loop.
1042 MachineInstr *ModuloScheduleExpander::findDefInLoop(unsigned Reg) {
1043   SmallPtrSet<MachineInstr *, 8> Visited;
1044   MachineInstr *Def = MRI.getVRegDef(Reg);
1045   while (Def->isPHI()) {
1046     if (!Visited.insert(Def).second)
1047       break;
1048     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
1049       if (Def->getOperand(i + 1).getMBB() == BB) {
1050         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
1051         break;
1052       }
1053   }
1054   return Def;
1055 }
1056 
1057 /// Return the new name for the value from the previous stage.
1058 unsigned ModuloScheduleExpander::getPrevMapVal(
1059     unsigned StageNum, unsigned PhiStage, unsigned LoopVal, unsigned LoopStage,
1060     ValueMapTy *VRMap, MachineBasicBlock *BB) {
1061   unsigned PrevVal = 0;
1062   if (StageNum > PhiStage) {
1063     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
1064     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
1065       // The name is defined in the previous stage.
1066       PrevVal = VRMap[StageNum - 1][LoopVal];
1067     else if (VRMap[StageNum].count(LoopVal))
1068       // The previous name is defined in the current stage when the instruction
1069       // order is swapped.
1070       PrevVal = VRMap[StageNum][LoopVal];
1071     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
1072       // The loop value hasn't yet been scheduled.
1073       PrevVal = LoopVal;
1074     else if (StageNum == PhiStage + 1)
1075       // The loop value is another phi, which has not been scheduled.
1076       PrevVal = getInitPhiReg(*LoopInst, BB);
1077     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
1078       // The loop value is another phi, which has been scheduled.
1079       PrevVal =
1080           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
1081                         LoopStage, VRMap, BB);
1082   }
1083   return PrevVal;
1084 }
1085 
1086 /// Rewrite the Phi values in the specified block to use the mappings
1087 /// from the initial operand. Once the Phi is scheduled, we switch
1088 /// to using the loop value instead of the Phi value, so those names
1089 /// do not need to be rewritten.
1090 void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
1091                                               unsigned StageNum,
1092                                               ValueMapTy *VRMap,
1093                                               InstrMapTy &InstrMap) {
1094   for (auto &PHI : BB->phis()) {
1095     unsigned InitVal = 0;
1096     unsigned LoopVal = 0;
1097     getPhiRegs(PHI, BB, InitVal, LoopVal);
1098     Register PhiDef = PHI.getOperand(0).getReg();
1099 
1100     unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
1101     unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
1102     unsigned NumPhis = getStagesForPhi(PhiDef);
1103     if (NumPhis > StageNum)
1104       NumPhis = StageNum;
1105     for (unsigned np = 0; np <= NumPhis; ++np) {
1106       unsigned NewVal =
1107           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
1108       if (!NewVal)
1109         NewVal = InitVal;
1110       rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
1111                             NewVal);
1112     }
1113   }
1114 }
1115 
1116 /// Rewrite a previously scheduled instruction to use the register value
1117 /// from the new instruction. Make sure the instruction occurs in the
1118 /// basic block, and we don't change the uses in the new instruction.
1119 void ModuloScheduleExpander::rewriteScheduledInstr(
1120     MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
1121     unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, unsigned NewReg,
1122     unsigned PrevReg) {
1123   bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
1124   int StagePhi = Schedule.getStage(Phi) + PhiNum;
1125   // Rewrite uses that have been scheduled already to use the new
1126   // Phi register.
1127   for (MachineOperand &UseOp :
1128        llvm::make_early_inc_range(MRI.use_operands(OldReg))) {
1129     MachineInstr *UseMI = UseOp.getParent();
1130     if (UseMI->getParent() != BB)
1131       continue;
1132     if (UseMI->isPHI()) {
1133       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
1134         continue;
1135       if (getLoopPhiReg(*UseMI, BB) != OldReg)
1136         continue;
1137     }
1138     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
1139     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
1140     MachineInstr *OrigMI = OrigInstr->second;
1141     int StageSched = Schedule.getStage(OrigMI);
1142     int CycleSched = Schedule.getCycle(OrigMI);
1143     unsigned ReplaceReg = 0;
1144     // This is the stage for the scheduled instruction.
1145     if (StagePhi == StageSched && Phi->isPHI()) {
1146       int CyclePhi = Schedule.getCycle(Phi);
1147       if (PrevReg && InProlog)
1148         ReplaceReg = PrevReg;
1149       else if (PrevReg && !isLoopCarried(*Phi) &&
1150                (CyclePhi <= CycleSched || OrigMI->isPHI()))
1151         ReplaceReg = PrevReg;
1152       else
1153         ReplaceReg = NewReg;
1154     }
1155     // The scheduled instruction occurs before the scheduled Phi, and the
1156     // Phi is not loop carried.
1157     if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
1158       ReplaceReg = NewReg;
1159     if (StagePhi > StageSched && Phi->isPHI())
1160       ReplaceReg = NewReg;
1161     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
1162       ReplaceReg = NewReg;
1163     if (ReplaceReg) {
1164       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
1165       UseOp.setReg(ReplaceReg);
1166     }
1167   }
1168 }
1169 
1170 bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
1171   if (!Phi.isPHI())
1172     return false;
1173   int DefCycle = Schedule.getCycle(&Phi);
1174   int DefStage = Schedule.getStage(&Phi);
1175 
1176   unsigned InitVal = 0;
1177   unsigned LoopVal = 0;
1178   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
1179   MachineInstr *Use = MRI.getVRegDef(LoopVal);
1180   if (!Use || Use->isPHI())
1181     return true;
1182   int LoopCycle = Schedule.getCycle(Use);
1183   int LoopStage = Schedule.getStage(Use);
1184   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
1185 }
1186 
1187 //===----------------------------------------------------------------------===//
1188 // PeelingModuloScheduleExpander implementation
1189 //===----------------------------------------------------------------------===//
1190 // This is a reimplementation of ModuloScheduleExpander that works by creating
1191 // a fully correct steady-state kernel and peeling off the prolog and epilogs.
1192 //===----------------------------------------------------------------------===//
1193 
1194 namespace {
1195 // Remove any dead phis in MBB. Dead phis either have only one block as input
1196 // (in which case they are the identity) or have no uses.
1197 void EliminateDeadPhis(MachineBasicBlock *MBB, MachineRegisterInfo &MRI,
1198                        LiveIntervals *LIS, bool KeepSingleSrcPhi = false) {
1199   bool Changed = true;
1200   while (Changed) {
1201     Changed = false;
1202     for (MachineInstr &MI : llvm::make_early_inc_range(MBB->phis())) {
1203       assert(MI.isPHI());
1204       if (MRI.use_empty(MI.getOperand(0).getReg())) {
1205         if (LIS)
1206           LIS->RemoveMachineInstrFromMaps(MI);
1207         MI.eraseFromParent();
1208         Changed = true;
1209       } else if (!KeepSingleSrcPhi && MI.getNumExplicitOperands() == 3) {
1210         MRI.constrainRegClass(MI.getOperand(1).getReg(),
1211                               MRI.getRegClass(MI.getOperand(0).getReg()));
1212         MRI.replaceRegWith(MI.getOperand(0).getReg(),
1213                            MI.getOperand(1).getReg());
1214         if (LIS)
1215           LIS->RemoveMachineInstrFromMaps(MI);
1216         MI.eraseFromParent();
1217         Changed = true;
1218       }
1219     }
1220   }
1221 }
1222 
1223 /// Rewrites the kernel block in-place to adhere to the given schedule.
1224 /// KernelRewriter holds all of the state required to perform the rewriting.
1225 class KernelRewriter {
1226   ModuloSchedule &S;
1227   MachineBasicBlock *BB;
1228   MachineBasicBlock *PreheaderBB, *ExitBB;
1229   MachineRegisterInfo &MRI;
1230   const TargetInstrInfo *TII;
1231   LiveIntervals *LIS;
1232 
1233   // Map from register class to canonical undef register for that class.
1234   DenseMap<const TargetRegisterClass *, Register> Undefs;
1235   // Map from <LoopReg, InitReg> to phi register for all created phis. Note that
1236   // this map is only used when InitReg is non-undef.
1237   DenseMap<std::pair<unsigned, unsigned>, Register> Phis;
1238   // Map from LoopReg to phi register where the InitReg is undef.
1239   DenseMap<Register, Register> UndefPhis;
1240 
1241   // Reg is used by MI. Return the new register MI should use to adhere to the
1242   // schedule. Insert phis as necessary.
1243   Register remapUse(Register Reg, MachineInstr &MI);
1244   // Insert a phi that carries LoopReg from the loop body and InitReg otherwise.
1245   // If InitReg is not given it is chosen arbitrarily. It will either be undef
1246   // or will be chosen so as to share another phi.
1247   Register phi(Register LoopReg, Optional<Register> InitReg = {},
1248                const TargetRegisterClass *RC = nullptr);
1249   // Create an undef register of the given register class.
1250   Register undef(const TargetRegisterClass *RC);
1251 
1252 public:
1253   KernelRewriter(MachineLoop &L, ModuloSchedule &S, MachineBasicBlock *LoopBB,
1254                  LiveIntervals *LIS = nullptr);
1255   void rewrite();
1256 };
1257 } // namespace
1258 
1259 KernelRewriter::KernelRewriter(MachineLoop &L, ModuloSchedule &S,
1260                                MachineBasicBlock *LoopBB, LiveIntervals *LIS)
1261     : S(S), BB(LoopBB), PreheaderBB(L.getLoopPreheader()),
1262       ExitBB(L.getExitBlock()), MRI(BB->getParent()->getRegInfo()),
1263       TII(BB->getParent()->getSubtarget().getInstrInfo()), LIS(LIS) {
1264   PreheaderBB = *BB->pred_begin();
1265   if (PreheaderBB == BB)
1266     PreheaderBB = *std::next(BB->pred_begin());
1267 }
1268 
1269 void KernelRewriter::rewrite() {
1270   // Rearrange the loop to be in schedule order. Note that the schedule may
1271   // contain instructions that are not owned by the loop block (InstrChanges and
1272   // friends), so we gracefully handle unowned instructions and delete any
1273   // instructions that weren't in the schedule.
1274   auto InsertPt = BB->getFirstTerminator();
1275   MachineInstr *FirstMI = nullptr;
1276   for (MachineInstr *MI : S.getInstructions()) {
1277     if (MI->isPHI())
1278       continue;
1279     if (MI->getParent())
1280       MI->removeFromParent();
1281     BB->insert(InsertPt, MI);
1282     if (!FirstMI)
1283       FirstMI = MI;
1284   }
1285   assert(FirstMI && "Failed to find first MI in schedule");
1286 
1287   // At this point all of the scheduled instructions are between FirstMI
1288   // and the end of the block. Kill from the first non-phi to FirstMI.
1289   for (auto I = BB->getFirstNonPHI(); I != FirstMI->getIterator();) {
1290     if (LIS)
1291       LIS->RemoveMachineInstrFromMaps(*I);
1292     (I++)->eraseFromParent();
1293   }
1294 
1295   // Now remap every instruction in the loop.
1296   for (MachineInstr &MI : *BB) {
1297     if (MI.isPHI() || MI.isTerminator())
1298       continue;
1299     for (MachineOperand &MO : MI.uses()) {
1300       if (!MO.isReg() || MO.getReg().isPhysical() || MO.isImplicit())
1301         continue;
1302       Register Reg = remapUse(MO.getReg(), MI);
1303       MO.setReg(Reg);
1304     }
1305   }
1306   EliminateDeadPhis(BB, MRI, LIS);
1307 
1308   // Ensure a phi exists for all instructions that are either referenced by
1309   // an illegal phi or by an instruction outside the loop. This allows us to
1310   // treat remaps of these values the same as "normal" values that come from
1311   // loop-carried phis.
1312   for (auto MI = BB->getFirstNonPHI(); MI != BB->end(); ++MI) {
1313     if (MI->isPHI()) {
1314       Register R = MI->getOperand(0).getReg();
1315       phi(R);
1316       continue;
1317     }
1318 
1319     for (MachineOperand &Def : MI->defs()) {
1320       for (MachineInstr &MI : MRI.use_instructions(Def.getReg())) {
1321         if (MI.getParent() != BB) {
1322           phi(Def.getReg());
1323           break;
1324         }
1325       }
1326     }
1327   }
1328 }
1329 
1330 Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
1331   MachineInstr *Producer = MRI.getUniqueVRegDef(Reg);
1332   if (!Producer)
1333     return Reg;
1334 
1335   int ConsumerStage = S.getStage(&MI);
1336   if (!Producer->isPHI()) {
1337     // Non-phi producers are simple to remap. Insert as many phis as the
1338     // difference between the consumer and producer stages.
1339     if (Producer->getParent() != BB)
1340       // Producer was not inside the loop. Use the register as-is.
1341       return Reg;
1342     int ProducerStage = S.getStage(Producer);
1343     assert(ConsumerStage != -1 &&
1344            "In-loop consumer should always be scheduled!");
1345     assert(ConsumerStage >= ProducerStage);
1346     unsigned StageDiff = ConsumerStage - ProducerStage;
1347 
1348     for (unsigned I = 0; I < StageDiff; ++I)
1349       Reg = phi(Reg);
1350     return Reg;
1351   }
1352 
1353   // First, dive through the phi chain to find the defaults for the generated
1354   // phis.
1355   SmallVector<Optional<Register>, 4> Defaults;
1356   Register LoopReg = Reg;
1357   auto LoopProducer = Producer;
1358   while (LoopProducer->isPHI() && LoopProducer->getParent() == BB) {
1359     LoopReg = getLoopPhiReg(*LoopProducer, BB);
1360     Defaults.emplace_back(getInitPhiReg(*LoopProducer, BB));
1361     LoopProducer = MRI.getUniqueVRegDef(LoopReg);
1362     assert(LoopProducer);
1363   }
1364   int LoopProducerStage = S.getStage(LoopProducer);
1365 
1366   Optional<Register> IllegalPhiDefault;
1367 
1368   if (LoopProducerStage == -1) {
1369     // Do nothing.
1370   } else if (LoopProducerStage > ConsumerStage) {
1371     // This schedule is only representable if ProducerStage == ConsumerStage+1.
1372     // In addition, Consumer's cycle must be scheduled after Producer in the
1373     // rescheduled loop. This is enforced by the pipeliner's ASAP and ALAP
1374     // functions.
1375 #ifndef NDEBUG // Silence unused variables in non-asserts mode.
1376     int LoopProducerCycle = S.getCycle(LoopProducer);
1377     int ConsumerCycle = S.getCycle(&MI);
1378 #endif
1379     assert(LoopProducerCycle <= ConsumerCycle);
1380     assert(LoopProducerStage == ConsumerStage + 1);
1381     // Peel off the first phi from Defaults and insert a phi between producer
1382     // and consumer. This phi will not be at the front of the block so we
1383     // consider it illegal. It will only exist during the rewrite process; it
1384     // needs to exist while we peel off prologs because these could take the
1385     // default value. After that we can replace all uses with the loop producer
1386     // value.
1387     IllegalPhiDefault = Defaults.front();
1388     Defaults.erase(Defaults.begin());
1389   } else {
1390     assert(ConsumerStage >= LoopProducerStage);
1391     int StageDiff = ConsumerStage - LoopProducerStage;
1392     if (StageDiff > 0) {
1393       LLVM_DEBUG(dbgs() << " -- padding defaults array from " << Defaults.size()
1394                         << " to " << (Defaults.size() + StageDiff) << "\n");
1395       // If we need more phis than we have defaults for, pad out with undefs for
1396       // the earliest phis, which are at the end of the defaults chain (the
1397       // chain is in reverse order).
1398       Defaults.resize(Defaults.size() + StageDiff, Defaults.empty()
1399                                                        ? Optional<Register>()
1400                                                        : Defaults.back());
1401     }
1402   }
1403 
1404   // Now we know the number of stages to jump back, insert the phi chain.
1405   auto DefaultI = Defaults.rbegin();
1406   while (DefaultI != Defaults.rend())
1407     LoopReg = phi(LoopReg, *DefaultI++, MRI.getRegClass(Reg));
1408 
1409   if (IllegalPhiDefault.hasValue()) {
1410     // The consumer optionally consumes LoopProducer in the same iteration
1411     // (because the producer is scheduled at an earlier cycle than the consumer)
1412     // or the initial value. To facilitate this we create an illegal block here
1413     // by embedding a phi in the middle of the block. We will fix this up
1414     // immediately prior to pruning.
1415     auto RC = MRI.getRegClass(Reg);
1416     Register R = MRI.createVirtualRegister(RC);
1417     MachineInstr *IllegalPhi =
1418         BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1419             .addReg(IllegalPhiDefault.getValue())
1420             .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
1421             .addReg(LoopReg)
1422             .addMBB(BB); // Block choice is arbitrary and has no effect.
1423     // Illegal phi should belong to the producer stage so that it can be
1424     // filtered correctly during peeling.
1425     S.setStage(IllegalPhi, LoopProducerStage);
1426     return R;
1427   }
1428 
1429   return LoopReg;
1430 }
1431 
1432 Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
1433                              const TargetRegisterClass *RC) {
1434   // If the init register is not undef, try and find an existing phi.
1435   if (InitReg.hasValue()) {
1436     auto I = Phis.find({LoopReg, InitReg.getValue()});
1437     if (I != Phis.end())
1438       return I->second;
1439   } else {
1440     for (auto &KV : Phis) {
1441       if (KV.first.first == LoopReg)
1442         return KV.second;
1443     }
1444   }
1445 
1446   // InitReg is either undef or no existing phi takes InitReg as input. Try and
1447   // find a phi that takes undef as input.
1448   auto I = UndefPhis.find(LoopReg);
1449   if (I != UndefPhis.end()) {
1450     Register R = I->second;
1451     if (!InitReg.hasValue())
1452       // Found a phi taking undef as input, and this input is undef so return
1453       // without any more changes.
1454       return R;
1455     // Found a phi taking undef as input, so rewrite it to take InitReg.
1456     MachineInstr *MI = MRI.getVRegDef(R);
1457     MI->getOperand(1).setReg(InitReg.getValue());
1458     Phis.insert({{LoopReg, InitReg.getValue()}, R});
1459     MRI.constrainRegClass(R, MRI.getRegClass(InitReg.getValue()));
1460     UndefPhis.erase(I);
1461     return R;
1462   }
1463 
1464   // Failed to find any existing phi to reuse, so create a new one.
1465   if (!RC)
1466     RC = MRI.getRegClass(LoopReg);
1467   Register R = MRI.createVirtualRegister(RC);
1468   if (InitReg.hasValue())
1469     MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
1470   BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
1471       .addReg(InitReg.hasValue() ? *InitReg : undef(RC))
1472       .addMBB(PreheaderBB)
1473       .addReg(LoopReg)
1474       .addMBB(BB);
1475   if (!InitReg.hasValue())
1476     UndefPhis[LoopReg] = R;
1477   else
1478     Phis[{LoopReg, *InitReg}] = R;
1479   return R;
1480 }
1481 
1482 Register KernelRewriter::undef(const TargetRegisterClass *RC) {
1483   Register &R = Undefs[RC];
1484   if (R == 0) {
1485     // Create an IMPLICIT_DEF that defines this register if we need it.
1486     // All uses of this should be removed by the time we have finished unrolling
1487     // prologs and epilogs.
1488     R = MRI.createVirtualRegister(RC);
1489     auto *InsertBB = &PreheaderBB->getParent()->front();
1490     BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
1491             TII->get(TargetOpcode::IMPLICIT_DEF), R);
1492   }
1493   return R;
1494 }
1495 
1496 namespace {
1497 /// Describes an operand in the kernel of a pipelined loop. Characteristics of
1498 /// the operand are discovered, such as how many in-loop PHIs it has to jump
1499 /// through and defaults for these phis.
1500 class KernelOperandInfo {
1501   MachineBasicBlock *BB;
1502   MachineRegisterInfo &MRI;
1503   SmallVector<Register, 4> PhiDefaults;
1504   MachineOperand *Source;
1505   MachineOperand *Target;
1506 
1507 public:
1508   KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
1509                     const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
1510       : MRI(MRI) {
1511     Source = MO;
1512     BB = MO->getParent()->getParent();
1513     while (isRegInLoop(MO)) {
1514       MachineInstr *MI = MRI.getVRegDef(MO->getReg());
1515       if (MI->isFullCopy()) {
1516         MO = &MI->getOperand(1);
1517         continue;
1518       }
1519       if (!MI->isPHI())
1520         break;
1521       // If this is an illegal phi, don't count it in distance.
1522       if (IllegalPhis.count(MI)) {
1523         MO = &MI->getOperand(3);
1524         continue;
1525       }
1526 
1527       Register Default = getInitPhiReg(*MI, BB);
1528       MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
1529                                             : &MI->getOperand(3);
1530       PhiDefaults.push_back(Default);
1531     }
1532     Target = MO;
1533   }
1534 
1535   bool operator==(const KernelOperandInfo &Other) const {
1536     return PhiDefaults.size() == Other.PhiDefaults.size();
1537   }
1538 
1539   void print(raw_ostream &OS) const {
1540     OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
1541        << *Source->getParent();
1542   }
1543 
1544 private:
1545   bool isRegInLoop(MachineOperand *MO) {
1546     return MO->isReg() && MO->getReg().isVirtual() &&
1547            MRI.getVRegDef(MO->getReg())->getParent() == BB;
1548   }
1549 };
1550 } // namespace
1551 
1552 MachineBasicBlock *
1553 PeelingModuloScheduleExpander::peelKernel(LoopPeelDirection LPD) {
1554   MachineBasicBlock *NewBB = PeelSingleBlockLoop(LPD, BB, MRI, TII);
1555   if (LPD == LPD_Front)
1556     PeeledFront.push_back(NewBB);
1557   else
1558     PeeledBack.push_front(NewBB);
1559   for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
1560        ++I, ++NI) {
1561     CanonicalMIs[&*I] = &*I;
1562     CanonicalMIs[&*NI] = &*I;
1563     BlockMIs[{NewBB, &*I}] = &*NI;
1564     BlockMIs[{BB, &*I}] = &*I;
1565   }
1566   return NewBB;
1567 }
1568 
1569 void PeelingModuloScheduleExpander::filterInstructions(MachineBasicBlock *MB,
1570                                                        int MinStage) {
1571   for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
1572        I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
1573     MachineInstr *MI = &*I++;
1574     int Stage = getStage(MI);
1575     if (Stage == -1 || Stage >= MinStage)
1576       continue;
1577 
1578     for (MachineOperand &DefMO : MI->defs()) {
1579       SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1580       for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1581         // Only PHIs can use values from this block by construction.
1582         // Match with the equivalent PHI in B.
1583         assert(UseMI.isPHI());
1584         Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1585                                                MI->getParent());
1586         Subs.emplace_back(&UseMI, Reg);
1587       }
1588       for (auto &Sub : Subs)
1589         Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1590                                       *MRI.getTargetRegisterInfo());
1591     }
1592     if (LIS)
1593       LIS->RemoveMachineInstrFromMaps(*MI);
1594     MI->eraseFromParent();
1595   }
1596 }
1597 
1598 void PeelingModuloScheduleExpander::moveStageBetweenBlocks(
1599     MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
1600   auto InsertPt = DestBB->getFirstNonPHI();
1601   DenseMap<Register, Register> Remaps;
1602   for (MachineInstr &MI : llvm::make_early_inc_range(
1603            llvm::make_range(SourceBB->getFirstNonPHI(), SourceBB->end()))) {
1604     if (MI.isPHI()) {
1605       // This is an illegal PHI. If we move any instructions using an illegal
1606       // PHI, we need to create a legal Phi.
1607       if (getStage(&MI) != Stage) {
1608         // The legal Phi is not necessary if the illegal phi's stage
1609         // is being moved.
1610         Register PhiR = MI.getOperand(0).getReg();
1611         auto RC = MRI.getRegClass(PhiR);
1612         Register NR = MRI.createVirtualRegister(RC);
1613         MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(),
1614                                    DebugLoc(), TII->get(TargetOpcode::PHI), NR)
1615                                .addReg(PhiR)
1616                                .addMBB(SourceBB);
1617         BlockMIs[{DestBB, CanonicalMIs[&MI]}] = NI;
1618         CanonicalMIs[NI] = CanonicalMIs[&MI];
1619         Remaps[PhiR] = NR;
1620       }
1621     }
1622     if (getStage(&MI) != Stage)
1623       continue;
1624     MI.removeFromParent();
1625     DestBB->insert(InsertPt, &MI);
1626     auto *KernelMI = CanonicalMIs[&MI];
1627     BlockMIs[{DestBB, KernelMI}] = &MI;
1628     BlockMIs.erase({SourceBB, KernelMI});
1629   }
1630   SmallVector<MachineInstr *, 4> PhiToDelete;
1631   for (MachineInstr &MI : DestBB->phis()) {
1632     assert(MI.getNumOperands() == 3);
1633     MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
1634     // If the instruction referenced by the phi is moved inside the block
1635     // we don't need the phi anymore.
1636     if (getStage(Def) == Stage) {
1637       Register PhiReg = MI.getOperand(0).getReg();
1638       assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg()) != -1);
1639       MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
1640       MI.getOperand(0).setReg(PhiReg);
1641       PhiToDelete.push_back(&MI);
1642     }
1643   }
1644   for (auto *P : PhiToDelete)
1645     P->eraseFromParent();
1646   InsertPt = DestBB->getFirstNonPHI();
1647   // Helper to clone Phi instructions into the destination block. We clone Phi
1648   // greedily to avoid combinatorial explosion of Phi instructions.
1649   auto clonePhi = [&](MachineInstr *Phi) {
1650     MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
1651     DestBB->insert(InsertPt, NewMI);
1652     Register OrigR = Phi->getOperand(0).getReg();
1653     Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
1654     NewMI->getOperand(0).setReg(R);
1655     NewMI->getOperand(1).setReg(OrigR);
1656     NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
1657     Remaps[OrigR] = R;
1658     CanonicalMIs[NewMI] = CanonicalMIs[Phi];
1659     BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
1660     PhiNodeLoopIteration[NewMI] = PhiNodeLoopIteration[Phi];
1661     return R;
1662   };
1663   for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
1664     for (MachineOperand &MO : I->uses()) {
1665       if (!MO.isReg())
1666         continue;
1667       if (Remaps.count(MO.getReg()))
1668         MO.setReg(Remaps[MO.getReg()]);
1669       else {
1670         // If we are using a phi from the source block we need to add a new phi
1671         // pointing to the old one.
1672         MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
1673         if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
1674           Register R = clonePhi(Use);
1675           MO.setReg(R);
1676         }
1677       }
1678     }
1679   }
1680 }
1681 
1682 Register
1683 PeelingModuloScheduleExpander::getPhiCanonicalReg(MachineInstr *CanonicalPhi,
1684                                                   MachineInstr *Phi) {
1685   unsigned distance = PhiNodeLoopIteration[Phi];
1686   MachineInstr *CanonicalUse = CanonicalPhi;
1687   Register CanonicalUseReg = CanonicalUse->getOperand(0).getReg();
1688   for (unsigned I = 0; I < distance; ++I) {
1689     assert(CanonicalUse->isPHI());
1690     assert(CanonicalUse->getNumOperands() == 5);
1691     unsigned LoopRegIdx = 3, InitRegIdx = 1;
1692     if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
1693       std::swap(LoopRegIdx, InitRegIdx);
1694     CanonicalUseReg = CanonicalUse->getOperand(LoopRegIdx).getReg();
1695     CanonicalUse = MRI.getVRegDef(CanonicalUseReg);
1696   }
1697   return CanonicalUseReg;
1698 }
1699 
1700 void PeelingModuloScheduleExpander::peelPrologAndEpilogs() {
1701   BitVector LS(Schedule.getNumStages(), true);
1702   BitVector AS(Schedule.getNumStages(), true);
1703   LiveStages[BB] = LS;
1704   AvailableStages[BB] = AS;
1705 
1706   // Peel out the prologs.
1707   LS.reset();
1708   for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
1709     LS[I] = 1;
1710     Prologs.push_back(peelKernel(LPD_Front));
1711     LiveStages[Prologs.back()] = LS;
1712     AvailableStages[Prologs.back()] = LS;
1713   }
1714 
1715   // Create a block that will end up as the new loop exiting block (dominated by
1716   // all prologs and epilogs). It will only contain PHIs, in the same order as
1717   // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
1718   // that the exiting block is a (sub) clone of BB. This in turn gives us the
1719   // property that any value deffed in BB but used outside of BB is used by a
1720   // PHI in the exiting block.
1721   MachineBasicBlock *ExitingBB = CreateLCSSAExitingBlock();
1722   EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1723   // Push out the epilogs, again in reverse order.
1724   // We can't assume anything about the minumum loop trip count at this point,
1725   // so emit a fairly complex epilog.
1726 
1727   // We first peel number of stages minus one epilogue. Then we remove dead
1728   // stages and reorder instructions based on their stage. If we have 3 stages
1729   // we generate first:
1730   // E0[3, 2, 1]
1731   // E1[3', 2']
1732   // E2[3'']
1733   // And then we move instructions based on their stages to have:
1734   // E0[3]
1735   // E1[2, 3']
1736   // E2[1, 2', 3'']
1737   // The transformation is legal because we only move instructions past
1738   // instructions of a previous loop iteration.
1739   for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
1740     Epilogs.push_back(peelKernel(LPD_Back));
1741     MachineBasicBlock *B = Epilogs.back();
1742     filterInstructions(B, Schedule.getNumStages() - I);
1743     // Keep track at which iteration each phi belongs to. We need it to know
1744     // what version of the variable to use during prologue/epilogue stitching.
1745     EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1746     for (MachineInstr &Phi : B->phis())
1747       PhiNodeLoopIteration[&Phi] = Schedule.getNumStages() - I;
1748   }
1749   for (size_t I = 0; I < Epilogs.size(); I++) {
1750     LS.reset();
1751     for (size_t J = I; J < Epilogs.size(); J++) {
1752       int Iteration = J;
1753       unsigned Stage = Schedule.getNumStages() - 1 + I - J;
1754       // Move stage one block at a time so that Phi nodes are updated correctly.
1755       for (size_t K = Iteration; K > I; K--)
1756         moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
1757       LS[Stage] = 1;
1758     }
1759     LiveStages[Epilogs[I]] = LS;
1760     AvailableStages[Epilogs[I]] = AS;
1761   }
1762 
1763   // Now we've defined all the prolog and epilog blocks as a fallthrough
1764   // sequence, add the edges that will be followed if the loop trip count is
1765   // lower than the number of stages (connecting prologs directly with epilogs).
1766   auto PI = Prologs.begin();
1767   auto EI = Epilogs.begin();
1768   assert(Prologs.size() == Epilogs.size());
1769   for (; PI != Prologs.end(); ++PI, ++EI) {
1770     MachineBasicBlock *Pred = *(*EI)->pred_begin();
1771     (*PI)->addSuccessor(*EI);
1772     for (MachineInstr &MI : (*EI)->phis()) {
1773       Register Reg = MI.getOperand(1).getReg();
1774       MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
1775       if (Use && Use->getParent() == Pred) {
1776         MachineInstr *CanonicalUse = CanonicalMIs[Use];
1777         if (CanonicalUse->isPHI()) {
1778           // If the use comes from a phi we need to skip as many phi as the
1779           // distance between the epilogue and the kernel. Trace through the phi
1780           // chain to find the right value.
1781           Reg = getPhiCanonicalReg(CanonicalUse, Use);
1782         }
1783         Reg = getEquivalentRegisterIn(Reg, *PI);
1784       }
1785       MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
1786       MI.addOperand(MachineOperand::CreateMBB(*PI));
1787     }
1788   }
1789 
1790   // Create a list of all blocks in order.
1791   SmallVector<MachineBasicBlock *, 8> Blocks;
1792   llvm::copy(PeeledFront, std::back_inserter(Blocks));
1793   Blocks.push_back(BB);
1794   llvm::copy(PeeledBack, std::back_inserter(Blocks));
1795 
1796   // Iterate in reverse order over all instructions, remapping as we go.
1797   for (MachineBasicBlock *B : reverse(Blocks)) {
1798     for (auto I = B->getFirstInstrTerminator()->getReverseIterator();
1799          I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
1800       MachineInstr *MI = &*I++;
1801       rewriteUsesOf(MI);
1802     }
1803   }
1804   for (auto *MI : IllegalPhisToDelete) {
1805     if (LIS)
1806       LIS->RemoveMachineInstrFromMaps(*MI);
1807     MI->eraseFromParent();
1808   }
1809   IllegalPhisToDelete.clear();
1810 
1811   // Now all remapping has been done, we're free to optimize the generated code.
1812   for (MachineBasicBlock *B : reverse(Blocks))
1813     EliminateDeadPhis(B, MRI, LIS);
1814   EliminateDeadPhis(ExitingBB, MRI, LIS);
1815 }
1816 
1817 MachineBasicBlock *PeelingModuloScheduleExpander::CreateLCSSAExitingBlock() {
1818   MachineFunction &MF = *BB->getParent();
1819   MachineBasicBlock *Exit = *BB->succ_begin();
1820   if (Exit == BB)
1821     Exit = *std::next(BB->succ_begin());
1822 
1823   MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1824   MF.insert(std::next(BB->getIterator()), NewBB);
1825 
1826   // Clone all phis in BB into NewBB and rewrite.
1827   for (MachineInstr &MI : BB->phis()) {
1828     auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
1829     Register OldR = MI.getOperand(3).getReg();
1830     Register R = MRI.createVirtualRegister(RC);
1831     SmallVector<MachineInstr *, 4> Uses;
1832     for (MachineInstr &Use : MRI.use_instructions(OldR))
1833       if (Use.getParent() != BB)
1834         Uses.push_back(&Use);
1835     for (MachineInstr *Use : Uses)
1836       Use->substituteRegister(OldR, R, /*SubIdx=*/0,
1837                               *MRI.getTargetRegisterInfo());
1838     MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1839         .addReg(OldR)
1840         .addMBB(BB);
1841     BlockMIs[{NewBB, &MI}] = NI;
1842     CanonicalMIs[NI] = &MI;
1843   }
1844   BB->replaceSuccessor(Exit, NewBB);
1845   Exit->replacePhiUsesWith(BB, NewBB);
1846   NewBB->addSuccessor(Exit);
1847 
1848   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1849   SmallVector<MachineOperand, 4> Cond;
1850   bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
1851   (void)CanAnalyzeBr;
1852   assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
1853   TII->removeBranch(*BB);
1854   TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
1855                     Cond, DebugLoc());
1856   TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
1857   return NewBB;
1858 }
1859 
1860 Register
1861 PeelingModuloScheduleExpander::getEquivalentRegisterIn(Register Reg,
1862                                                        MachineBasicBlock *BB) {
1863   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
1864   unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg);
1865   return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
1866 }
1867 
1868 void PeelingModuloScheduleExpander::rewriteUsesOf(MachineInstr *MI) {
1869   if (MI->isPHI()) {
1870     // This is an illegal PHI. The loop-carried (desired) value is operand 3,
1871     // and it is produced by this block.
1872     Register PhiR = MI->getOperand(0).getReg();
1873     Register R = MI->getOperand(3).getReg();
1874     int RMIStage = getStage(MRI.getUniqueVRegDef(R));
1875     if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
1876       R = MI->getOperand(1).getReg();
1877     MRI.setRegClass(R, MRI.getRegClass(PhiR));
1878     MRI.replaceRegWith(PhiR, R);
1879     // Postpone deleting the Phi as it may be referenced by BlockMIs and used
1880     // later to figure out how to remap registers.
1881     MI->getOperand(0).setReg(PhiR);
1882     IllegalPhisToDelete.push_back(MI);
1883     return;
1884   }
1885 
1886   int Stage = getStage(MI);
1887   if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
1888       LiveStages[MI->getParent()].test(Stage))
1889     // Instruction is live, no rewriting to do.
1890     return;
1891 
1892   for (MachineOperand &DefMO : MI->defs()) {
1893     SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1894     for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1895       // Only PHIs can use values from this block by construction.
1896       // Match with the equivalent PHI in B.
1897       assert(UseMI.isPHI());
1898       Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1899                                              MI->getParent());
1900       Subs.emplace_back(&UseMI, Reg);
1901     }
1902     for (auto &Sub : Subs)
1903       Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1904                                     *MRI.getTargetRegisterInfo());
1905   }
1906   if (LIS)
1907     LIS->RemoveMachineInstrFromMaps(*MI);
1908   MI->eraseFromParent();
1909 }
1910 
1911 void PeelingModuloScheduleExpander::fixupBranches() {
1912   // Work outwards from the kernel.
1913   bool KernelDisposed = false;
1914   int TC = Schedule.getNumStages() - 1;
1915   for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
1916        ++PI, ++EI, --TC) {
1917     MachineBasicBlock *Prolog = *PI;
1918     MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
1919     MachineBasicBlock *Epilog = *EI;
1920     SmallVector<MachineOperand, 4> Cond;
1921     TII->removeBranch(*Prolog);
1922     Optional<bool> StaticallyGreater =
1923         LoopInfo->createTripCountGreaterCondition(TC, *Prolog, Cond);
1924     if (!StaticallyGreater.hasValue()) {
1925       LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
1926       // Dynamically branch based on Cond.
1927       TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
1928     } else if (*StaticallyGreater == false) {
1929       LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
1930       // Prolog never falls through; branch to epilog and orphan interior
1931       // blocks. Leave it to unreachable-block-elim to clean up.
1932       Prolog->removeSuccessor(Fallthrough);
1933       for (MachineInstr &P : Fallthrough->phis()) {
1934         P.RemoveOperand(2);
1935         P.RemoveOperand(1);
1936       }
1937       TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
1938       KernelDisposed = true;
1939     } else {
1940       LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
1941       // Prolog always falls through; remove incoming values in epilog.
1942       Prolog->removeSuccessor(Epilog);
1943       for (MachineInstr &P : Epilog->phis()) {
1944         P.RemoveOperand(4);
1945         P.RemoveOperand(3);
1946       }
1947     }
1948   }
1949 
1950   if (!KernelDisposed) {
1951     LoopInfo->adjustTripCount(-(Schedule.getNumStages() - 1));
1952     LoopInfo->setPreheader(Prologs.back());
1953   } else {
1954     LoopInfo->disposed();
1955   }
1956 }
1957 
1958 void PeelingModuloScheduleExpander::rewriteKernel() {
1959   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
1960   KR.rewrite();
1961 }
1962 
1963 void PeelingModuloScheduleExpander::expand() {
1964   BB = Schedule.getLoop()->getTopBlock();
1965   Preheader = Schedule.getLoop()->getLoopPreheader();
1966   LLVM_DEBUG(Schedule.dump());
1967   LoopInfo = TII->analyzeLoopForPipelining(BB);
1968   assert(LoopInfo);
1969 
1970   rewriteKernel();
1971   peelPrologAndEpilogs();
1972   fixupBranches();
1973 }
1974 
1975 void PeelingModuloScheduleExpander::validateAgainstModuloScheduleExpander() {
1976   BB = Schedule.getLoop()->getTopBlock();
1977   Preheader = Schedule.getLoop()->getLoopPreheader();
1978 
1979   // Dump the schedule before we invalidate and remap all its instructions.
1980   // Stash it in a string so we can print it if we found an error.
1981   std::string ScheduleDump;
1982   raw_string_ostream OS(ScheduleDump);
1983   Schedule.print(OS);
1984   OS.flush();
1985 
1986   // First, run the normal ModuleScheduleExpander. We don't support any
1987   // InstrChanges.
1988   assert(LIS && "Requires LiveIntervals!");
1989   ModuloScheduleExpander MSE(MF, Schedule, *LIS,
1990                              ModuloScheduleExpander::InstrChangesTy());
1991   MSE.expand();
1992   MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
1993   if (!ExpandedKernel) {
1994     // The expander optimized away the kernel. We can't do any useful checking.
1995     MSE.cleanup();
1996     return;
1997   }
1998   // Before running the KernelRewriter, re-add BB into the CFG.
1999   Preheader->addSuccessor(BB);
2000 
2001   // Now run the new expansion algorithm.
2002   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
2003   KR.rewrite();
2004   peelPrologAndEpilogs();
2005 
2006   // Collect all illegal phis that the new algorithm created. We'll give these
2007   // to KernelOperandInfo.
2008   SmallPtrSet<MachineInstr *, 4> IllegalPhis;
2009   for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
2010     if (NI->isPHI())
2011       IllegalPhis.insert(&*NI);
2012   }
2013 
2014   // Co-iterate across both kernels. We expect them to be identical apart from
2015   // phis and full COPYs (we look through both).
2016   SmallVector<std::pair<KernelOperandInfo, KernelOperandInfo>, 8> KOIs;
2017   auto OI = ExpandedKernel->begin();
2018   auto NI = BB->begin();
2019   for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
2020     while (OI->isPHI() || OI->isFullCopy())
2021       ++OI;
2022     while (NI->isPHI() || NI->isFullCopy())
2023       ++NI;
2024     assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
2025     // Analyze every operand separately.
2026     for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
2027          OOpI != OI->operands_end(); ++OOpI, ++NOpI)
2028       KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
2029                         KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
2030   }
2031 
2032   bool Failed = false;
2033   for (auto &OldAndNew : KOIs) {
2034     if (OldAndNew.first == OldAndNew.second)
2035       continue;
2036     Failed = true;
2037     errs() << "Modulo kernel validation error: [\n";
2038     errs() << " [golden] ";
2039     OldAndNew.first.print(errs());
2040     errs() << "          ";
2041     OldAndNew.second.print(errs());
2042     errs() << "]\n";
2043   }
2044 
2045   if (Failed) {
2046     errs() << "Golden reference kernel:\n";
2047     ExpandedKernel->print(errs());
2048     errs() << "New kernel:\n";
2049     BB->print(errs());
2050     errs() << ScheduleDump;
2051     report_fatal_error(
2052         "Modulo kernel validation (-pipeliner-experimental-cg) failed");
2053   }
2054 
2055   // Cleanup by removing BB from the CFG again as the original
2056   // ModuloScheduleExpander intended.
2057   Preheader->removeSuccessor(BB);
2058   MSE.cleanup();
2059 }
2060 
2061 //===----------------------------------------------------------------------===//
2062 // ModuloScheduleTestPass implementation
2063 //===----------------------------------------------------------------------===//
2064 // This pass constructs a ModuloSchedule from its module and runs
2065 // ModuloScheduleExpander.
2066 //
2067 // The module is expected to contain a single-block analyzable loop.
2068 // The total order of instructions is taken from the loop as-is.
2069 // Instructions are expected to be annotated with a PostInstrSymbol.
2070 // This PostInstrSymbol must have the following format:
2071 //  "Stage=%d Cycle=%d".
2072 //===----------------------------------------------------------------------===//
2073 
2074 namespace {
2075 class ModuloScheduleTest : public MachineFunctionPass {
2076 public:
2077   static char ID;
2078 
2079   ModuloScheduleTest() : MachineFunctionPass(ID) {
2080     initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
2081   }
2082 
2083   bool runOnMachineFunction(MachineFunction &MF) override;
2084   void runOnLoop(MachineFunction &MF, MachineLoop &L);
2085 
2086   void getAnalysisUsage(AnalysisUsage &AU) const override {
2087     AU.addRequired<MachineLoopInfo>();
2088     AU.addRequired<LiveIntervals>();
2089     MachineFunctionPass::getAnalysisUsage(AU);
2090   }
2091 };
2092 } // namespace
2093 
2094 char ModuloScheduleTest::ID = 0;
2095 
2096 INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
2097                       "Modulo Schedule test pass", false, false)
2098 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2099 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
2100 INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
2101                     "Modulo Schedule test pass", false, false)
2102 
2103 bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
2104   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
2105   for (auto *L : MLI) {
2106     if (L->getTopBlock() != L->getBottomBlock())
2107       continue;
2108     runOnLoop(MF, *L);
2109     return false;
2110   }
2111   return false;
2112 }
2113 
2114 static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
2115   std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
2116   std::pair<StringRef, StringRef> StageTokenAndValue =
2117       getToken(StageAndCycle.first, "-");
2118   std::pair<StringRef, StringRef> CycleTokenAndValue =
2119       getToken(StageAndCycle.second, "-");
2120   if (StageTokenAndValue.first != "Stage" ||
2121       CycleTokenAndValue.first != "_Cycle") {
2122     llvm_unreachable(
2123         "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
2124     return;
2125   }
2126 
2127   StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
2128   CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
2129 
2130   dbgs() << "  Stage=" << Stage << ", Cycle=" << Cycle << "\n";
2131 }
2132 
2133 void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
2134   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
2135   MachineBasicBlock *BB = L.getTopBlock();
2136   dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
2137 
2138   DenseMap<MachineInstr *, int> Cycle, Stage;
2139   std::vector<MachineInstr *> Instrs;
2140   for (MachineInstr &MI : *BB) {
2141     if (MI.isTerminator())
2142       continue;
2143     Instrs.push_back(&MI);
2144     if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
2145       dbgs() << "Parsing post-instr symbol for " << MI;
2146       parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
2147     }
2148   }
2149 
2150   ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
2151                     std::move(Stage));
2152   ModuloScheduleExpander MSE(
2153       MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
2154   MSE.expand();
2155   MSE.cleanup();
2156 }
2157 
2158 //===----------------------------------------------------------------------===//
2159 // ModuloScheduleTestAnnotater implementation
2160 //===----------------------------------------------------------------------===//
2161 
2162 void ModuloScheduleTestAnnotater::annotate() {
2163   for (MachineInstr *MI : S.getInstructions()) {
2164     SmallVector<char, 16> SV;
2165     raw_svector_ostream OS(SV);
2166     OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
2167     MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
2168     MI->setPostInstrSymbol(MF, Sym);
2169   }
2170 }
2171