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