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