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     MachineInstr *IllegalPhi =
1444         BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1445             .addReg(IllegalPhiDefault.getValue())
1446             .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
1447             .addReg(LoopReg)
1448             .addMBB(BB); // Block choice is arbitrary and has no effect.
1449     // Illegal phi should belong to the producer stage so that it can be
1450     // filtered correctly during peeling.
1451     S.setStage(IllegalPhi, LoopProducerStage);
1452     return R;
1453   }
1454 
1455   return LoopReg;
1456 }
1457 
1458 Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
1459                              const TargetRegisterClass *RC) {
1460   // If the init register is not undef, try and find an existing phi.
1461   if (InitReg.hasValue()) {
1462     auto I = Phis.find({LoopReg, InitReg.getValue()});
1463     if (I != Phis.end())
1464       return I->second;
1465   } else {
1466     for (auto &KV : Phis) {
1467       if (KV.first.first == LoopReg)
1468         return KV.second;
1469     }
1470   }
1471 
1472   // InitReg is either undef or no existing phi takes InitReg as input. Try and
1473   // find a phi that takes undef as input.
1474   auto I = UndefPhis.find(LoopReg);
1475   if (I != UndefPhis.end()) {
1476     Register R = I->second;
1477     if (!InitReg.hasValue())
1478       // Found a phi taking undef as input, and this input is undef so return
1479       // without any more changes.
1480       return R;
1481     // Found a phi taking undef as input, so rewrite it to take InitReg.
1482     MachineInstr *MI = MRI.getVRegDef(R);
1483     MI->getOperand(1).setReg(InitReg.getValue());
1484     Phis.insert({{LoopReg, InitReg.getValue()}, R});
1485     MRI.constrainRegClass(R, MRI.getRegClass(InitReg.getValue()));
1486     UndefPhis.erase(I);
1487     return R;
1488   }
1489 
1490   // Failed to find any existing phi to reuse, so create a new one.
1491   if (!RC)
1492     RC = MRI.getRegClass(LoopReg);
1493   Register R = MRI.createVirtualRegister(RC);
1494   if (InitReg.hasValue())
1495     MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
1496   BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
1497       .addReg(InitReg.hasValue() ? *InitReg : undef(RC))
1498       .addMBB(PreheaderBB)
1499       .addReg(LoopReg)
1500       .addMBB(BB);
1501   if (!InitReg.hasValue())
1502     UndefPhis[LoopReg] = R;
1503   else
1504     Phis[{LoopReg, *InitReg}] = R;
1505   return R;
1506 }
1507 
1508 Register KernelRewriter::undef(const TargetRegisterClass *RC) {
1509   Register &R = Undefs[RC];
1510   if (R == 0) {
1511     // Create an IMPLICIT_DEF that defines this register if we need it.
1512     // All uses of this should be removed by the time we have finished unrolling
1513     // prologs and epilogs.
1514     R = MRI.createVirtualRegister(RC);
1515     auto *InsertBB = &PreheaderBB->getParent()->front();
1516     BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
1517             TII->get(TargetOpcode::IMPLICIT_DEF), R);
1518   }
1519   return R;
1520 }
1521 
1522 namespace {
1523 /// Describes an operand in the kernel of a pipelined loop. Characteristics of
1524 /// the operand are discovered, such as how many in-loop PHIs it has to jump
1525 /// through and defaults for these phis.
1526 class KernelOperandInfo {
1527   MachineBasicBlock *BB;
1528   MachineRegisterInfo &MRI;
1529   SmallVector<Register, 4> PhiDefaults;
1530   MachineOperand *Source;
1531   MachineOperand *Target;
1532 
1533 public:
1534   KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
1535                     const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
1536       : MRI(MRI) {
1537     Source = MO;
1538     BB = MO->getParent()->getParent();
1539     while (isRegInLoop(MO)) {
1540       MachineInstr *MI = MRI.getVRegDef(MO->getReg());
1541       if (MI->isFullCopy()) {
1542         MO = &MI->getOperand(1);
1543         continue;
1544       }
1545       if (!MI->isPHI())
1546         break;
1547       // If this is an illegal phi, don't count it in distance.
1548       if (IllegalPhis.count(MI)) {
1549         MO = &MI->getOperand(3);
1550         continue;
1551       }
1552 
1553       Register Default = getInitPhiReg(*MI, BB);
1554       MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
1555                                             : &MI->getOperand(3);
1556       PhiDefaults.push_back(Default);
1557     }
1558     Target = MO;
1559   }
1560 
1561   bool operator==(const KernelOperandInfo &Other) const {
1562     return PhiDefaults.size() == Other.PhiDefaults.size();
1563   }
1564 
1565   void print(raw_ostream &OS) const {
1566     OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
1567        << *Source->getParent();
1568   }
1569 
1570 private:
1571   bool isRegInLoop(MachineOperand *MO) {
1572     return MO->isReg() && MO->getReg().isVirtual() &&
1573            MRI.getVRegDef(MO->getReg())->getParent() == BB;
1574   }
1575 };
1576 } // namespace
1577 
1578 MachineBasicBlock *
1579 PeelingModuloScheduleExpander::peelKernel(LoopPeelDirection LPD) {
1580   MachineBasicBlock *NewBB = PeelSingleBlockLoop(LPD, BB, MRI, TII);
1581   if (LPD == LPD_Front)
1582     PeeledFront.push_back(NewBB);
1583   else
1584     PeeledBack.push_front(NewBB);
1585   for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
1586        ++I, ++NI) {
1587     CanonicalMIs[&*I] = &*I;
1588     CanonicalMIs[&*NI] = &*I;
1589     BlockMIs[{NewBB, &*I}] = &*NI;
1590     BlockMIs[{BB, &*I}] = &*I;
1591   }
1592   return NewBB;
1593 }
1594 
1595 void PeelingModuloScheduleExpander::filterInstructions(MachineBasicBlock *MB,
1596                                                        int MinStage) {
1597   for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
1598        I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
1599     MachineInstr *MI = &*I++;
1600     int Stage = getStage(MI);
1601     if (Stage == -1 || Stage >= MinStage)
1602       continue;
1603 
1604     for (MachineOperand &DefMO : MI->defs()) {
1605       SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1606       for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1607         // Only PHIs can use values from this block by construction.
1608         // Match with the equivalent PHI in B.
1609         assert(UseMI.isPHI());
1610         Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1611                                                MI->getParent());
1612         Subs.emplace_back(&UseMI, Reg);
1613       }
1614       for (auto &Sub : Subs)
1615         Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1616                                       *MRI.getTargetRegisterInfo());
1617     }
1618     if (LIS)
1619       LIS->RemoveMachineInstrFromMaps(*MI);
1620     MI->eraseFromParent();
1621   }
1622 }
1623 
1624 void PeelingModuloScheduleExpander::moveStageBetweenBlocks(
1625     MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
1626   auto InsertPt = DestBB->getFirstNonPHI();
1627   DenseMap<Register, Register> Remaps;
1628   for (auto I = SourceBB->getFirstNonPHI(); I != SourceBB->end();) {
1629     MachineInstr *MI = &*I++;
1630     if (MI->isPHI()) {
1631       // This is an illegal PHI. If we move any instructions using an illegal
1632       // PHI, we need to create a legal Phi
1633       Register PhiR = MI->getOperand(0).getReg();
1634       auto RC = MRI.getRegClass(PhiR);
1635       Register NR = MRI.createVirtualRegister(RC);
1636       MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(), DebugLoc(),
1637                                  TII->get(TargetOpcode::PHI), NR)
1638                              .addReg(PhiR)
1639                              .addMBB(SourceBB);
1640       BlockMIs[{DestBB, CanonicalMIs[MI]}] = NI;
1641       CanonicalMIs[NI] = CanonicalMIs[MI];
1642       Remaps[PhiR] = NR;
1643       continue;
1644     }
1645     if (getStage(MI) != Stage)
1646       continue;
1647     MI->removeFromParent();
1648     DestBB->insert(InsertPt, MI);
1649     auto *KernelMI = CanonicalMIs[MI];
1650     BlockMIs[{DestBB, KernelMI}] = MI;
1651     BlockMIs.erase({SourceBB, KernelMI});
1652   }
1653   SmallVector<MachineInstr *, 4> PhiToDelete;
1654   for (MachineInstr &MI : DestBB->phis()) {
1655     assert(MI.getNumOperands() == 3);
1656     MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
1657     // If the instruction referenced by the phi is moved inside the block
1658     // we don't need the phi anymore.
1659     if (getStage(Def) == Stage) {
1660       Register PhiReg = MI.getOperand(0).getReg();
1661       assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg()) != -1);
1662       MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
1663       MI.getOperand(0).setReg(PhiReg);
1664       PhiToDelete.push_back(&MI);
1665     }
1666   }
1667   for (auto *P : PhiToDelete)
1668     P->eraseFromParent();
1669   InsertPt = DestBB->getFirstNonPHI();
1670   // Helper to clone Phi instructions into the destination block. We clone Phi
1671   // greedily to avoid combinatorial explosion of Phi instructions.
1672   auto clonePhi = [&](MachineInstr *Phi) {
1673     MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
1674     DestBB->insert(InsertPt, NewMI);
1675     Register OrigR = Phi->getOperand(0).getReg();
1676     Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
1677     NewMI->getOperand(0).setReg(R);
1678     NewMI->getOperand(1).setReg(OrigR);
1679     NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
1680     Remaps[OrigR] = R;
1681     CanonicalMIs[NewMI] = CanonicalMIs[Phi];
1682     BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
1683     PhiNodeLoopIteration[NewMI] = PhiNodeLoopIteration[Phi];
1684     return R;
1685   };
1686   for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
1687     for (MachineOperand &MO : I->uses()) {
1688       if (!MO.isReg())
1689         continue;
1690       if (Remaps.count(MO.getReg()))
1691         MO.setReg(Remaps[MO.getReg()]);
1692       else {
1693         // If we are using a phi from the source block we need to add a new phi
1694         // pointing to the old one.
1695         MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
1696         if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
1697           Register R = clonePhi(Use);
1698           MO.setReg(R);
1699         }
1700       }
1701     }
1702   }
1703 }
1704 
1705 Register
1706 PeelingModuloScheduleExpander::getPhiCanonicalReg(MachineInstr *CanonicalPhi,
1707                                                   MachineInstr *Phi) {
1708   unsigned distance = PhiNodeLoopIteration[Phi];
1709   MachineInstr *CanonicalUse = CanonicalPhi;
1710   for (unsigned I = 0; I < distance; ++I) {
1711     assert(CanonicalUse->isPHI());
1712     assert(CanonicalUse->getNumOperands() == 5);
1713     unsigned LoopRegIdx = 3, InitRegIdx = 1;
1714     if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
1715       std::swap(LoopRegIdx, InitRegIdx);
1716     CanonicalUse =
1717         MRI.getVRegDef(CanonicalUse->getOperand(LoopRegIdx).getReg());
1718   }
1719   return CanonicalUse->getOperand(0).getReg();
1720 }
1721 
1722 void PeelingModuloScheduleExpander::peelPrologAndEpilogs() {
1723   BitVector LS(Schedule.getNumStages(), true);
1724   BitVector AS(Schedule.getNumStages(), true);
1725   LiveStages[BB] = LS;
1726   AvailableStages[BB] = AS;
1727 
1728   // Peel out the prologs.
1729   LS.reset();
1730   for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
1731     LS[I] = 1;
1732     Prologs.push_back(peelKernel(LPD_Front));
1733     LiveStages[Prologs.back()] = LS;
1734     AvailableStages[Prologs.back()] = LS;
1735   }
1736 
1737   // Create a block that will end up as the new loop exiting block (dominated by
1738   // all prologs and epilogs). It will only contain PHIs, in the same order as
1739   // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
1740   // that the exiting block is a (sub) clone of BB. This in turn gives us the
1741   // property that any value deffed in BB but used outside of BB is used by a
1742   // PHI in the exiting block.
1743   MachineBasicBlock *ExitingBB = CreateLCSSAExitingBlock();
1744   EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1745   // Push out the epilogs, again in reverse order.
1746   // We can't assume anything about the minumum loop trip count at this point,
1747   // so emit a fairly complex epilog.
1748 
1749   // We first peel number of stages minus one epilogue. Then we remove dead
1750   // stages and reorder instructions based on their stage. If we have 3 stages
1751   // we generate first:
1752   // E0[3, 2, 1]
1753   // E1[3', 2']
1754   // E2[3'']
1755   // And then we move instructions based on their stages to have:
1756   // E0[3]
1757   // E1[2, 3']
1758   // E2[1, 2', 3'']
1759   // The transformation is legal because we only move instructions past
1760   // instructions of a previous loop iteration.
1761   for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
1762     Epilogs.push_back(peelKernel(LPD_Back));
1763     MachineBasicBlock *B = Epilogs.back();
1764     filterInstructions(B, Schedule.getNumStages() - I);
1765     // Keep track at which iteration each phi belongs to. We need it to know
1766     // what version of the variable to use during prologue/epilogue stitching.
1767     EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1768     for (auto Phi = B->begin(), IE = B->getFirstNonPHI(); Phi != IE; ++Phi)
1769       PhiNodeLoopIteration[&*Phi] = Schedule.getNumStages() - I;
1770   }
1771   for (size_t I = 0; I < Epilogs.size(); I++) {
1772     LS.reset();
1773     for (size_t J = I; J < Epilogs.size(); J++) {
1774       int Iteration = J;
1775       unsigned Stage = Schedule.getNumStages() - 1 + I - J;
1776       // Move stage one block at a time so that Phi nodes are updated correctly.
1777       for (size_t K = Iteration; K > I; K--)
1778         moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
1779       LS[Stage] = 1;
1780     }
1781     LiveStages[Epilogs[I]] = LS;
1782     AvailableStages[Epilogs[I]] = AS;
1783   }
1784 
1785   // Now we've defined all the prolog and epilog blocks as a fallthrough
1786   // sequence, add the edges that will be followed if the loop trip count is
1787   // lower than the number of stages (connecting prologs directly with epilogs).
1788   auto PI = Prologs.begin();
1789   auto EI = Epilogs.begin();
1790   assert(Prologs.size() == Epilogs.size());
1791   for (; PI != Prologs.end(); ++PI, ++EI) {
1792     MachineBasicBlock *Pred = *(*EI)->pred_begin();
1793     (*PI)->addSuccessor(*EI);
1794     for (MachineInstr &MI : (*EI)->phis()) {
1795       Register Reg = MI.getOperand(1).getReg();
1796       MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
1797       if (Use && Use->getParent() == Pred) {
1798         MachineInstr *CanonicalUse = CanonicalMIs[Use];
1799         if (CanonicalUse->isPHI()) {
1800           // If the use comes from a phi we need to skip as many phi as the
1801           // distance between the epilogue and the kernel. Trace through the phi
1802           // chain to find the right value.
1803           Reg = getPhiCanonicalReg(CanonicalUse, Use);
1804         }
1805         Reg = getEquivalentRegisterIn(Reg, *PI);
1806       }
1807       MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
1808       MI.addOperand(MachineOperand::CreateMBB(*PI));
1809     }
1810   }
1811 
1812   // Create a list of all blocks in order.
1813   SmallVector<MachineBasicBlock *, 8> Blocks;
1814   llvm::copy(PeeledFront, std::back_inserter(Blocks));
1815   Blocks.push_back(BB);
1816   llvm::copy(PeeledBack, std::back_inserter(Blocks));
1817 
1818   // Iterate in reverse order over all instructions, remapping as we go.
1819   for (MachineBasicBlock *B : reverse(Blocks)) {
1820     for (auto I = B->getFirstInstrTerminator()->getReverseIterator();
1821          I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
1822       MachineInstr *MI = &*I++;
1823       rewriteUsesOf(MI);
1824     }
1825   }
1826   for (auto *MI : IllegalPhisToDelete) {
1827     if (LIS)
1828       LIS->RemoveMachineInstrFromMaps(*MI);
1829     MI->eraseFromParent();
1830   }
1831   IllegalPhisToDelete.clear();
1832 
1833   // Now all remapping has been done, we're free to optimize the generated code.
1834   for (MachineBasicBlock *B : reverse(Blocks))
1835     EliminateDeadPhis(B, MRI, LIS);
1836   EliminateDeadPhis(ExitingBB, MRI, LIS);
1837 }
1838 
1839 MachineBasicBlock *PeelingModuloScheduleExpander::CreateLCSSAExitingBlock() {
1840   MachineFunction &MF = *BB->getParent();
1841   MachineBasicBlock *Exit = *BB->succ_begin();
1842   if (Exit == BB)
1843     Exit = *std::next(BB->succ_begin());
1844 
1845   MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1846   MF.insert(std::next(BB->getIterator()), NewBB);
1847 
1848   // Clone all phis in BB into NewBB and rewrite.
1849   for (MachineInstr &MI : BB->phis()) {
1850     auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
1851     Register OldR = MI.getOperand(3).getReg();
1852     Register R = MRI.createVirtualRegister(RC);
1853     SmallVector<MachineInstr *, 4> Uses;
1854     for (MachineInstr &Use : MRI.use_instructions(OldR))
1855       if (Use.getParent() != BB)
1856         Uses.push_back(&Use);
1857     for (MachineInstr *Use : Uses)
1858       Use->substituteRegister(OldR, R, /*SubIdx=*/0,
1859                               *MRI.getTargetRegisterInfo());
1860     MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1861         .addReg(OldR)
1862         .addMBB(BB);
1863     BlockMIs[{NewBB, &MI}] = NI;
1864     CanonicalMIs[NI] = &MI;
1865   }
1866   BB->replaceSuccessor(Exit, NewBB);
1867   Exit->replacePhiUsesWith(BB, NewBB);
1868   NewBB->addSuccessor(Exit);
1869 
1870   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1871   SmallVector<MachineOperand, 4> Cond;
1872   bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
1873   (void)CanAnalyzeBr;
1874   assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
1875   TII->removeBranch(*BB);
1876   TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
1877                     Cond, DebugLoc());
1878   TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
1879   return NewBB;
1880 }
1881 
1882 Register
1883 PeelingModuloScheduleExpander::getEquivalentRegisterIn(Register Reg,
1884                                                        MachineBasicBlock *BB) {
1885   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
1886   unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg);
1887   return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
1888 }
1889 
1890 void PeelingModuloScheduleExpander::rewriteUsesOf(MachineInstr *MI) {
1891   if (MI->isPHI()) {
1892     // This is an illegal PHI. The loop-carried (desired) value is operand 3,
1893     // and it is produced by this block.
1894     Register PhiR = MI->getOperand(0).getReg();
1895     Register R = MI->getOperand(3).getReg();
1896     int RMIStage = getStage(MRI.getUniqueVRegDef(R));
1897     if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
1898       R = MI->getOperand(1).getReg();
1899     MRI.setRegClass(R, MRI.getRegClass(PhiR));
1900     MRI.replaceRegWith(PhiR, R);
1901     // Postpone deleting the Phi as it may be referenced by BlockMIs and used
1902     // later to figure out how to remap registers.
1903     MI->getOperand(0).setReg(PhiR);
1904     IllegalPhisToDelete.push_back(MI);
1905     return;
1906   }
1907 
1908   int Stage = getStage(MI);
1909   if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
1910       LiveStages[MI->getParent()].test(Stage))
1911     // Instruction is live, no rewriting to do.
1912     return;
1913 
1914   for (MachineOperand &DefMO : MI->defs()) {
1915     SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1916     for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1917       // Only PHIs can use values from this block by construction.
1918       // Match with the equivalent PHI in B.
1919       assert(UseMI.isPHI());
1920       Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1921                                              MI->getParent());
1922       Subs.emplace_back(&UseMI, Reg);
1923     }
1924     for (auto &Sub : Subs)
1925       Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1926                                     *MRI.getTargetRegisterInfo());
1927   }
1928   if (LIS)
1929     LIS->RemoveMachineInstrFromMaps(*MI);
1930   MI->eraseFromParent();
1931 }
1932 
1933 void PeelingModuloScheduleExpander::fixupBranches() {
1934   // Work outwards from the kernel.
1935   bool KernelDisposed = false;
1936   int TC = Schedule.getNumStages() - 1;
1937   for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
1938        ++PI, ++EI, --TC) {
1939     MachineBasicBlock *Prolog = *PI;
1940     MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
1941     MachineBasicBlock *Epilog = *EI;
1942     SmallVector<MachineOperand, 4> Cond;
1943     TII->removeBranch(*Prolog);
1944     Optional<bool> StaticallyGreater =
1945         Info->createTripCountGreaterCondition(TC, *Prolog, Cond);
1946     if (!StaticallyGreater.hasValue()) {
1947       LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
1948       // Dynamically branch based on Cond.
1949       TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
1950     } else if (*StaticallyGreater == false) {
1951       LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
1952       // Prolog never falls through; branch to epilog and orphan interior
1953       // blocks. Leave it to unreachable-block-elim to clean up.
1954       Prolog->removeSuccessor(Fallthrough);
1955       for (MachineInstr &P : Fallthrough->phis()) {
1956         P.RemoveOperand(2);
1957         P.RemoveOperand(1);
1958       }
1959       TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
1960       KernelDisposed = true;
1961     } else {
1962       LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
1963       // Prolog always falls through; remove incoming values in epilog.
1964       Prolog->removeSuccessor(Epilog);
1965       for (MachineInstr &P : Epilog->phis()) {
1966         P.RemoveOperand(4);
1967         P.RemoveOperand(3);
1968       }
1969     }
1970   }
1971 
1972   if (!KernelDisposed) {
1973     Info->adjustTripCount(-(Schedule.getNumStages() - 1));
1974     Info->setPreheader(Prologs.back());
1975   } else {
1976     Info->disposed();
1977   }
1978 }
1979 
1980 void PeelingModuloScheduleExpander::rewriteKernel() {
1981   KernelRewriter KR(*Schedule.getLoop(), Schedule);
1982   KR.rewrite();
1983 }
1984 
1985 void PeelingModuloScheduleExpander::expand() {
1986   BB = Schedule.getLoop()->getTopBlock();
1987   Preheader = Schedule.getLoop()->getLoopPreheader();
1988   LLVM_DEBUG(Schedule.dump());
1989   Info = TII->analyzeLoopForPipelining(BB);
1990   assert(Info);
1991 
1992   rewriteKernel();
1993   peelPrologAndEpilogs();
1994   fixupBranches();
1995 }
1996 
1997 void PeelingModuloScheduleExpander::validateAgainstModuloScheduleExpander() {
1998   BB = Schedule.getLoop()->getTopBlock();
1999   Preheader = Schedule.getLoop()->getLoopPreheader();
2000 
2001   // Dump the schedule before we invalidate and remap all its instructions.
2002   // Stash it in a string so we can print it if we found an error.
2003   std::string ScheduleDump;
2004   raw_string_ostream OS(ScheduleDump);
2005   Schedule.print(OS);
2006   OS.flush();
2007 
2008   // First, run the normal ModuleScheduleExpander. We don't support any
2009   // InstrChanges.
2010   assert(LIS && "Requires LiveIntervals!");
2011   ModuloScheduleExpander MSE(MF, Schedule, *LIS,
2012                              ModuloScheduleExpander::InstrChangesTy());
2013   MSE.expand();
2014   MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
2015   if (!ExpandedKernel) {
2016     // The expander optimized away the kernel. We can't do any useful checking.
2017     MSE.cleanup();
2018     return;
2019   }
2020   // Before running the KernelRewriter, re-add BB into the CFG.
2021   Preheader->addSuccessor(BB);
2022 
2023   // Now run the new expansion algorithm.
2024   KernelRewriter KR(*Schedule.getLoop(), Schedule);
2025   KR.rewrite();
2026   peelPrologAndEpilogs();
2027 
2028   // Collect all illegal phis that the new algorithm created. We'll give these
2029   // to KernelOperandInfo.
2030   SmallPtrSet<MachineInstr *, 4> IllegalPhis;
2031   for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
2032     if (NI->isPHI())
2033       IllegalPhis.insert(&*NI);
2034   }
2035 
2036   // Co-iterate across both kernels. We expect them to be identical apart from
2037   // phis and full COPYs (we look through both).
2038   SmallVector<std::pair<KernelOperandInfo, KernelOperandInfo>, 8> KOIs;
2039   auto OI = ExpandedKernel->begin();
2040   auto NI = BB->begin();
2041   for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
2042     while (OI->isPHI() || OI->isFullCopy())
2043       ++OI;
2044     while (NI->isPHI() || NI->isFullCopy())
2045       ++NI;
2046     assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
2047     // Analyze every operand separately.
2048     for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
2049          OOpI != OI->operands_end(); ++OOpI, ++NOpI)
2050       KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
2051                         KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
2052   }
2053 
2054   bool Failed = false;
2055   for (auto &OldAndNew : KOIs) {
2056     if (OldAndNew.first == OldAndNew.second)
2057       continue;
2058     Failed = true;
2059     errs() << "Modulo kernel validation error: [\n";
2060     errs() << " [golden] ";
2061     OldAndNew.first.print(errs());
2062     errs() << "          ";
2063     OldAndNew.second.print(errs());
2064     errs() << "]\n";
2065   }
2066 
2067   if (Failed) {
2068     errs() << "Golden reference kernel:\n";
2069     ExpandedKernel->print(errs());
2070     errs() << "New kernel:\n";
2071     BB->print(errs());
2072     errs() << ScheduleDump;
2073     report_fatal_error(
2074         "Modulo kernel validation (-pipeliner-experimental-cg) failed");
2075   }
2076 
2077   // Cleanup by removing BB from the CFG again as the original
2078   // ModuloScheduleExpander intended.
2079   Preheader->removeSuccessor(BB);
2080   MSE.cleanup();
2081 }
2082 
2083 //===----------------------------------------------------------------------===//
2084 // ModuloScheduleTestPass implementation
2085 //===----------------------------------------------------------------------===//
2086 // This pass constructs a ModuloSchedule from its module and runs
2087 // ModuloScheduleExpander.
2088 //
2089 // The module is expected to contain a single-block analyzable loop.
2090 // The total order of instructions is taken from the loop as-is.
2091 // Instructions are expected to be annotated with a PostInstrSymbol.
2092 // This PostInstrSymbol must have the following format:
2093 //  "Stage=%d Cycle=%d".
2094 //===----------------------------------------------------------------------===//
2095 
2096 namespace {
2097 class ModuloScheduleTest : public MachineFunctionPass {
2098 public:
2099   static char ID;
2100 
2101   ModuloScheduleTest() : MachineFunctionPass(ID) {
2102     initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
2103   }
2104 
2105   bool runOnMachineFunction(MachineFunction &MF) override;
2106   void runOnLoop(MachineFunction &MF, MachineLoop &L);
2107 
2108   void getAnalysisUsage(AnalysisUsage &AU) const override {
2109     AU.addRequired<MachineLoopInfo>();
2110     AU.addRequired<LiveIntervals>();
2111     MachineFunctionPass::getAnalysisUsage(AU);
2112   }
2113 };
2114 } // namespace
2115 
2116 char ModuloScheduleTest::ID = 0;
2117 
2118 INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
2119                       "Modulo Schedule test pass", false, false)
2120 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2121 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
2122 INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
2123                     "Modulo Schedule test pass", false, false)
2124 
2125 bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
2126   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
2127   for (auto *L : MLI) {
2128     if (L->getTopBlock() != L->getBottomBlock())
2129       continue;
2130     runOnLoop(MF, *L);
2131     return false;
2132   }
2133   return false;
2134 }
2135 
2136 static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
2137   std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
2138   std::pair<StringRef, StringRef> StageTokenAndValue =
2139       getToken(StageAndCycle.first, "-");
2140   std::pair<StringRef, StringRef> CycleTokenAndValue =
2141       getToken(StageAndCycle.second, "-");
2142   if (StageTokenAndValue.first != "Stage" ||
2143       CycleTokenAndValue.first != "_Cycle") {
2144     llvm_unreachable(
2145         "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
2146     return;
2147   }
2148 
2149   StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
2150   CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
2151 
2152   dbgs() << "  Stage=" << Stage << ", Cycle=" << Cycle << "\n";
2153 }
2154 
2155 void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
2156   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
2157   MachineBasicBlock *BB = L.getTopBlock();
2158   dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
2159 
2160   DenseMap<MachineInstr *, int> Cycle, Stage;
2161   std::vector<MachineInstr *> Instrs;
2162   for (MachineInstr &MI : *BB) {
2163     if (MI.isTerminator())
2164       continue;
2165     Instrs.push_back(&MI);
2166     if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
2167       dbgs() << "Parsing post-instr symbol for " << MI;
2168       parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
2169     }
2170   }
2171 
2172   ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
2173                     std::move(Stage));
2174   ModuloScheduleExpander MSE(
2175       MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
2176   MSE.expand();
2177   MSE.cleanup();
2178 }
2179 
2180 //===----------------------------------------------------------------------===//
2181 // ModuloScheduleTestAnnotater implementation
2182 //===----------------------------------------------------------------------===//
2183 
2184 void ModuloScheduleTestAnnotater::annotate() {
2185   for (MachineInstr *MI : S.getInstructions()) {
2186     SmallVector<char, 16> SV;
2187     raw_svector_ostream OS(SV);
2188     OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
2189     MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
2190     MI->setPostInstrSymbol(MF, Sym);
2191   }
2192 }
2193