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