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