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