xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/ModuloSchedule.cpp (revision c80e69b00d976a5a3b3e84527f270fa7e72a8205)
18bcb0991SDimitry Andric //===- ModuloSchedule.cpp - Software pipeline schedule expansion ----------===//
28bcb0991SDimitry Andric //
38bcb0991SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48bcb0991SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
58bcb0991SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68bcb0991SDimitry Andric //
78bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
88bcb0991SDimitry Andric 
98bcb0991SDimitry Andric #include "llvm/CodeGen/ModuloSchedule.h"
108bcb0991SDimitry Andric #include "llvm/ADT/StringExtras.h"
115ffd83dbSDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
128bcb0991SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
138bcb0991SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
1481ad6265SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
158bcb0991SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
16480093f4SDimitry Andric #include "llvm/InitializePasses.h"
178bcb0991SDimitry Andric #include "llvm/MC/MCContext.h"
188bcb0991SDimitry Andric #include "llvm/Support/Debug.h"
198bcb0991SDimitry Andric #include "llvm/Support/ErrorHandling.h"
208bcb0991SDimitry Andric #include "llvm/Support/raw_ostream.h"
218bcb0991SDimitry Andric 
228bcb0991SDimitry Andric #define DEBUG_TYPE "pipeliner"
238bcb0991SDimitry Andric using namespace llvm;
248bcb0991SDimitry Andric 
250fca6ea1SDimitry Andric static cl::opt<bool> SwapBranchTargetsMVE(
260fca6ea1SDimitry Andric     "pipeliner-swap-branch-targets-mve", cl::Hidden, cl::init(false),
270fca6ea1SDimitry Andric     cl::desc("Swap target blocks of a conditional branch for MVE expander"));
280fca6ea1SDimitry Andric 
298bcb0991SDimitry Andric void ModuloSchedule::print(raw_ostream &OS) {
308bcb0991SDimitry Andric   for (MachineInstr *MI : ScheduledInstrs)
318bcb0991SDimitry Andric     OS << "[stage " << getStage(MI) << " @" << getCycle(MI) << "c] " << *MI;
328bcb0991SDimitry Andric }
338bcb0991SDimitry Andric 
348bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
358bcb0991SDimitry Andric // ModuloScheduleExpander implementation
368bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
378bcb0991SDimitry Andric 
388bcb0991SDimitry Andric /// Return the register values for  the operands of a Phi instruction.
398bcb0991SDimitry Andric /// This function assume the instruction is a Phi.
408bcb0991SDimitry Andric static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
418bcb0991SDimitry Andric                        unsigned &InitVal, unsigned &LoopVal) {
428bcb0991SDimitry Andric   assert(Phi.isPHI() && "Expecting a Phi.");
438bcb0991SDimitry Andric 
448bcb0991SDimitry Andric   InitVal = 0;
458bcb0991SDimitry Andric   LoopVal = 0;
468bcb0991SDimitry Andric   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
478bcb0991SDimitry Andric     if (Phi.getOperand(i + 1).getMBB() != Loop)
488bcb0991SDimitry Andric       InitVal = Phi.getOperand(i).getReg();
498bcb0991SDimitry Andric     else
508bcb0991SDimitry Andric       LoopVal = Phi.getOperand(i).getReg();
518bcb0991SDimitry Andric 
528bcb0991SDimitry Andric   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
538bcb0991SDimitry Andric }
548bcb0991SDimitry Andric 
558bcb0991SDimitry Andric /// Return the Phi register value that comes from the incoming block.
568bcb0991SDimitry Andric static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
578bcb0991SDimitry Andric   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
588bcb0991SDimitry Andric     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
598bcb0991SDimitry Andric       return Phi.getOperand(i).getReg();
608bcb0991SDimitry Andric   return 0;
618bcb0991SDimitry Andric }
628bcb0991SDimitry Andric 
638bcb0991SDimitry Andric /// Return the Phi register value that comes the loop block.
648bcb0991SDimitry Andric static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
658bcb0991SDimitry Andric   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
668bcb0991SDimitry Andric     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
678bcb0991SDimitry Andric       return Phi.getOperand(i).getReg();
688bcb0991SDimitry Andric   return 0;
698bcb0991SDimitry Andric }
708bcb0991SDimitry Andric 
718bcb0991SDimitry Andric void ModuloScheduleExpander::expand() {
728bcb0991SDimitry Andric   BB = Schedule.getLoop()->getTopBlock();
738bcb0991SDimitry Andric   Preheader = *BB->pred_begin();
748bcb0991SDimitry Andric   if (Preheader == BB)
758bcb0991SDimitry Andric     Preheader = *std::next(BB->pred_begin());
768bcb0991SDimitry Andric 
778bcb0991SDimitry Andric   // Iterate over the definitions in each instruction, and compute the
788bcb0991SDimitry Andric   // stage difference for each use.  Keep the maximum value.
798bcb0991SDimitry Andric   for (MachineInstr *MI : Schedule.getInstructions()) {
808bcb0991SDimitry Andric     int DefStage = Schedule.getStage(MI);
8106c3fb27SDimitry Andric     for (const MachineOperand &Op : MI->all_defs()) {
828bcb0991SDimitry Andric       Register Reg = Op.getReg();
838bcb0991SDimitry Andric       unsigned MaxDiff = 0;
848bcb0991SDimitry Andric       bool PhiIsSwapped = false;
85349cc55cSDimitry Andric       for (MachineOperand &UseOp : MRI.use_operands(Reg)) {
868bcb0991SDimitry Andric         MachineInstr *UseMI = UseOp.getParent();
878bcb0991SDimitry Andric         int UseStage = Schedule.getStage(UseMI);
888bcb0991SDimitry Andric         unsigned Diff = 0;
898bcb0991SDimitry Andric         if (UseStage != -1 && UseStage >= DefStage)
908bcb0991SDimitry Andric           Diff = UseStage - DefStage;
918bcb0991SDimitry Andric         if (MI->isPHI()) {
928bcb0991SDimitry Andric           if (isLoopCarried(*MI))
938bcb0991SDimitry Andric             ++Diff;
948bcb0991SDimitry Andric           else
958bcb0991SDimitry Andric             PhiIsSwapped = true;
968bcb0991SDimitry Andric         }
978bcb0991SDimitry Andric         MaxDiff = std::max(Diff, MaxDiff);
988bcb0991SDimitry Andric       }
998bcb0991SDimitry Andric       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
1008bcb0991SDimitry Andric     }
1018bcb0991SDimitry Andric   }
1028bcb0991SDimitry Andric 
1038bcb0991SDimitry Andric   generatePipelinedLoop();
1048bcb0991SDimitry Andric }
1058bcb0991SDimitry Andric 
1068bcb0991SDimitry Andric void ModuloScheduleExpander::generatePipelinedLoop() {
1078bcb0991SDimitry Andric   LoopInfo = TII->analyzeLoopForPipelining(BB);
1088bcb0991SDimitry Andric   assert(LoopInfo && "Must be able to analyze loop!");
1098bcb0991SDimitry Andric 
1108bcb0991SDimitry Andric   // Create a new basic block for the kernel and add it to the CFG.
1118bcb0991SDimitry Andric   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1128bcb0991SDimitry Andric 
1138bcb0991SDimitry Andric   unsigned MaxStageCount = Schedule.getNumStages() - 1;
1148bcb0991SDimitry Andric 
1158bcb0991SDimitry Andric   // Remember the registers that are used in different stages. The index is
1168bcb0991SDimitry Andric   // the iteration, or stage, that the instruction is scheduled in.  This is
1178bcb0991SDimitry Andric   // a map between register names in the original block and the names created
1188bcb0991SDimitry Andric   // in each stage of the pipelined loop.
1198bcb0991SDimitry Andric   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
120bdd1243dSDimitry Andric 
121bdd1243dSDimitry Andric   // The renaming destination by Phis for the registers across stages.
122bdd1243dSDimitry Andric   // This map is updated during Phis generation to point to the most recent
123bdd1243dSDimitry Andric   // renaming destination.
124bdd1243dSDimitry Andric   ValueMapTy *VRMapPhi = new ValueMapTy[(MaxStageCount + 1) * 2];
125bdd1243dSDimitry Andric 
1268bcb0991SDimitry Andric   InstrMapTy InstrMap;
1278bcb0991SDimitry Andric 
1288bcb0991SDimitry Andric   SmallVector<MachineBasicBlock *, 4> PrologBBs;
1298bcb0991SDimitry Andric 
1308bcb0991SDimitry Andric   // Generate the prolog instructions that set up the pipeline.
1318bcb0991SDimitry Andric   generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
1328bcb0991SDimitry Andric   MF.insert(BB->getIterator(), KernelBB);
133*c80e69b0SDimitry Andric   LIS.insertMBBInMaps(KernelBB);
1348bcb0991SDimitry Andric 
1358bcb0991SDimitry Andric   // Rearrange the instructions to generate the new, pipelined loop,
1368bcb0991SDimitry Andric   // and update register names as needed.
1378bcb0991SDimitry Andric   for (MachineInstr *CI : Schedule.getInstructions()) {
1388bcb0991SDimitry Andric     if (CI->isPHI())
1398bcb0991SDimitry Andric       continue;
1408bcb0991SDimitry Andric     unsigned StageNum = Schedule.getStage(CI);
1418bcb0991SDimitry Andric     MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
1428bcb0991SDimitry Andric     updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
1438bcb0991SDimitry Andric     KernelBB->push_back(NewMI);
1448bcb0991SDimitry Andric     InstrMap[NewMI] = CI;
1458bcb0991SDimitry Andric   }
1468bcb0991SDimitry Andric 
1478bcb0991SDimitry Andric   // Copy any terminator instructions to the new kernel, and update
1488bcb0991SDimitry Andric   // names as needed.
149349cc55cSDimitry Andric   for (MachineInstr &MI : BB->terminators()) {
150349cc55cSDimitry Andric     MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
1518bcb0991SDimitry Andric     updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
1528bcb0991SDimitry Andric     KernelBB->push_back(NewMI);
153349cc55cSDimitry Andric     InstrMap[NewMI] = &MI;
1548bcb0991SDimitry Andric   }
1558bcb0991SDimitry Andric 
1568bcb0991SDimitry Andric   NewKernel = KernelBB;
1578bcb0991SDimitry Andric   KernelBB->transferSuccessors(BB);
1588bcb0991SDimitry Andric   KernelBB->replaceSuccessor(BB, KernelBB);
1598bcb0991SDimitry Andric 
1608bcb0991SDimitry Andric   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
1618bcb0991SDimitry Andric                        InstrMap, MaxStageCount, MaxStageCount, false);
162bdd1243dSDimitry Andric   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, VRMapPhi,
163bdd1243dSDimitry Andric                InstrMap, MaxStageCount, MaxStageCount, false);
1648bcb0991SDimitry Andric 
1658bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
1668bcb0991SDimitry Andric 
1678bcb0991SDimitry Andric   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
1688bcb0991SDimitry Andric   // Generate the epilog instructions to complete the pipeline.
169bdd1243dSDimitry Andric   generateEpilog(MaxStageCount, KernelBB, BB, VRMap, VRMapPhi, EpilogBBs,
170bdd1243dSDimitry Andric                  PrologBBs);
1718bcb0991SDimitry Andric 
1728bcb0991SDimitry Andric   // We need this step because the register allocation doesn't handle some
1738bcb0991SDimitry Andric   // situations well, so we insert copies to help out.
1748bcb0991SDimitry Andric   splitLifetimes(KernelBB, EpilogBBs);
1758bcb0991SDimitry Andric 
1768bcb0991SDimitry Andric   // Remove dead instructions due to loop induction variables.
1778bcb0991SDimitry Andric   removeDeadInstructions(KernelBB, EpilogBBs);
1788bcb0991SDimitry Andric 
1798bcb0991SDimitry Andric   // Add branches between prolog and epilog blocks.
1808bcb0991SDimitry Andric   addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
1818bcb0991SDimitry Andric 
1828bcb0991SDimitry Andric   delete[] VRMap;
183bdd1243dSDimitry Andric   delete[] VRMapPhi;
1848bcb0991SDimitry Andric }
1858bcb0991SDimitry Andric 
1868bcb0991SDimitry Andric void ModuloScheduleExpander::cleanup() {
1878bcb0991SDimitry Andric   // Remove the original loop since it's no longer referenced.
1888bcb0991SDimitry Andric   for (auto &I : *BB)
1898bcb0991SDimitry Andric     LIS.RemoveMachineInstrFromMaps(I);
1908bcb0991SDimitry Andric   BB->clear();
1918bcb0991SDimitry Andric   BB->eraseFromParent();
1928bcb0991SDimitry Andric }
1938bcb0991SDimitry Andric 
1948bcb0991SDimitry Andric /// Generate the pipeline prolog code.
1958bcb0991SDimitry Andric void ModuloScheduleExpander::generateProlog(unsigned LastStage,
1968bcb0991SDimitry Andric                                             MachineBasicBlock *KernelBB,
1978bcb0991SDimitry Andric                                             ValueMapTy *VRMap,
1988bcb0991SDimitry Andric                                             MBBVectorTy &PrologBBs) {
1998bcb0991SDimitry Andric   MachineBasicBlock *PredBB = Preheader;
2008bcb0991SDimitry Andric   InstrMapTy InstrMap;
2018bcb0991SDimitry Andric 
2028bcb0991SDimitry Andric   // Generate a basic block for each stage, not including the last stage,
2038bcb0991SDimitry Andric   // which will be generated in the kernel. Each basic block may contain
2048bcb0991SDimitry Andric   // instructions from multiple stages/iterations.
2058bcb0991SDimitry Andric   for (unsigned i = 0; i < LastStage; ++i) {
2068bcb0991SDimitry Andric     // Create and insert the prolog basic block prior to the original loop
2078bcb0991SDimitry Andric     // basic block.  The original loop is removed later.
2088bcb0991SDimitry Andric     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2098bcb0991SDimitry Andric     PrologBBs.push_back(NewBB);
2108bcb0991SDimitry Andric     MF.insert(BB->getIterator(), NewBB);
2118bcb0991SDimitry Andric     NewBB->transferSuccessors(PredBB);
2128bcb0991SDimitry Andric     PredBB->addSuccessor(NewBB);
2138bcb0991SDimitry Andric     PredBB = NewBB;
214*c80e69b0SDimitry Andric     LIS.insertMBBInMaps(NewBB);
2158bcb0991SDimitry Andric 
2168bcb0991SDimitry Andric     // Generate instructions for each appropriate stage. Process instructions
2178bcb0991SDimitry Andric     // in original program order.
2188bcb0991SDimitry Andric     for (int StageNum = i; StageNum >= 0; --StageNum) {
2198bcb0991SDimitry Andric       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2208bcb0991SDimitry Andric                                        BBE = BB->getFirstTerminator();
2218bcb0991SDimitry Andric            BBI != BBE; ++BBI) {
2228bcb0991SDimitry Andric         if (Schedule.getStage(&*BBI) == StageNum) {
2238bcb0991SDimitry Andric           if (BBI->isPHI())
2248bcb0991SDimitry Andric             continue;
2258bcb0991SDimitry Andric           MachineInstr *NewMI =
2268bcb0991SDimitry Andric               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
2278bcb0991SDimitry Andric           updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
2288bcb0991SDimitry Andric           NewBB->push_back(NewMI);
2298bcb0991SDimitry Andric           InstrMap[NewMI] = &*BBI;
2308bcb0991SDimitry Andric         }
2318bcb0991SDimitry Andric       }
2328bcb0991SDimitry Andric     }
2338bcb0991SDimitry Andric     rewritePhiValues(NewBB, i, VRMap, InstrMap);
2348bcb0991SDimitry Andric     LLVM_DEBUG({
2358bcb0991SDimitry Andric       dbgs() << "prolog:\n";
2368bcb0991SDimitry Andric       NewBB->dump();
2378bcb0991SDimitry Andric     });
2388bcb0991SDimitry Andric   }
2398bcb0991SDimitry Andric 
2408bcb0991SDimitry Andric   PredBB->replaceSuccessor(BB, KernelBB);
2418bcb0991SDimitry Andric 
2428bcb0991SDimitry Andric   // Check if we need to remove the branch from the preheader to the original
2438bcb0991SDimitry Andric   // loop, and replace it with a branch to the new loop.
2448bcb0991SDimitry Andric   unsigned numBranches = TII->removeBranch(*Preheader);
2458bcb0991SDimitry Andric   if (numBranches) {
2468bcb0991SDimitry Andric     SmallVector<MachineOperand, 0> Cond;
2478bcb0991SDimitry Andric     TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
2488bcb0991SDimitry Andric   }
2498bcb0991SDimitry Andric }
2508bcb0991SDimitry Andric 
2518bcb0991SDimitry Andric /// Generate the pipeline epilog code. The epilog code finishes the iterations
2528bcb0991SDimitry Andric /// that were started in either the prolog or the kernel.  We create a basic
2538bcb0991SDimitry Andric /// block for each stage that needs to complete.
25481ad6265SDimitry Andric void ModuloScheduleExpander::generateEpilog(
25581ad6265SDimitry Andric     unsigned LastStage, MachineBasicBlock *KernelBB, MachineBasicBlock *OrigBB,
256bdd1243dSDimitry Andric     ValueMapTy *VRMap, ValueMapTy *VRMapPhi, MBBVectorTy &EpilogBBs,
257bdd1243dSDimitry Andric     MBBVectorTy &PrologBBs) {
2588bcb0991SDimitry Andric   // We need to change the branch from the kernel to the first epilog block, so
2598bcb0991SDimitry Andric   // this call to analyze branch uses the kernel rather than the original BB.
2608bcb0991SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2618bcb0991SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
2628bcb0991SDimitry Andric   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2638bcb0991SDimitry Andric   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2648bcb0991SDimitry Andric   if (checkBranch)
2658bcb0991SDimitry Andric     return;
2668bcb0991SDimitry Andric 
2678bcb0991SDimitry Andric   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2688bcb0991SDimitry Andric   if (*LoopExitI == KernelBB)
2698bcb0991SDimitry Andric     ++LoopExitI;
2708bcb0991SDimitry Andric   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2718bcb0991SDimitry Andric   MachineBasicBlock *LoopExitBB = *LoopExitI;
2728bcb0991SDimitry Andric 
2738bcb0991SDimitry Andric   MachineBasicBlock *PredBB = KernelBB;
2748bcb0991SDimitry Andric   MachineBasicBlock *EpilogStart = LoopExitBB;
2758bcb0991SDimitry Andric   InstrMapTy InstrMap;
2768bcb0991SDimitry Andric 
2778bcb0991SDimitry Andric   // Generate a basic block for each stage, not including the last stage,
2788bcb0991SDimitry Andric   // which was generated for the kernel.  Each basic block may contain
2798bcb0991SDimitry Andric   // instructions from multiple stages/iterations.
2808bcb0991SDimitry Andric   int EpilogStage = LastStage + 1;
2818bcb0991SDimitry Andric   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2828bcb0991SDimitry Andric     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2838bcb0991SDimitry Andric     EpilogBBs.push_back(NewBB);
2848bcb0991SDimitry Andric     MF.insert(BB->getIterator(), NewBB);
2858bcb0991SDimitry Andric 
2868bcb0991SDimitry Andric     PredBB->replaceSuccessor(LoopExitBB, NewBB);
2878bcb0991SDimitry Andric     NewBB->addSuccessor(LoopExitBB);
288*c80e69b0SDimitry Andric     LIS.insertMBBInMaps(NewBB);
2898bcb0991SDimitry Andric 
2908bcb0991SDimitry Andric     if (EpilogStart == LoopExitBB)
2918bcb0991SDimitry Andric       EpilogStart = NewBB;
2928bcb0991SDimitry Andric 
2938bcb0991SDimitry Andric     // Add instructions to the epilog depending on the current block.
2948bcb0991SDimitry Andric     // Process instructions in original program order.
2958bcb0991SDimitry Andric     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2968bcb0991SDimitry Andric       for (auto &BBI : *BB) {
2978bcb0991SDimitry Andric         if (BBI.isPHI())
2988bcb0991SDimitry Andric           continue;
2998bcb0991SDimitry Andric         MachineInstr *In = &BBI;
3008bcb0991SDimitry Andric         if ((unsigned)Schedule.getStage(In) == StageNum) {
3018bcb0991SDimitry Andric           // Instructions with memoperands in the epilog are updated with
3028bcb0991SDimitry Andric           // conservative values.
3038bcb0991SDimitry Andric           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
3048bcb0991SDimitry Andric           updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
3058bcb0991SDimitry Andric           NewBB->push_back(NewMI);
3068bcb0991SDimitry Andric           InstrMap[NewMI] = In;
3078bcb0991SDimitry Andric         }
3088bcb0991SDimitry Andric       }
3098bcb0991SDimitry Andric     }
3108bcb0991SDimitry Andric     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
3118bcb0991SDimitry Andric                          InstrMap, LastStage, EpilogStage, i == 1);
312bdd1243dSDimitry Andric     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, VRMapPhi,
313bdd1243dSDimitry Andric                  InstrMap, LastStage, EpilogStage, i == 1);
3148bcb0991SDimitry Andric     PredBB = NewBB;
3158bcb0991SDimitry Andric 
3168bcb0991SDimitry Andric     LLVM_DEBUG({
3178bcb0991SDimitry Andric       dbgs() << "epilog:\n";
3188bcb0991SDimitry Andric       NewBB->dump();
3198bcb0991SDimitry Andric     });
3208bcb0991SDimitry Andric   }
3218bcb0991SDimitry Andric 
3228bcb0991SDimitry Andric   // Fix any Phi nodes in the loop exit block.
3238bcb0991SDimitry Andric   LoopExitBB->replacePhiUsesWith(BB, PredBB);
3248bcb0991SDimitry Andric 
3258bcb0991SDimitry Andric   // Create a branch to the new epilog from the kernel.
3268bcb0991SDimitry Andric   // Remove the original branch and add a new branch to the epilog.
3278bcb0991SDimitry Andric   TII->removeBranch(*KernelBB);
32881ad6265SDimitry Andric   assert((OrigBB == TBB || OrigBB == FBB) &&
32981ad6265SDimitry Andric          "Unable to determine looping branch direction");
33081ad6265SDimitry Andric   if (OrigBB != TBB)
33181ad6265SDimitry Andric     TII->insertBranch(*KernelBB, EpilogStart, KernelBB, Cond, DebugLoc());
33281ad6265SDimitry Andric   else
3338bcb0991SDimitry Andric     TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
3348bcb0991SDimitry Andric   // Add a branch to the loop exit.
3358bcb0991SDimitry Andric   if (EpilogBBs.size() > 0) {
3368bcb0991SDimitry Andric     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
3378bcb0991SDimitry Andric     SmallVector<MachineOperand, 4> Cond1;
3388bcb0991SDimitry Andric     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
3398bcb0991SDimitry Andric   }
3408bcb0991SDimitry Andric }
3418bcb0991SDimitry Andric 
3428bcb0991SDimitry Andric /// Replace all uses of FromReg that appear outside the specified
3438bcb0991SDimitry Andric /// basic block with ToReg.
3448bcb0991SDimitry Andric static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
3458bcb0991SDimitry Andric                                     MachineBasicBlock *MBB,
3468bcb0991SDimitry Andric                                     MachineRegisterInfo &MRI,
3478bcb0991SDimitry Andric                                     LiveIntervals &LIS) {
348349cc55cSDimitry Andric   for (MachineOperand &O :
349349cc55cSDimitry Andric        llvm::make_early_inc_range(MRI.use_operands(FromReg)))
3508bcb0991SDimitry Andric     if (O.getParent()->getParent() != MBB)
3518bcb0991SDimitry Andric       O.setReg(ToReg);
3528bcb0991SDimitry Andric   if (!LIS.hasInterval(ToReg))
3538bcb0991SDimitry Andric     LIS.createEmptyInterval(ToReg);
3548bcb0991SDimitry Andric }
3558bcb0991SDimitry Andric 
3568bcb0991SDimitry Andric /// Return true if the register has a use that occurs outside the
3578bcb0991SDimitry Andric /// specified loop.
3588bcb0991SDimitry Andric static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
3598bcb0991SDimitry Andric                             MachineRegisterInfo &MRI) {
360349cc55cSDimitry Andric   for (const MachineOperand &MO : MRI.use_operands(Reg))
361349cc55cSDimitry Andric     if (MO.getParent()->getParent() != BB)
3628bcb0991SDimitry Andric       return true;
3638bcb0991SDimitry Andric   return false;
3648bcb0991SDimitry Andric }
3658bcb0991SDimitry Andric 
3668bcb0991SDimitry Andric /// Generate Phis for the specific block in the generated pipelined code.
3678bcb0991SDimitry Andric /// This function looks at the Phis from the original code to guide the
3688bcb0991SDimitry Andric /// creation of new Phis.
3698bcb0991SDimitry Andric void ModuloScheduleExpander::generateExistingPhis(
3708bcb0991SDimitry Andric     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
3718bcb0991SDimitry Andric     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
3728bcb0991SDimitry Andric     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
3738bcb0991SDimitry Andric   // Compute the stage number for the initial value of the Phi, which
3748bcb0991SDimitry Andric   // comes from the prolog. The prolog to use depends on to which kernel/
3758bcb0991SDimitry Andric   // epilog that we're adding the Phi.
3768bcb0991SDimitry Andric   unsigned PrologStage = 0;
3778bcb0991SDimitry Andric   unsigned PrevStage = 0;
3788bcb0991SDimitry Andric   bool InKernel = (LastStageNum == CurStageNum);
3798bcb0991SDimitry Andric   if (InKernel) {
3808bcb0991SDimitry Andric     PrologStage = LastStageNum - 1;
3818bcb0991SDimitry Andric     PrevStage = CurStageNum;
3828bcb0991SDimitry Andric   } else {
3838bcb0991SDimitry Andric     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
3848bcb0991SDimitry Andric     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
3858bcb0991SDimitry Andric   }
3868bcb0991SDimitry Andric 
3878bcb0991SDimitry Andric   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
3888bcb0991SDimitry Andric                                    BBE = BB->getFirstNonPHI();
3898bcb0991SDimitry Andric        BBI != BBE; ++BBI) {
3908bcb0991SDimitry Andric     Register Def = BBI->getOperand(0).getReg();
3918bcb0991SDimitry Andric 
3928bcb0991SDimitry Andric     unsigned InitVal = 0;
3938bcb0991SDimitry Andric     unsigned LoopVal = 0;
3948bcb0991SDimitry Andric     getPhiRegs(*BBI, BB, InitVal, LoopVal);
3958bcb0991SDimitry Andric 
3968bcb0991SDimitry Andric     unsigned PhiOp1 = 0;
3978bcb0991SDimitry Andric     // The Phi value from the loop body typically is defined in the loop, but
3988bcb0991SDimitry Andric     // not always. So, we need to check if the value is defined in the loop.
3998bcb0991SDimitry Andric     unsigned PhiOp2 = LoopVal;
4008bcb0991SDimitry Andric     if (VRMap[LastStageNum].count(LoopVal))
4018bcb0991SDimitry Andric       PhiOp2 = VRMap[LastStageNum][LoopVal];
4028bcb0991SDimitry Andric 
4038bcb0991SDimitry Andric     int StageScheduled = Schedule.getStage(&*BBI);
4048bcb0991SDimitry Andric     int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
4058bcb0991SDimitry Andric     unsigned NumStages = getStagesForReg(Def, CurStageNum);
4068bcb0991SDimitry Andric     if (NumStages == 0) {
4078bcb0991SDimitry Andric       // We don't need to generate a Phi anymore, but we need to rename any uses
4088bcb0991SDimitry Andric       // of the Phi value.
4098bcb0991SDimitry Andric       unsigned NewReg = VRMap[PrevStage][LoopVal];
4108bcb0991SDimitry Andric       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
4118bcb0991SDimitry Andric                             InitVal, NewReg);
4128bcb0991SDimitry Andric       if (VRMap[CurStageNum].count(LoopVal))
4138bcb0991SDimitry Andric         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
4148bcb0991SDimitry Andric     }
4158bcb0991SDimitry Andric     // Adjust the number of Phis needed depending on the number of prologs left,
4168bcb0991SDimitry Andric     // and the distance from where the Phi is first scheduled. The number of
4178bcb0991SDimitry Andric     // Phis cannot exceed the number of prolog stages. Each stage can
4188bcb0991SDimitry Andric     // potentially define two values.
4198bcb0991SDimitry Andric     unsigned MaxPhis = PrologStage + 2;
4208bcb0991SDimitry Andric     if (!InKernel && (int)PrologStage <= LoopValStage)
4218bcb0991SDimitry Andric       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
4228bcb0991SDimitry Andric     unsigned NumPhis = std::min(NumStages, MaxPhis);
4238bcb0991SDimitry Andric 
4248bcb0991SDimitry Andric     unsigned NewReg = 0;
4258bcb0991SDimitry Andric     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
4268bcb0991SDimitry Andric     // In the epilog, we may need to look back one stage to get the correct
4275ffd83dbSDimitry Andric     // Phi name, because the epilog and prolog blocks execute the same stage.
4288bcb0991SDimitry Andric     // The correct name is from the previous block only when the Phi has
4298bcb0991SDimitry Andric     // been completely scheduled prior to the epilog, and Phi value is not
4308bcb0991SDimitry Andric     // needed in multiple stages.
4318bcb0991SDimitry Andric     int StageDiff = 0;
4328bcb0991SDimitry Andric     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
4338bcb0991SDimitry Andric         NumPhis == 1)
4348bcb0991SDimitry Andric       StageDiff = 1;
4358bcb0991SDimitry Andric     // Adjust the computations below when the phi and the loop definition
4368bcb0991SDimitry Andric     // are scheduled in different stages.
4378bcb0991SDimitry Andric     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
4388bcb0991SDimitry Andric       StageDiff = StageScheduled - LoopValStage;
4398bcb0991SDimitry Andric     for (unsigned np = 0; np < NumPhis; ++np) {
4408bcb0991SDimitry Andric       // If the Phi hasn't been scheduled, then use the initial Phi operand
4418bcb0991SDimitry Andric       // value. Otherwise, use the scheduled version of the instruction. This
4428bcb0991SDimitry Andric       // is a little complicated when a Phi references another Phi.
4438bcb0991SDimitry Andric       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
4448bcb0991SDimitry Andric         PhiOp1 = InitVal;
4458bcb0991SDimitry Andric       // Check if the Phi has already been scheduled in a prolog stage.
4468bcb0991SDimitry Andric       else if (PrologStage >= AccessStage + StageDiff + np &&
4478bcb0991SDimitry Andric                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
4488bcb0991SDimitry Andric         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
4498bcb0991SDimitry Andric       // Check if the Phi has already been scheduled, but the loop instruction
4508bcb0991SDimitry Andric       // is either another Phi, or doesn't occur in the loop.
4518bcb0991SDimitry Andric       else if (PrologStage >= AccessStage + StageDiff + np) {
4528bcb0991SDimitry Andric         // If the Phi references another Phi, we need to examine the other
4538bcb0991SDimitry Andric         // Phi to get the correct value.
4548bcb0991SDimitry Andric         PhiOp1 = LoopVal;
4558bcb0991SDimitry Andric         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
4568bcb0991SDimitry Andric         int Indirects = 1;
4578bcb0991SDimitry Andric         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
4588bcb0991SDimitry Andric           int PhiStage = Schedule.getStage(InstOp1);
4598bcb0991SDimitry Andric           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
4608bcb0991SDimitry Andric             PhiOp1 = getInitPhiReg(*InstOp1, BB);
4618bcb0991SDimitry Andric           else
4628bcb0991SDimitry Andric             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
4638bcb0991SDimitry Andric           InstOp1 = MRI.getVRegDef(PhiOp1);
4648bcb0991SDimitry Andric           int PhiOpStage = Schedule.getStage(InstOp1);
4658bcb0991SDimitry Andric           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
4668bcb0991SDimitry Andric           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
4678bcb0991SDimitry Andric               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
4688bcb0991SDimitry Andric             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
4698bcb0991SDimitry Andric             break;
4708bcb0991SDimitry Andric           }
4718bcb0991SDimitry Andric           ++Indirects;
4728bcb0991SDimitry Andric         }
4738bcb0991SDimitry Andric       } else
4748bcb0991SDimitry Andric         PhiOp1 = InitVal;
4758bcb0991SDimitry Andric       // If this references a generated Phi in the kernel, get the Phi operand
4768bcb0991SDimitry Andric       // from the incoming block.
4778bcb0991SDimitry Andric       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
4788bcb0991SDimitry Andric         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
4798bcb0991SDimitry Andric           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
4808bcb0991SDimitry Andric 
4818bcb0991SDimitry Andric       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
4828bcb0991SDimitry Andric       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
4838bcb0991SDimitry Andric       // In the epilog, a map lookup is needed to get the value from the kernel,
4848bcb0991SDimitry Andric       // or previous epilog block. How is does this depends on if the
4858bcb0991SDimitry Andric       // instruction is scheduled in the previous block.
4868bcb0991SDimitry Andric       if (!InKernel) {
4878bcb0991SDimitry Andric         int StageDiffAdj = 0;
4888bcb0991SDimitry Andric         if (LoopValStage != -1 && StageScheduled > LoopValStage)
4898bcb0991SDimitry Andric           StageDiffAdj = StageScheduled - LoopValStage;
4908bcb0991SDimitry Andric         // Use the loop value defined in the kernel, unless the kernel
4918bcb0991SDimitry Andric         // contains the last definition of the Phi.
4928bcb0991SDimitry Andric         if (np == 0 && PrevStage == LastStageNum &&
4938bcb0991SDimitry Andric             (StageScheduled != 0 || LoopValStage != 0) &&
4948bcb0991SDimitry Andric             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
4958bcb0991SDimitry Andric           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
4968bcb0991SDimitry Andric         // Use the value defined by the Phi. We add one because we switch
4978bcb0991SDimitry Andric         // from looking at the loop value to the Phi definition.
4988bcb0991SDimitry Andric         else if (np > 0 && PrevStage == LastStageNum &&
4998bcb0991SDimitry Andric                  VRMap[PrevStage - np + 1].count(Def))
5008bcb0991SDimitry Andric           PhiOp2 = VRMap[PrevStage - np + 1][Def];
5018bcb0991SDimitry Andric         // Use the loop value defined in the kernel.
5028bcb0991SDimitry Andric         else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
5038bcb0991SDimitry Andric                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
5048bcb0991SDimitry Andric           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
5058bcb0991SDimitry Andric         // Use the value defined by the Phi, unless we're generating the first
5068bcb0991SDimitry Andric         // epilog and the Phi refers to a Phi in a different stage.
5078bcb0991SDimitry Andric         else if (VRMap[PrevStage - np].count(Def) &&
5088bcb0991SDimitry Andric                  (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
5098bcb0991SDimitry Andric                   (LoopValStage == StageScheduled)))
5108bcb0991SDimitry Andric           PhiOp2 = VRMap[PrevStage - np][Def];
5118bcb0991SDimitry Andric       }
5128bcb0991SDimitry Andric 
5138bcb0991SDimitry Andric       // Check if we can reuse an existing Phi. This occurs when a Phi
5148bcb0991SDimitry Andric       // references another Phi, and the other Phi is scheduled in an
5158bcb0991SDimitry Andric       // earlier stage. We can try to reuse an existing Phi up until the last
5168bcb0991SDimitry Andric       // stage of the current Phi.
5178bcb0991SDimitry Andric       if (LoopDefIsPhi) {
5188bcb0991SDimitry Andric         if (static_cast<int>(PrologStage - np) >= StageScheduled) {
5198bcb0991SDimitry Andric           int LVNumStages = getStagesForPhi(LoopVal);
5208bcb0991SDimitry Andric           int StageDiff = (StageScheduled - LoopValStage);
5218bcb0991SDimitry Andric           LVNumStages -= StageDiff;
5228bcb0991SDimitry Andric           // Make sure the loop value Phi has been processed already.
5238bcb0991SDimitry Andric           if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
5248bcb0991SDimitry Andric             NewReg = PhiOp2;
5258bcb0991SDimitry Andric             unsigned ReuseStage = CurStageNum;
5268bcb0991SDimitry Andric             if (isLoopCarried(*PhiInst))
5278bcb0991SDimitry Andric               ReuseStage -= LVNumStages;
5288bcb0991SDimitry Andric             // Check if the Phi to reuse has been generated yet. If not, then
5298bcb0991SDimitry Andric             // there is nothing to reuse.
5308bcb0991SDimitry Andric             if (VRMap[ReuseStage - np].count(LoopVal)) {
5318bcb0991SDimitry Andric               NewReg = VRMap[ReuseStage - np][LoopVal];
5328bcb0991SDimitry Andric 
5338bcb0991SDimitry Andric               rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
5348bcb0991SDimitry Andric                                     Def, NewReg);
5358bcb0991SDimitry Andric               // Update the map with the new Phi name.
5368bcb0991SDimitry Andric               VRMap[CurStageNum - np][Def] = NewReg;
5378bcb0991SDimitry Andric               PhiOp2 = NewReg;
5388bcb0991SDimitry Andric               if (VRMap[LastStageNum - np - 1].count(LoopVal))
5398bcb0991SDimitry Andric                 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
5408bcb0991SDimitry Andric 
5418bcb0991SDimitry Andric               if (IsLast && np == NumPhis - 1)
5428bcb0991SDimitry Andric                 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
5438bcb0991SDimitry Andric               continue;
5448bcb0991SDimitry Andric             }
5458bcb0991SDimitry Andric           }
5468bcb0991SDimitry Andric         }
5478bcb0991SDimitry Andric         if (InKernel && StageDiff > 0 &&
5488bcb0991SDimitry Andric             VRMap[CurStageNum - StageDiff - np].count(LoopVal))
5498bcb0991SDimitry Andric           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
5508bcb0991SDimitry Andric       }
5518bcb0991SDimitry Andric 
5528bcb0991SDimitry Andric       const TargetRegisterClass *RC = MRI.getRegClass(Def);
5538bcb0991SDimitry Andric       NewReg = MRI.createVirtualRegister(RC);
5548bcb0991SDimitry Andric 
5558bcb0991SDimitry Andric       MachineInstrBuilder NewPhi =
5568bcb0991SDimitry Andric           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
5578bcb0991SDimitry Andric                   TII->get(TargetOpcode::PHI), NewReg);
5588bcb0991SDimitry Andric       NewPhi.addReg(PhiOp1).addMBB(BB1);
5598bcb0991SDimitry Andric       NewPhi.addReg(PhiOp2).addMBB(BB2);
5608bcb0991SDimitry Andric       if (np == 0)
5618bcb0991SDimitry Andric         InstrMap[NewPhi] = &*BBI;
5628bcb0991SDimitry Andric 
5638bcb0991SDimitry Andric       // We define the Phis after creating the new pipelined code, so
5648bcb0991SDimitry Andric       // we need to rename the Phi values in scheduled instructions.
5658bcb0991SDimitry Andric 
5668bcb0991SDimitry Andric       unsigned PrevReg = 0;
5678bcb0991SDimitry Andric       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
5688bcb0991SDimitry Andric         PrevReg = VRMap[PrevStage - np][LoopVal];
5698bcb0991SDimitry Andric       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
5708bcb0991SDimitry Andric                             NewReg, PrevReg);
5718bcb0991SDimitry Andric       // If the Phi has been scheduled, use the new name for rewriting.
5728bcb0991SDimitry Andric       if (VRMap[CurStageNum - np].count(Def)) {
5738bcb0991SDimitry Andric         unsigned R = VRMap[CurStageNum - np][Def];
5748bcb0991SDimitry Andric         rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
5758bcb0991SDimitry Andric                               NewReg);
5768bcb0991SDimitry Andric       }
5778bcb0991SDimitry Andric 
5788bcb0991SDimitry Andric       // Check if we need to rename any uses that occurs after the loop. The
5798bcb0991SDimitry Andric       // register to replace depends on whether the Phi is scheduled in the
5808bcb0991SDimitry Andric       // epilog.
5818bcb0991SDimitry Andric       if (IsLast && np == NumPhis - 1)
5828bcb0991SDimitry Andric         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
5838bcb0991SDimitry Andric 
5848bcb0991SDimitry Andric       // In the kernel, a dependent Phi uses the value from this Phi.
5858bcb0991SDimitry Andric       if (InKernel)
5868bcb0991SDimitry Andric         PhiOp2 = NewReg;
5878bcb0991SDimitry Andric 
5888bcb0991SDimitry Andric       // Update the map with the new Phi name.
5898bcb0991SDimitry Andric       VRMap[CurStageNum - np][Def] = NewReg;
5908bcb0991SDimitry Andric     }
5918bcb0991SDimitry Andric 
5928bcb0991SDimitry Andric     while (NumPhis++ < NumStages) {
5938bcb0991SDimitry Andric       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
5948bcb0991SDimitry Andric                             NewReg, 0);
5958bcb0991SDimitry Andric     }
5968bcb0991SDimitry Andric 
5978bcb0991SDimitry Andric     // Check if we need to rename a Phi that has been eliminated due to
5988bcb0991SDimitry Andric     // scheduling.
5998bcb0991SDimitry Andric     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
6008bcb0991SDimitry Andric       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
6018bcb0991SDimitry Andric   }
6028bcb0991SDimitry Andric }
6038bcb0991SDimitry Andric 
6048bcb0991SDimitry Andric /// Generate Phis for the specified block in the generated pipelined code.
6058bcb0991SDimitry Andric /// These are new Phis needed because the definition is scheduled after the
6068bcb0991SDimitry Andric /// use in the pipelined sequence.
6078bcb0991SDimitry Andric void ModuloScheduleExpander::generatePhis(
6088bcb0991SDimitry Andric     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
609bdd1243dSDimitry Andric     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, ValueMapTy *VRMapPhi,
610bdd1243dSDimitry Andric     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
611bdd1243dSDimitry Andric     bool IsLast) {
6128bcb0991SDimitry Andric   // Compute the stage number that contains the initial Phi value, and
6138bcb0991SDimitry Andric   // the Phi from the previous stage.
6148bcb0991SDimitry Andric   unsigned PrologStage = 0;
6158bcb0991SDimitry Andric   unsigned PrevStage = 0;
6168bcb0991SDimitry Andric   unsigned StageDiff = CurStageNum - LastStageNum;
6178bcb0991SDimitry Andric   bool InKernel = (StageDiff == 0);
6188bcb0991SDimitry Andric   if (InKernel) {
6198bcb0991SDimitry Andric     PrologStage = LastStageNum - 1;
6208bcb0991SDimitry Andric     PrevStage = CurStageNum;
6218bcb0991SDimitry Andric   } else {
6228bcb0991SDimitry Andric     PrologStage = LastStageNum - StageDiff;
6238bcb0991SDimitry Andric     PrevStage = LastStageNum + StageDiff - 1;
6248bcb0991SDimitry Andric   }
6258bcb0991SDimitry Andric 
6268bcb0991SDimitry Andric   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
6278bcb0991SDimitry Andric                                    BBE = BB->instr_end();
6288bcb0991SDimitry Andric        BBI != BBE; ++BBI) {
6298bcb0991SDimitry Andric     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
6308bcb0991SDimitry Andric       MachineOperand &MO = BBI->getOperand(i);
631bdd1243dSDimitry Andric       if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
6328bcb0991SDimitry Andric         continue;
6338bcb0991SDimitry Andric 
6348bcb0991SDimitry Andric       int StageScheduled = Schedule.getStage(&*BBI);
6358bcb0991SDimitry Andric       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
6368bcb0991SDimitry Andric       Register Def = MO.getReg();
6378bcb0991SDimitry Andric       unsigned NumPhis = getStagesForReg(Def, CurStageNum);
6388bcb0991SDimitry Andric       // An instruction scheduled in stage 0 and is used after the loop
6398bcb0991SDimitry Andric       // requires a phi in the epilog for the last definition from either
6408bcb0991SDimitry Andric       // the kernel or prolog.
6418bcb0991SDimitry Andric       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
6428bcb0991SDimitry Andric           hasUseAfterLoop(Def, BB, MRI))
6438bcb0991SDimitry Andric         NumPhis = 1;
6448bcb0991SDimitry Andric       if (!InKernel && (unsigned)StageScheduled > PrologStage)
6458bcb0991SDimitry Andric         continue;
6468bcb0991SDimitry Andric 
647bdd1243dSDimitry Andric       unsigned PhiOp2;
648bdd1243dSDimitry Andric       if (InKernel) {
649bdd1243dSDimitry Andric         PhiOp2 = VRMap[PrevStage][Def];
6508bcb0991SDimitry Andric         if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
6518bcb0991SDimitry Andric           if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
6528bcb0991SDimitry Andric             PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
653bdd1243dSDimitry Andric       }
6548bcb0991SDimitry Andric       // The number of Phis can't exceed the number of prolog stages. The
6558bcb0991SDimitry Andric       // prolog stage number is zero based.
6568bcb0991SDimitry Andric       if (NumPhis > PrologStage + 1 - StageScheduled)
6578bcb0991SDimitry Andric         NumPhis = PrologStage + 1 - StageScheduled;
6588bcb0991SDimitry Andric       for (unsigned np = 0; np < NumPhis; ++np) {
659bdd1243dSDimitry Andric         // Example for
660bdd1243dSDimitry Andric         // Org:
661bdd1243dSDimitry Andric         //   %Org = ... (Scheduled at Stage#0, NumPhi = 2)
662bdd1243dSDimitry Andric         //
663bdd1243dSDimitry Andric         // Prolog0 (Stage0):
664bdd1243dSDimitry Andric         //   %Clone0 = ...
665bdd1243dSDimitry Andric         // Prolog1 (Stage1):
666bdd1243dSDimitry Andric         //   %Clone1 = ...
667bdd1243dSDimitry Andric         // Kernel (Stage2):
668bdd1243dSDimitry Andric         //   %Phi0 = Phi %Clone1, Prolog1, %Clone2, Kernel
669bdd1243dSDimitry Andric         //   %Phi1 = Phi %Clone0, Prolog1, %Phi0, Kernel
670bdd1243dSDimitry Andric         //   %Clone2 = ...
671bdd1243dSDimitry Andric         // Epilog0 (Stage3):
672bdd1243dSDimitry Andric         //   %Phi2 = Phi %Clone1, Prolog1, %Clone2, Kernel
673bdd1243dSDimitry Andric         //   %Phi3 = Phi %Clone0, Prolog1, %Phi0, Kernel
674bdd1243dSDimitry Andric         // Epilog1 (Stage4):
675bdd1243dSDimitry Andric         //   %Phi4 = Phi %Clone0, Prolog0, %Phi2, Epilog0
676bdd1243dSDimitry Andric         //
677bdd1243dSDimitry Andric         // VRMap = {0: %Clone0, 1: %Clone1, 2: %Clone2}
678bdd1243dSDimitry Andric         // VRMapPhi (after Kernel) = {0: %Phi1, 1: %Phi0}
679bdd1243dSDimitry Andric         // VRMapPhi (after Epilog0) = {0: %Phi3, 1: %Phi2}
680bdd1243dSDimitry Andric 
6818bcb0991SDimitry Andric         unsigned PhiOp1 = VRMap[PrologStage][Def];
6828bcb0991SDimitry Andric         if (np <= PrologStage)
6838bcb0991SDimitry Andric           PhiOp1 = VRMap[PrologStage - np][Def];
684bdd1243dSDimitry Andric         if (!InKernel) {
685bdd1243dSDimitry Andric           if (PrevStage == LastStageNum && np == 0)
686bdd1243dSDimitry Andric             PhiOp2 = VRMap[LastStageNum][Def];
687bdd1243dSDimitry Andric           else
688bdd1243dSDimitry Andric             PhiOp2 = VRMapPhi[PrevStage - np][Def];
6898bcb0991SDimitry Andric         }
6908bcb0991SDimitry Andric 
6918bcb0991SDimitry Andric         const TargetRegisterClass *RC = MRI.getRegClass(Def);
6928bcb0991SDimitry Andric         Register NewReg = MRI.createVirtualRegister(RC);
6938bcb0991SDimitry Andric 
6948bcb0991SDimitry Andric         MachineInstrBuilder NewPhi =
6958bcb0991SDimitry Andric             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
6968bcb0991SDimitry Andric                     TII->get(TargetOpcode::PHI), NewReg);
6978bcb0991SDimitry Andric         NewPhi.addReg(PhiOp1).addMBB(BB1);
6988bcb0991SDimitry Andric         NewPhi.addReg(PhiOp2).addMBB(BB2);
6998bcb0991SDimitry Andric         if (np == 0)
7008bcb0991SDimitry Andric           InstrMap[NewPhi] = &*BBI;
7018bcb0991SDimitry Andric 
7028bcb0991SDimitry Andric         // Rewrite uses and update the map. The actions depend upon whether
7038bcb0991SDimitry Andric         // we generating code for the kernel or epilog blocks.
7048bcb0991SDimitry Andric         if (InKernel) {
7058bcb0991SDimitry Andric           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
7068bcb0991SDimitry Andric                                 NewReg);
7078bcb0991SDimitry Andric           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
7088bcb0991SDimitry Andric                                 NewReg);
7098bcb0991SDimitry Andric 
7108bcb0991SDimitry Andric           PhiOp2 = NewReg;
711bdd1243dSDimitry Andric           VRMapPhi[PrevStage - np - 1][Def] = NewReg;
7128bcb0991SDimitry Andric         } else {
713bdd1243dSDimitry Andric           VRMapPhi[CurStageNum - np][Def] = NewReg;
7148bcb0991SDimitry Andric           if (np == NumPhis - 1)
7158bcb0991SDimitry Andric             rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
7168bcb0991SDimitry Andric                                   NewReg);
7178bcb0991SDimitry Andric         }
7188bcb0991SDimitry Andric         if (IsLast && np == NumPhis - 1)
7198bcb0991SDimitry Andric           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
7208bcb0991SDimitry Andric       }
7218bcb0991SDimitry Andric     }
7228bcb0991SDimitry Andric   }
7238bcb0991SDimitry Andric }
7248bcb0991SDimitry Andric 
7258bcb0991SDimitry Andric /// Remove instructions that generate values with no uses.
7268bcb0991SDimitry Andric /// Typically, these are induction variable operations that generate values
7278bcb0991SDimitry Andric /// used in the loop itself.  A dead instruction has a definition with
7288bcb0991SDimitry Andric /// no uses, or uses that occur in the original loop only.
7298bcb0991SDimitry Andric void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
7308bcb0991SDimitry Andric                                                     MBBVectorTy &EpilogBBs) {
7318bcb0991SDimitry Andric   // For each epilog block, check that the value defined by each instruction
7328bcb0991SDimitry Andric   // is used.  If not, delete it.
733349cc55cSDimitry Andric   for (MachineBasicBlock *MBB : llvm::reverse(EpilogBBs))
734349cc55cSDimitry Andric     for (MachineBasicBlock::reverse_instr_iterator MI = MBB->instr_rbegin(),
735349cc55cSDimitry Andric                                                    ME = MBB->instr_rend();
7368bcb0991SDimitry Andric          MI != ME;) {
7378bcb0991SDimitry Andric       // From DeadMachineInstructionElem. Don't delete inline assembly.
7388bcb0991SDimitry Andric       if (MI->isInlineAsm()) {
7398bcb0991SDimitry Andric         ++MI;
7408bcb0991SDimitry Andric         continue;
7418bcb0991SDimitry Andric       }
7428bcb0991SDimitry Andric       bool SawStore = false;
7438bcb0991SDimitry Andric       // Check if it's safe to remove the instruction due to side effects.
7448bcb0991SDimitry Andric       // We can, and want to, remove Phis here.
7458bcb0991SDimitry Andric       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
7468bcb0991SDimitry Andric         ++MI;
7478bcb0991SDimitry Andric         continue;
7488bcb0991SDimitry Andric       }
7498bcb0991SDimitry Andric       bool used = true;
75006c3fb27SDimitry Andric       for (const MachineOperand &MO : MI->all_defs()) {
751349cc55cSDimitry Andric         Register reg = MO.getReg();
7528bcb0991SDimitry Andric         // Assume physical registers are used, unless they are marked dead.
753bdd1243dSDimitry Andric         if (reg.isPhysical()) {
754349cc55cSDimitry Andric           used = !MO.isDead();
7558bcb0991SDimitry Andric           if (used)
7568bcb0991SDimitry Andric             break;
7578bcb0991SDimitry Andric           continue;
7588bcb0991SDimitry Andric         }
7598bcb0991SDimitry Andric         unsigned realUses = 0;
760349cc55cSDimitry Andric         for (const MachineOperand &U : MRI.use_operands(reg)) {
7618bcb0991SDimitry Andric           // Check if there are any uses that occur only in the original
7628bcb0991SDimitry Andric           // loop.  If so, that's not a real use.
763349cc55cSDimitry Andric           if (U.getParent()->getParent() != BB) {
7648bcb0991SDimitry Andric             realUses++;
7658bcb0991SDimitry Andric             used = true;
7668bcb0991SDimitry Andric             break;
7678bcb0991SDimitry Andric           }
7688bcb0991SDimitry Andric         }
7698bcb0991SDimitry Andric         if (realUses > 0)
7708bcb0991SDimitry Andric           break;
7718bcb0991SDimitry Andric         used = false;
7728bcb0991SDimitry Andric       }
7738bcb0991SDimitry Andric       if (!used) {
7748bcb0991SDimitry Andric         LIS.RemoveMachineInstrFromMaps(*MI);
7758bcb0991SDimitry Andric         MI++->eraseFromParent();
7768bcb0991SDimitry Andric         continue;
7778bcb0991SDimitry Andric       }
7788bcb0991SDimitry Andric       ++MI;
7798bcb0991SDimitry Andric     }
7808bcb0991SDimitry Andric   // In the kernel block, check if we can remove a Phi that generates a value
7818bcb0991SDimitry Andric   // used in an instruction removed in the epilog block.
782349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(KernelBB->phis())) {
783349cc55cSDimitry Andric     Register reg = MI.getOperand(0).getReg();
7848bcb0991SDimitry Andric     if (MRI.use_begin(reg) == MRI.use_end()) {
785349cc55cSDimitry Andric       LIS.RemoveMachineInstrFromMaps(MI);
786349cc55cSDimitry Andric       MI.eraseFromParent();
7878bcb0991SDimitry Andric     }
7888bcb0991SDimitry Andric   }
7898bcb0991SDimitry Andric }
7908bcb0991SDimitry Andric 
7918bcb0991SDimitry Andric /// For loop carried definitions, we split the lifetime of a virtual register
7928bcb0991SDimitry Andric /// that has uses past the definition in the next iteration. A copy with a new
7938bcb0991SDimitry Andric /// virtual register is inserted before the definition, which helps with
7948bcb0991SDimitry Andric /// generating a better register assignment.
7958bcb0991SDimitry Andric ///
7968bcb0991SDimitry Andric ///   v1 = phi(a, v2)     v1 = phi(a, v2)
7978bcb0991SDimitry Andric ///   v2 = phi(b, v3)     v2 = phi(b, v3)
7988bcb0991SDimitry Andric ///   v3 = ..             v4 = copy v1
7998bcb0991SDimitry Andric ///   .. = V1             v3 = ..
8008bcb0991SDimitry Andric ///                       .. = v4
8018bcb0991SDimitry Andric void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
8028bcb0991SDimitry Andric                                             MBBVectorTy &EpilogBBs) {
8038bcb0991SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
8048bcb0991SDimitry Andric   for (auto &PHI : KernelBB->phis()) {
8058bcb0991SDimitry Andric     Register Def = PHI.getOperand(0).getReg();
8068bcb0991SDimitry Andric     // Check for any Phi definition that used as an operand of another Phi
8078bcb0991SDimitry Andric     // in the same block.
8088bcb0991SDimitry Andric     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
8098bcb0991SDimitry Andric                                                  E = MRI.use_instr_end();
8108bcb0991SDimitry Andric          I != E; ++I) {
8118bcb0991SDimitry Andric       if (I->isPHI() && I->getParent() == KernelBB) {
8128bcb0991SDimitry Andric         // Get the loop carried definition.
8138bcb0991SDimitry Andric         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
8148bcb0991SDimitry Andric         if (!LCDef)
8158bcb0991SDimitry Andric           continue;
8168bcb0991SDimitry Andric         MachineInstr *MI = MRI.getVRegDef(LCDef);
8178bcb0991SDimitry Andric         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
8188bcb0991SDimitry Andric           continue;
8198bcb0991SDimitry Andric         // Search through the rest of the block looking for uses of the Phi
8208bcb0991SDimitry Andric         // definition. If one occurs, then split the lifetime.
8218bcb0991SDimitry Andric         unsigned SplitReg = 0;
8228bcb0991SDimitry Andric         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
8238bcb0991SDimitry Andric                                     KernelBB->instr_end()))
8240fca6ea1SDimitry Andric           if (BBJ.readsRegister(Def, /*TRI=*/nullptr)) {
8258bcb0991SDimitry Andric             // We split the lifetime when we find the first use.
8268bcb0991SDimitry Andric             if (SplitReg == 0) {
8278bcb0991SDimitry Andric               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
8288bcb0991SDimitry Andric               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
8298bcb0991SDimitry Andric                       TII->get(TargetOpcode::COPY), SplitReg)
8308bcb0991SDimitry Andric                   .addReg(Def);
8318bcb0991SDimitry Andric             }
8328bcb0991SDimitry Andric             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
8338bcb0991SDimitry Andric           }
8348bcb0991SDimitry Andric         if (!SplitReg)
8358bcb0991SDimitry Andric           continue;
8368bcb0991SDimitry Andric         // Search through each of the epilog blocks for any uses to be renamed.
8378bcb0991SDimitry Andric         for (auto &Epilog : EpilogBBs)
8388bcb0991SDimitry Andric           for (auto &I : *Epilog)
8390fca6ea1SDimitry Andric             if (I.readsRegister(Def, /*TRI=*/nullptr))
8408bcb0991SDimitry Andric               I.substituteRegister(Def, SplitReg, 0, *TRI);
8418bcb0991SDimitry Andric         break;
8428bcb0991SDimitry Andric       }
8438bcb0991SDimitry Andric     }
8448bcb0991SDimitry Andric   }
8458bcb0991SDimitry Andric }
8468bcb0991SDimitry Andric 
8478bcb0991SDimitry Andric /// Remove the incoming block from the Phis in a basic block.
8488bcb0991SDimitry Andric static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
8498bcb0991SDimitry Andric   for (MachineInstr &MI : *BB) {
8508bcb0991SDimitry Andric     if (!MI.isPHI())
8518bcb0991SDimitry Andric       break;
8528bcb0991SDimitry Andric     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
8538bcb0991SDimitry Andric       if (MI.getOperand(i + 1).getMBB() == Incoming) {
85481ad6265SDimitry Andric         MI.removeOperand(i + 1);
85581ad6265SDimitry Andric         MI.removeOperand(i);
8568bcb0991SDimitry Andric         break;
8578bcb0991SDimitry Andric       }
8588bcb0991SDimitry Andric   }
8598bcb0991SDimitry Andric }
8608bcb0991SDimitry Andric 
8618bcb0991SDimitry Andric /// Create branches from each prolog basic block to the appropriate epilog
8628bcb0991SDimitry Andric /// block.  These edges are needed if the loop ends before reaching the
8638bcb0991SDimitry Andric /// kernel.
8648bcb0991SDimitry Andric void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
8658bcb0991SDimitry Andric                                          MBBVectorTy &PrologBBs,
8668bcb0991SDimitry Andric                                          MachineBasicBlock *KernelBB,
8678bcb0991SDimitry Andric                                          MBBVectorTy &EpilogBBs,
8688bcb0991SDimitry Andric                                          ValueMapTy *VRMap) {
8698bcb0991SDimitry Andric   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
8708bcb0991SDimitry Andric   MachineBasicBlock *LastPro = KernelBB;
8718bcb0991SDimitry Andric   MachineBasicBlock *LastEpi = KernelBB;
8728bcb0991SDimitry Andric 
8738bcb0991SDimitry Andric   // Start from the blocks connected to the kernel and work "out"
8748bcb0991SDimitry Andric   // to the first prolog and the last epilog blocks.
8758bcb0991SDimitry Andric   SmallVector<MachineInstr *, 4> PrevInsts;
8768bcb0991SDimitry Andric   unsigned MaxIter = PrologBBs.size() - 1;
8778bcb0991SDimitry Andric   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
8788bcb0991SDimitry Andric     // Add branches to the prolog that go to the corresponding
8798bcb0991SDimitry Andric     // epilog, and the fall-thru prolog/kernel block.
8808bcb0991SDimitry Andric     MachineBasicBlock *Prolog = PrologBBs[j];
8818bcb0991SDimitry Andric     MachineBasicBlock *Epilog = EpilogBBs[i];
8828bcb0991SDimitry Andric 
8838bcb0991SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
884bdd1243dSDimitry Andric     std::optional<bool> StaticallyGreater =
8858bcb0991SDimitry Andric         LoopInfo->createTripCountGreaterCondition(j + 1, *Prolog, Cond);
8868bcb0991SDimitry Andric     unsigned numAdded = 0;
88781ad6265SDimitry Andric     if (!StaticallyGreater) {
8888bcb0991SDimitry Andric       Prolog->addSuccessor(Epilog);
8898bcb0991SDimitry Andric       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
8908bcb0991SDimitry Andric     } else if (*StaticallyGreater == false) {
8918bcb0991SDimitry Andric       Prolog->addSuccessor(Epilog);
8928bcb0991SDimitry Andric       Prolog->removeSuccessor(LastPro);
8938bcb0991SDimitry Andric       LastEpi->removeSuccessor(Epilog);
8948bcb0991SDimitry Andric       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
8958bcb0991SDimitry Andric       removePhis(Epilog, LastEpi);
8968bcb0991SDimitry Andric       // Remove the blocks that are no longer referenced.
8978bcb0991SDimitry Andric       if (LastPro != LastEpi) {
8988bcb0991SDimitry Andric         LastEpi->clear();
8998bcb0991SDimitry Andric         LastEpi->eraseFromParent();
9008bcb0991SDimitry Andric       }
9018bcb0991SDimitry Andric       if (LastPro == KernelBB) {
9028bcb0991SDimitry Andric         LoopInfo->disposed();
9038bcb0991SDimitry Andric         NewKernel = nullptr;
9048bcb0991SDimitry Andric       }
9058bcb0991SDimitry Andric       LastPro->clear();
9068bcb0991SDimitry Andric       LastPro->eraseFromParent();
9078bcb0991SDimitry Andric     } else {
9088bcb0991SDimitry Andric       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
9098bcb0991SDimitry Andric       removePhis(Epilog, Prolog);
9108bcb0991SDimitry Andric     }
9118bcb0991SDimitry Andric     LastPro = Prolog;
9128bcb0991SDimitry Andric     LastEpi = Epilog;
9138bcb0991SDimitry Andric     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
9148bcb0991SDimitry Andric                                                    E = Prolog->instr_rend();
9158bcb0991SDimitry Andric          I != E && numAdded > 0; ++I, --numAdded)
9168bcb0991SDimitry Andric       updateInstruction(&*I, false, j, 0, VRMap);
9178bcb0991SDimitry Andric   }
9188bcb0991SDimitry Andric 
9198bcb0991SDimitry Andric   if (NewKernel) {
9208bcb0991SDimitry Andric     LoopInfo->setPreheader(PrologBBs[MaxIter]);
9218bcb0991SDimitry Andric     LoopInfo->adjustTripCount(-(MaxIter + 1));
9228bcb0991SDimitry Andric   }
9238bcb0991SDimitry Andric }
9248bcb0991SDimitry Andric 
9258bcb0991SDimitry Andric /// Return true if we can compute the amount the instruction changes
9268bcb0991SDimitry Andric /// during each iteration. Set Delta to the amount of the change.
9278bcb0991SDimitry Andric bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
9288bcb0991SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
9298bcb0991SDimitry Andric   const MachineOperand *BaseOp;
9308bcb0991SDimitry Andric   int64_t Offset;
9315ffd83dbSDimitry Andric   bool OffsetIsScalable;
9325ffd83dbSDimitry Andric   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
9335ffd83dbSDimitry Andric     return false;
9345ffd83dbSDimitry Andric 
9355ffd83dbSDimitry Andric   // FIXME: This algorithm assumes instructions have fixed-size offsets.
9365ffd83dbSDimitry Andric   if (OffsetIsScalable)
9378bcb0991SDimitry Andric     return false;
9388bcb0991SDimitry Andric 
9398bcb0991SDimitry Andric   if (!BaseOp->isReg())
9408bcb0991SDimitry Andric     return false;
9418bcb0991SDimitry Andric 
9428bcb0991SDimitry Andric   Register BaseReg = BaseOp->getReg();
9438bcb0991SDimitry Andric 
9448bcb0991SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
9458bcb0991SDimitry Andric   // Check if there is a Phi. If so, get the definition in the loop.
9468bcb0991SDimitry Andric   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
9478bcb0991SDimitry Andric   if (BaseDef && BaseDef->isPHI()) {
9488bcb0991SDimitry Andric     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
9498bcb0991SDimitry Andric     BaseDef = MRI.getVRegDef(BaseReg);
9508bcb0991SDimitry Andric   }
9518bcb0991SDimitry Andric   if (!BaseDef)
9528bcb0991SDimitry Andric     return false;
9538bcb0991SDimitry Andric 
9548bcb0991SDimitry Andric   int D = 0;
9558bcb0991SDimitry Andric   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
9568bcb0991SDimitry Andric     return false;
9578bcb0991SDimitry Andric 
9588bcb0991SDimitry Andric   Delta = D;
9598bcb0991SDimitry Andric   return true;
9608bcb0991SDimitry Andric }
9618bcb0991SDimitry Andric 
9628bcb0991SDimitry Andric /// Update the memory operand with a new offset when the pipeliner
9638bcb0991SDimitry Andric /// generates a new copy of the instruction that refers to a
9648bcb0991SDimitry Andric /// different memory location.
9658bcb0991SDimitry Andric void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
9668bcb0991SDimitry Andric                                                MachineInstr &OldMI,
9678bcb0991SDimitry Andric                                                unsigned Num) {
9688bcb0991SDimitry Andric   if (Num == 0)
9698bcb0991SDimitry Andric     return;
9708bcb0991SDimitry Andric   // If the instruction has memory operands, then adjust the offset
9718bcb0991SDimitry Andric   // when the instruction appears in different stages.
9728bcb0991SDimitry Andric   if (NewMI.memoperands_empty())
9738bcb0991SDimitry Andric     return;
9748bcb0991SDimitry Andric   SmallVector<MachineMemOperand *, 2> NewMMOs;
9758bcb0991SDimitry Andric   for (MachineMemOperand *MMO : NewMI.memoperands()) {
9768bcb0991SDimitry Andric     // TODO: Figure out whether isAtomic is really necessary (see D57601).
9778bcb0991SDimitry Andric     if (MMO->isVolatile() || MMO->isAtomic() ||
9788bcb0991SDimitry Andric         (MMO->isInvariant() && MMO->isDereferenceable()) ||
9798bcb0991SDimitry Andric         (!MMO->getValue())) {
9808bcb0991SDimitry Andric       NewMMOs.push_back(MMO);
9818bcb0991SDimitry Andric       continue;
9828bcb0991SDimitry Andric     }
9838bcb0991SDimitry Andric     unsigned Delta;
9848bcb0991SDimitry Andric     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
9858bcb0991SDimitry Andric       int64_t AdjOffset = Delta * Num;
9868bcb0991SDimitry Andric       NewMMOs.push_back(
9878bcb0991SDimitry Andric           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
9888bcb0991SDimitry Andric     } else {
9890fca6ea1SDimitry Andric       NewMMOs.push_back(MF.getMachineMemOperand(
9900fca6ea1SDimitry Andric           MMO, 0, LocationSize::beforeOrAfterPointer()));
9918bcb0991SDimitry Andric     }
9928bcb0991SDimitry Andric   }
9938bcb0991SDimitry Andric   NewMI.setMemRefs(MF, NewMMOs);
9948bcb0991SDimitry Andric }
9958bcb0991SDimitry Andric 
9968bcb0991SDimitry Andric /// Clone the instruction for the new pipelined loop and update the
9978bcb0991SDimitry Andric /// memory operands, if needed.
9988bcb0991SDimitry Andric MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
9998bcb0991SDimitry Andric                                                  unsigned CurStageNum,
10008bcb0991SDimitry Andric                                                  unsigned InstStageNum) {
10018bcb0991SDimitry Andric   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
10028bcb0991SDimitry Andric   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
10038bcb0991SDimitry Andric   return NewMI;
10048bcb0991SDimitry Andric }
10058bcb0991SDimitry Andric 
10068bcb0991SDimitry Andric /// Clone the instruction for the new pipelined loop. If needed, this
10078bcb0991SDimitry Andric /// function updates the instruction using the values saved in the
10088bcb0991SDimitry Andric /// InstrChanges structure.
10098bcb0991SDimitry Andric MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
10108bcb0991SDimitry Andric     MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
10118bcb0991SDimitry Andric   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
10128bcb0991SDimitry Andric   auto It = InstrChanges.find(OldMI);
10138bcb0991SDimitry Andric   if (It != InstrChanges.end()) {
10148bcb0991SDimitry Andric     std::pair<unsigned, int64_t> RegAndOffset = It->second;
10158bcb0991SDimitry Andric     unsigned BasePos, OffsetPos;
10168bcb0991SDimitry Andric     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
10178bcb0991SDimitry Andric       return nullptr;
10188bcb0991SDimitry Andric     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
10198bcb0991SDimitry Andric     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
10208bcb0991SDimitry Andric     if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
10218bcb0991SDimitry Andric       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
10228bcb0991SDimitry Andric     NewMI->getOperand(OffsetPos).setImm(NewOffset);
10238bcb0991SDimitry Andric   }
10248bcb0991SDimitry Andric   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
10258bcb0991SDimitry Andric   return NewMI;
10268bcb0991SDimitry Andric }
10278bcb0991SDimitry Andric 
10288bcb0991SDimitry Andric /// Update the machine instruction with new virtual registers.  This
102981ad6265SDimitry Andric /// function may change the definitions and/or uses.
10308bcb0991SDimitry Andric void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
10318bcb0991SDimitry Andric                                                bool LastDef,
10328bcb0991SDimitry Andric                                                unsigned CurStageNum,
10338bcb0991SDimitry Andric                                                unsigned InstrStageNum,
10348bcb0991SDimitry Andric                                                ValueMapTy *VRMap) {
10354824e7fdSDimitry Andric   for (MachineOperand &MO : NewMI->operands()) {
1036bdd1243dSDimitry Andric     if (!MO.isReg() || !MO.getReg().isVirtual())
10378bcb0991SDimitry Andric       continue;
10388bcb0991SDimitry Andric     Register reg = MO.getReg();
10398bcb0991SDimitry Andric     if (MO.isDef()) {
10408bcb0991SDimitry Andric       // Create a new virtual register for the definition.
10418bcb0991SDimitry Andric       const TargetRegisterClass *RC = MRI.getRegClass(reg);
10428bcb0991SDimitry Andric       Register NewReg = MRI.createVirtualRegister(RC);
10438bcb0991SDimitry Andric       MO.setReg(NewReg);
10448bcb0991SDimitry Andric       VRMap[CurStageNum][reg] = NewReg;
10458bcb0991SDimitry Andric       if (LastDef)
10468bcb0991SDimitry Andric         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
10478bcb0991SDimitry Andric     } else if (MO.isUse()) {
10488bcb0991SDimitry Andric       MachineInstr *Def = MRI.getVRegDef(reg);
10498bcb0991SDimitry Andric       // Compute the stage that contains the last definition for instruction.
10508bcb0991SDimitry Andric       int DefStageNum = Schedule.getStage(Def);
10518bcb0991SDimitry Andric       unsigned StageNum = CurStageNum;
10528bcb0991SDimitry Andric       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
10538bcb0991SDimitry Andric         // Compute the difference in stages between the defintion and the use.
10548bcb0991SDimitry Andric         unsigned StageDiff = (InstrStageNum - DefStageNum);
10558bcb0991SDimitry Andric         // Make an adjustment to get the last definition.
10568bcb0991SDimitry Andric         StageNum -= StageDiff;
10578bcb0991SDimitry Andric       }
10588bcb0991SDimitry Andric       if (VRMap[StageNum].count(reg))
10598bcb0991SDimitry Andric         MO.setReg(VRMap[StageNum][reg]);
10608bcb0991SDimitry Andric     }
10618bcb0991SDimitry Andric   }
10628bcb0991SDimitry Andric }
10638bcb0991SDimitry Andric 
10648bcb0991SDimitry Andric /// Return the instruction in the loop that defines the register.
10658bcb0991SDimitry Andric /// If the definition is a Phi, then follow the Phi operand to
10668bcb0991SDimitry Andric /// the instruction in the loop.
10678bcb0991SDimitry Andric MachineInstr *ModuloScheduleExpander::findDefInLoop(unsigned Reg) {
10688bcb0991SDimitry Andric   SmallPtrSet<MachineInstr *, 8> Visited;
10698bcb0991SDimitry Andric   MachineInstr *Def = MRI.getVRegDef(Reg);
10708bcb0991SDimitry Andric   while (Def->isPHI()) {
10718bcb0991SDimitry Andric     if (!Visited.insert(Def).second)
10728bcb0991SDimitry Andric       break;
10738bcb0991SDimitry Andric     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
10748bcb0991SDimitry Andric       if (Def->getOperand(i + 1).getMBB() == BB) {
10758bcb0991SDimitry Andric         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
10768bcb0991SDimitry Andric         break;
10778bcb0991SDimitry Andric       }
10788bcb0991SDimitry Andric   }
10798bcb0991SDimitry Andric   return Def;
10808bcb0991SDimitry Andric }
10818bcb0991SDimitry Andric 
10828bcb0991SDimitry Andric /// Return the new name for the value from the previous stage.
10838bcb0991SDimitry Andric unsigned ModuloScheduleExpander::getPrevMapVal(
10848bcb0991SDimitry Andric     unsigned StageNum, unsigned PhiStage, unsigned LoopVal, unsigned LoopStage,
10858bcb0991SDimitry Andric     ValueMapTy *VRMap, MachineBasicBlock *BB) {
10868bcb0991SDimitry Andric   unsigned PrevVal = 0;
10878bcb0991SDimitry Andric   if (StageNum > PhiStage) {
10888bcb0991SDimitry Andric     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
10898bcb0991SDimitry Andric     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
10908bcb0991SDimitry Andric       // The name is defined in the previous stage.
10918bcb0991SDimitry Andric       PrevVal = VRMap[StageNum - 1][LoopVal];
10928bcb0991SDimitry Andric     else if (VRMap[StageNum].count(LoopVal))
10938bcb0991SDimitry Andric       // The previous name is defined in the current stage when the instruction
10948bcb0991SDimitry Andric       // order is swapped.
10958bcb0991SDimitry Andric       PrevVal = VRMap[StageNum][LoopVal];
10968bcb0991SDimitry Andric     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
10978bcb0991SDimitry Andric       // The loop value hasn't yet been scheduled.
10988bcb0991SDimitry Andric       PrevVal = LoopVal;
10998bcb0991SDimitry Andric     else if (StageNum == PhiStage + 1)
11008bcb0991SDimitry Andric       // The loop value is another phi, which has not been scheduled.
11018bcb0991SDimitry Andric       PrevVal = getInitPhiReg(*LoopInst, BB);
11028bcb0991SDimitry Andric     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
11038bcb0991SDimitry Andric       // The loop value is another phi, which has been scheduled.
11048bcb0991SDimitry Andric       PrevVal =
11058bcb0991SDimitry Andric           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
11068bcb0991SDimitry Andric                         LoopStage, VRMap, BB);
11078bcb0991SDimitry Andric   }
11088bcb0991SDimitry Andric   return PrevVal;
11098bcb0991SDimitry Andric }
11108bcb0991SDimitry Andric 
11118bcb0991SDimitry Andric /// Rewrite the Phi values in the specified block to use the mappings
11128bcb0991SDimitry Andric /// from the initial operand. Once the Phi is scheduled, we switch
11138bcb0991SDimitry Andric /// to using the loop value instead of the Phi value, so those names
11148bcb0991SDimitry Andric /// do not need to be rewritten.
11158bcb0991SDimitry Andric void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
11168bcb0991SDimitry Andric                                               unsigned StageNum,
11178bcb0991SDimitry Andric                                               ValueMapTy *VRMap,
11188bcb0991SDimitry Andric                                               InstrMapTy &InstrMap) {
11198bcb0991SDimitry Andric   for (auto &PHI : BB->phis()) {
11208bcb0991SDimitry Andric     unsigned InitVal = 0;
11218bcb0991SDimitry Andric     unsigned LoopVal = 0;
11228bcb0991SDimitry Andric     getPhiRegs(PHI, BB, InitVal, LoopVal);
11238bcb0991SDimitry Andric     Register PhiDef = PHI.getOperand(0).getReg();
11248bcb0991SDimitry Andric 
11258bcb0991SDimitry Andric     unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
11268bcb0991SDimitry Andric     unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
11278bcb0991SDimitry Andric     unsigned NumPhis = getStagesForPhi(PhiDef);
11288bcb0991SDimitry Andric     if (NumPhis > StageNum)
11298bcb0991SDimitry Andric       NumPhis = StageNum;
11308bcb0991SDimitry Andric     for (unsigned np = 0; np <= NumPhis; ++np) {
11318bcb0991SDimitry Andric       unsigned NewVal =
11328bcb0991SDimitry Andric           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
11338bcb0991SDimitry Andric       if (!NewVal)
11348bcb0991SDimitry Andric         NewVal = InitVal;
11358bcb0991SDimitry Andric       rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
11368bcb0991SDimitry Andric                             NewVal);
11378bcb0991SDimitry Andric     }
11388bcb0991SDimitry Andric   }
11398bcb0991SDimitry Andric }
11408bcb0991SDimitry Andric 
11418bcb0991SDimitry Andric /// Rewrite a previously scheduled instruction to use the register value
11428bcb0991SDimitry Andric /// from the new instruction. Make sure the instruction occurs in the
11438bcb0991SDimitry Andric /// basic block, and we don't change the uses in the new instruction.
11448bcb0991SDimitry Andric void ModuloScheduleExpander::rewriteScheduledInstr(
11458bcb0991SDimitry Andric     MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
11468bcb0991SDimitry Andric     unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, unsigned NewReg,
11478bcb0991SDimitry Andric     unsigned PrevReg) {
11488bcb0991SDimitry Andric   bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
11498bcb0991SDimitry Andric   int StagePhi = Schedule.getStage(Phi) + PhiNum;
11508bcb0991SDimitry Andric   // Rewrite uses that have been scheduled already to use the new
11518bcb0991SDimitry Andric   // Phi register.
1152349cc55cSDimitry Andric   for (MachineOperand &UseOp :
1153349cc55cSDimitry Andric        llvm::make_early_inc_range(MRI.use_operands(OldReg))) {
11548bcb0991SDimitry Andric     MachineInstr *UseMI = UseOp.getParent();
11558bcb0991SDimitry Andric     if (UseMI->getParent() != BB)
11568bcb0991SDimitry Andric       continue;
11578bcb0991SDimitry Andric     if (UseMI->isPHI()) {
11588bcb0991SDimitry Andric       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
11598bcb0991SDimitry Andric         continue;
11608bcb0991SDimitry Andric       if (getLoopPhiReg(*UseMI, BB) != OldReg)
11618bcb0991SDimitry Andric         continue;
11628bcb0991SDimitry Andric     }
11638bcb0991SDimitry Andric     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
11648bcb0991SDimitry Andric     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
11658bcb0991SDimitry Andric     MachineInstr *OrigMI = OrigInstr->second;
11668bcb0991SDimitry Andric     int StageSched = Schedule.getStage(OrigMI);
11678bcb0991SDimitry Andric     int CycleSched = Schedule.getCycle(OrigMI);
11688bcb0991SDimitry Andric     unsigned ReplaceReg = 0;
11698bcb0991SDimitry Andric     // This is the stage for the scheduled instruction.
11708bcb0991SDimitry Andric     if (StagePhi == StageSched && Phi->isPHI()) {
11718bcb0991SDimitry Andric       int CyclePhi = Schedule.getCycle(Phi);
11728bcb0991SDimitry Andric       if (PrevReg && InProlog)
11738bcb0991SDimitry Andric         ReplaceReg = PrevReg;
11748bcb0991SDimitry Andric       else if (PrevReg && !isLoopCarried(*Phi) &&
11758bcb0991SDimitry Andric                (CyclePhi <= CycleSched || OrigMI->isPHI()))
11768bcb0991SDimitry Andric         ReplaceReg = PrevReg;
11778bcb0991SDimitry Andric       else
11788bcb0991SDimitry Andric         ReplaceReg = NewReg;
11798bcb0991SDimitry Andric     }
11808bcb0991SDimitry Andric     // The scheduled instruction occurs before the scheduled Phi, and the
11818bcb0991SDimitry Andric     // Phi is not loop carried.
11828bcb0991SDimitry Andric     if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
11838bcb0991SDimitry Andric       ReplaceReg = NewReg;
11848bcb0991SDimitry Andric     if (StagePhi > StageSched && Phi->isPHI())
11858bcb0991SDimitry Andric       ReplaceReg = NewReg;
11868bcb0991SDimitry Andric     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
11878bcb0991SDimitry Andric       ReplaceReg = NewReg;
11888bcb0991SDimitry Andric     if (ReplaceReg) {
118981ad6265SDimitry Andric       const TargetRegisterClass *NRC =
11908bcb0991SDimitry Andric           MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
119181ad6265SDimitry Andric       if (NRC)
11928bcb0991SDimitry Andric         UseOp.setReg(ReplaceReg);
119381ad6265SDimitry Andric       else {
119481ad6265SDimitry Andric         Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
119581ad6265SDimitry Andric         BuildMI(*BB, UseMI, UseMI->getDebugLoc(), TII->get(TargetOpcode::COPY),
119681ad6265SDimitry Andric                 SplitReg)
119781ad6265SDimitry Andric             .addReg(ReplaceReg);
119881ad6265SDimitry Andric         UseOp.setReg(SplitReg);
119981ad6265SDimitry Andric       }
12008bcb0991SDimitry Andric     }
12018bcb0991SDimitry Andric   }
12028bcb0991SDimitry Andric }
12038bcb0991SDimitry Andric 
12048bcb0991SDimitry Andric bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
12058bcb0991SDimitry Andric   if (!Phi.isPHI())
12068bcb0991SDimitry Andric     return false;
1207480093f4SDimitry Andric   int DefCycle = Schedule.getCycle(&Phi);
12088bcb0991SDimitry Andric   int DefStage = Schedule.getStage(&Phi);
12098bcb0991SDimitry Andric 
12108bcb0991SDimitry Andric   unsigned InitVal = 0;
12118bcb0991SDimitry Andric   unsigned LoopVal = 0;
12128bcb0991SDimitry Andric   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
12138bcb0991SDimitry Andric   MachineInstr *Use = MRI.getVRegDef(LoopVal);
12148bcb0991SDimitry Andric   if (!Use || Use->isPHI())
12158bcb0991SDimitry Andric     return true;
1216480093f4SDimitry Andric   int LoopCycle = Schedule.getCycle(Use);
12178bcb0991SDimitry Andric   int LoopStage = Schedule.getStage(Use);
12188bcb0991SDimitry Andric   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
12198bcb0991SDimitry Andric }
12208bcb0991SDimitry Andric 
12218bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
12228bcb0991SDimitry Andric // PeelingModuloScheduleExpander implementation
12238bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
12248bcb0991SDimitry Andric // This is a reimplementation of ModuloScheduleExpander that works by creating
12258bcb0991SDimitry Andric // a fully correct steady-state kernel and peeling off the prolog and epilogs.
12268bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
12278bcb0991SDimitry Andric 
12288bcb0991SDimitry Andric namespace {
12298bcb0991SDimitry Andric // Remove any dead phis in MBB. Dead phis either have only one block as input
12308bcb0991SDimitry Andric // (in which case they are the identity) or have no uses.
12318bcb0991SDimitry Andric void EliminateDeadPhis(MachineBasicBlock *MBB, MachineRegisterInfo &MRI,
1232480093f4SDimitry Andric                        LiveIntervals *LIS, bool KeepSingleSrcPhi = false) {
12338bcb0991SDimitry Andric   bool Changed = true;
12348bcb0991SDimitry Andric   while (Changed) {
12358bcb0991SDimitry Andric     Changed = false;
1236349cc55cSDimitry Andric     for (MachineInstr &MI : llvm::make_early_inc_range(MBB->phis())) {
12378bcb0991SDimitry Andric       assert(MI.isPHI());
12388bcb0991SDimitry Andric       if (MRI.use_empty(MI.getOperand(0).getReg())) {
12398bcb0991SDimitry Andric         if (LIS)
12408bcb0991SDimitry Andric           LIS->RemoveMachineInstrFromMaps(MI);
12418bcb0991SDimitry Andric         MI.eraseFromParent();
12428bcb0991SDimitry Andric         Changed = true;
1243480093f4SDimitry Andric       } else if (!KeepSingleSrcPhi && MI.getNumExplicitOperands() == 3) {
124481ad6265SDimitry Andric         const TargetRegisterClass *ConstrainRegClass =
12458bcb0991SDimitry Andric             MRI.constrainRegClass(MI.getOperand(1).getReg(),
12468bcb0991SDimitry Andric                                   MRI.getRegClass(MI.getOperand(0).getReg()));
124781ad6265SDimitry Andric         assert(ConstrainRegClass &&
124881ad6265SDimitry Andric                "Expected a valid constrained register class!");
124981ad6265SDimitry Andric         (void)ConstrainRegClass;
12508bcb0991SDimitry Andric         MRI.replaceRegWith(MI.getOperand(0).getReg(),
12518bcb0991SDimitry Andric                            MI.getOperand(1).getReg());
12528bcb0991SDimitry Andric         if (LIS)
12538bcb0991SDimitry Andric           LIS->RemoveMachineInstrFromMaps(MI);
12548bcb0991SDimitry Andric         MI.eraseFromParent();
12558bcb0991SDimitry Andric         Changed = true;
12568bcb0991SDimitry Andric       }
12578bcb0991SDimitry Andric     }
12588bcb0991SDimitry Andric   }
12598bcb0991SDimitry Andric }
12608bcb0991SDimitry Andric 
12618bcb0991SDimitry Andric /// Rewrites the kernel block in-place to adhere to the given schedule.
12628bcb0991SDimitry Andric /// KernelRewriter holds all of the state required to perform the rewriting.
12638bcb0991SDimitry Andric class KernelRewriter {
12648bcb0991SDimitry Andric   ModuloSchedule &S;
12658bcb0991SDimitry Andric   MachineBasicBlock *BB;
12668bcb0991SDimitry Andric   MachineBasicBlock *PreheaderBB, *ExitBB;
12678bcb0991SDimitry Andric   MachineRegisterInfo &MRI;
12688bcb0991SDimitry Andric   const TargetInstrInfo *TII;
12698bcb0991SDimitry Andric   LiveIntervals *LIS;
12708bcb0991SDimitry Andric 
12718bcb0991SDimitry Andric   // Map from register class to canonical undef register for that class.
12728bcb0991SDimitry Andric   DenseMap<const TargetRegisterClass *, Register> Undefs;
12738bcb0991SDimitry Andric   // Map from <LoopReg, InitReg> to phi register for all created phis. Note that
12748bcb0991SDimitry Andric   // this map is only used when InitReg is non-undef.
12758bcb0991SDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, Register> Phis;
12768bcb0991SDimitry Andric   // Map from LoopReg to phi register where the InitReg is undef.
12778bcb0991SDimitry Andric   DenseMap<Register, Register> UndefPhis;
12788bcb0991SDimitry Andric 
12798bcb0991SDimitry Andric   // Reg is used by MI. Return the new register MI should use to adhere to the
12808bcb0991SDimitry Andric   // schedule. Insert phis as necessary.
12818bcb0991SDimitry Andric   Register remapUse(Register Reg, MachineInstr &MI);
12828bcb0991SDimitry Andric   // Insert a phi that carries LoopReg from the loop body and InitReg otherwise.
12838bcb0991SDimitry Andric   // If InitReg is not given it is chosen arbitrarily. It will either be undef
12848bcb0991SDimitry Andric   // or will be chosen so as to share another phi.
1285bdd1243dSDimitry Andric   Register phi(Register LoopReg, std::optional<Register> InitReg = {},
12868bcb0991SDimitry Andric                const TargetRegisterClass *RC = nullptr);
12878bcb0991SDimitry Andric   // Create an undef register of the given register class.
12888bcb0991SDimitry Andric   Register undef(const TargetRegisterClass *RC);
12898bcb0991SDimitry Andric 
12908bcb0991SDimitry Andric public:
1291fe6060f1SDimitry Andric   KernelRewriter(MachineLoop &L, ModuloSchedule &S, MachineBasicBlock *LoopBB,
12928bcb0991SDimitry Andric                  LiveIntervals *LIS = nullptr);
12938bcb0991SDimitry Andric   void rewrite();
12948bcb0991SDimitry Andric };
12958bcb0991SDimitry Andric } // namespace
12968bcb0991SDimitry Andric 
12978bcb0991SDimitry Andric KernelRewriter::KernelRewriter(MachineLoop &L, ModuloSchedule &S,
1298fe6060f1SDimitry Andric                                MachineBasicBlock *LoopBB, LiveIntervals *LIS)
1299fe6060f1SDimitry Andric     : S(S), BB(LoopBB), PreheaderBB(L.getLoopPreheader()),
13008bcb0991SDimitry Andric       ExitBB(L.getExitBlock()), MRI(BB->getParent()->getRegInfo()),
13018bcb0991SDimitry Andric       TII(BB->getParent()->getSubtarget().getInstrInfo()), LIS(LIS) {
13028bcb0991SDimitry Andric   PreheaderBB = *BB->pred_begin();
13038bcb0991SDimitry Andric   if (PreheaderBB == BB)
13048bcb0991SDimitry Andric     PreheaderBB = *std::next(BB->pred_begin());
13058bcb0991SDimitry Andric }
13068bcb0991SDimitry Andric 
13078bcb0991SDimitry Andric void KernelRewriter::rewrite() {
13088bcb0991SDimitry Andric   // Rearrange the loop to be in schedule order. Note that the schedule may
13098bcb0991SDimitry Andric   // contain instructions that are not owned by the loop block (InstrChanges and
13108bcb0991SDimitry Andric   // friends), so we gracefully handle unowned instructions and delete any
13118bcb0991SDimitry Andric   // instructions that weren't in the schedule.
13128bcb0991SDimitry Andric   auto InsertPt = BB->getFirstTerminator();
13138bcb0991SDimitry Andric   MachineInstr *FirstMI = nullptr;
13148bcb0991SDimitry Andric   for (MachineInstr *MI : S.getInstructions()) {
13158bcb0991SDimitry Andric     if (MI->isPHI())
13168bcb0991SDimitry Andric       continue;
13178bcb0991SDimitry Andric     if (MI->getParent())
13188bcb0991SDimitry Andric       MI->removeFromParent();
13198bcb0991SDimitry Andric     BB->insert(InsertPt, MI);
13208bcb0991SDimitry Andric     if (!FirstMI)
13218bcb0991SDimitry Andric       FirstMI = MI;
13228bcb0991SDimitry Andric   }
13238bcb0991SDimitry Andric   assert(FirstMI && "Failed to find first MI in schedule");
13248bcb0991SDimitry Andric 
13258bcb0991SDimitry Andric   // At this point all of the scheduled instructions are between FirstMI
13268bcb0991SDimitry Andric   // and the end of the block. Kill from the first non-phi to FirstMI.
13278bcb0991SDimitry Andric   for (auto I = BB->getFirstNonPHI(); I != FirstMI->getIterator();) {
13288bcb0991SDimitry Andric     if (LIS)
13298bcb0991SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*I);
13308bcb0991SDimitry Andric     (I++)->eraseFromParent();
13318bcb0991SDimitry Andric   }
13328bcb0991SDimitry Andric 
13338bcb0991SDimitry Andric   // Now remap every instruction in the loop.
13348bcb0991SDimitry Andric   for (MachineInstr &MI : *BB) {
13358bcb0991SDimitry Andric     if (MI.isPHI() || MI.isTerminator())
13368bcb0991SDimitry Andric       continue;
13378bcb0991SDimitry Andric     for (MachineOperand &MO : MI.uses()) {
13388bcb0991SDimitry Andric       if (!MO.isReg() || MO.getReg().isPhysical() || MO.isImplicit())
13398bcb0991SDimitry Andric         continue;
13408bcb0991SDimitry Andric       Register Reg = remapUse(MO.getReg(), MI);
13418bcb0991SDimitry Andric       MO.setReg(Reg);
13428bcb0991SDimitry Andric     }
13438bcb0991SDimitry Andric   }
13448bcb0991SDimitry Andric   EliminateDeadPhis(BB, MRI, LIS);
13458bcb0991SDimitry Andric 
13468bcb0991SDimitry Andric   // Ensure a phi exists for all instructions that are either referenced by
13478bcb0991SDimitry Andric   // an illegal phi or by an instruction outside the loop. This allows us to
13488bcb0991SDimitry Andric   // treat remaps of these values the same as "normal" values that come from
13498bcb0991SDimitry Andric   // loop-carried phis.
13508bcb0991SDimitry Andric   for (auto MI = BB->getFirstNonPHI(); MI != BB->end(); ++MI) {
13518bcb0991SDimitry Andric     if (MI->isPHI()) {
13528bcb0991SDimitry Andric       Register R = MI->getOperand(0).getReg();
13538bcb0991SDimitry Andric       phi(R);
13548bcb0991SDimitry Andric       continue;
13558bcb0991SDimitry Andric     }
13568bcb0991SDimitry Andric 
13578bcb0991SDimitry Andric     for (MachineOperand &Def : MI->defs()) {
13588bcb0991SDimitry Andric       for (MachineInstr &MI : MRI.use_instructions(Def.getReg())) {
13598bcb0991SDimitry Andric         if (MI.getParent() != BB) {
13608bcb0991SDimitry Andric           phi(Def.getReg());
13618bcb0991SDimitry Andric           break;
13628bcb0991SDimitry Andric         }
13638bcb0991SDimitry Andric       }
13648bcb0991SDimitry Andric     }
13658bcb0991SDimitry Andric   }
13668bcb0991SDimitry Andric }
13678bcb0991SDimitry Andric 
13688bcb0991SDimitry Andric Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
13698bcb0991SDimitry Andric   MachineInstr *Producer = MRI.getUniqueVRegDef(Reg);
13708bcb0991SDimitry Andric   if (!Producer)
13718bcb0991SDimitry Andric     return Reg;
13728bcb0991SDimitry Andric 
13738bcb0991SDimitry Andric   int ConsumerStage = S.getStage(&MI);
13748bcb0991SDimitry Andric   if (!Producer->isPHI()) {
13758bcb0991SDimitry Andric     // Non-phi producers are simple to remap. Insert as many phis as the
13768bcb0991SDimitry Andric     // difference between the consumer and producer stages.
13778bcb0991SDimitry Andric     if (Producer->getParent() != BB)
13788bcb0991SDimitry Andric       // Producer was not inside the loop. Use the register as-is.
13798bcb0991SDimitry Andric       return Reg;
13808bcb0991SDimitry Andric     int ProducerStage = S.getStage(Producer);
13818bcb0991SDimitry Andric     assert(ConsumerStage != -1 &&
13828bcb0991SDimitry Andric            "In-loop consumer should always be scheduled!");
13838bcb0991SDimitry Andric     assert(ConsumerStage >= ProducerStage);
13848bcb0991SDimitry Andric     unsigned StageDiff = ConsumerStage - ProducerStage;
13858bcb0991SDimitry Andric 
13868bcb0991SDimitry Andric     for (unsigned I = 0; I < StageDiff; ++I)
13878bcb0991SDimitry Andric       Reg = phi(Reg);
13888bcb0991SDimitry Andric     return Reg;
13898bcb0991SDimitry Andric   }
13908bcb0991SDimitry Andric 
13918bcb0991SDimitry Andric   // First, dive through the phi chain to find the defaults for the generated
13928bcb0991SDimitry Andric   // phis.
1393bdd1243dSDimitry Andric   SmallVector<std::optional<Register>, 4> Defaults;
13948bcb0991SDimitry Andric   Register LoopReg = Reg;
13958bcb0991SDimitry Andric   auto LoopProducer = Producer;
13968bcb0991SDimitry Andric   while (LoopProducer->isPHI() && LoopProducer->getParent() == BB) {
13978bcb0991SDimitry Andric     LoopReg = getLoopPhiReg(*LoopProducer, BB);
13988bcb0991SDimitry Andric     Defaults.emplace_back(getInitPhiReg(*LoopProducer, BB));
13998bcb0991SDimitry Andric     LoopProducer = MRI.getUniqueVRegDef(LoopReg);
14008bcb0991SDimitry Andric     assert(LoopProducer);
14018bcb0991SDimitry Andric   }
14028bcb0991SDimitry Andric   int LoopProducerStage = S.getStage(LoopProducer);
14038bcb0991SDimitry Andric 
1404bdd1243dSDimitry Andric   std::optional<Register> IllegalPhiDefault;
14058bcb0991SDimitry Andric 
14068bcb0991SDimitry Andric   if (LoopProducerStage == -1) {
14078bcb0991SDimitry Andric     // Do nothing.
14088bcb0991SDimitry Andric   } else if (LoopProducerStage > ConsumerStage) {
14098bcb0991SDimitry Andric     // This schedule is only representable if ProducerStage == ConsumerStage+1.
14108bcb0991SDimitry Andric     // In addition, Consumer's cycle must be scheduled after Producer in the
14118bcb0991SDimitry Andric     // rescheduled loop. This is enforced by the pipeliner's ASAP and ALAP
14128bcb0991SDimitry Andric     // functions.
14138bcb0991SDimitry Andric #ifndef NDEBUG // Silence unused variables in non-asserts mode.
14148bcb0991SDimitry Andric     int LoopProducerCycle = S.getCycle(LoopProducer);
14158bcb0991SDimitry Andric     int ConsumerCycle = S.getCycle(&MI);
14168bcb0991SDimitry Andric #endif
14178bcb0991SDimitry Andric     assert(LoopProducerCycle <= ConsumerCycle);
14188bcb0991SDimitry Andric     assert(LoopProducerStage == ConsumerStage + 1);
14198bcb0991SDimitry Andric     // Peel off the first phi from Defaults and insert a phi between producer
14208bcb0991SDimitry Andric     // and consumer. This phi will not be at the front of the block so we
14218bcb0991SDimitry Andric     // consider it illegal. It will only exist during the rewrite process; it
14228bcb0991SDimitry Andric     // needs to exist while we peel off prologs because these could take the
14238bcb0991SDimitry Andric     // default value. After that we can replace all uses with the loop producer
14248bcb0991SDimitry Andric     // value.
14258bcb0991SDimitry Andric     IllegalPhiDefault = Defaults.front();
14268bcb0991SDimitry Andric     Defaults.erase(Defaults.begin());
14278bcb0991SDimitry Andric   } else {
14288bcb0991SDimitry Andric     assert(ConsumerStage >= LoopProducerStage);
14298bcb0991SDimitry Andric     int StageDiff = ConsumerStage - LoopProducerStage;
14308bcb0991SDimitry Andric     if (StageDiff > 0) {
14318bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << " -- padding defaults array from " << Defaults.size()
14328bcb0991SDimitry Andric                         << " to " << (Defaults.size() + StageDiff) << "\n");
14338bcb0991SDimitry Andric       // If we need more phis than we have defaults for, pad out with undefs for
14348bcb0991SDimitry Andric       // the earliest phis, which are at the end of the defaults chain (the
14358bcb0991SDimitry Andric       // chain is in reverse order).
1436bdd1243dSDimitry Andric       Defaults.resize(Defaults.size() + StageDiff,
1437bdd1243dSDimitry Andric                       Defaults.empty() ? std::optional<Register>()
14388bcb0991SDimitry Andric                                        : Defaults.back());
14398bcb0991SDimitry Andric     }
14408bcb0991SDimitry Andric   }
14418bcb0991SDimitry Andric 
14428bcb0991SDimitry Andric   // Now we know the number of stages to jump back, insert the phi chain.
14438bcb0991SDimitry Andric   auto DefaultI = Defaults.rbegin();
14448bcb0991SDimitry Andric   while (DefaultI != Defaults.rend())
14458bcb0991SDimitry Andric     LoopReg = phi(LoopReg, *DefaultI++, MRI.getRegClass(Reg));
14468bcb0991SDimitry Andric 
144781ad6265SDimitry Andric   if (IllegalPhiDefault) {
14488bcb0991SDimitry Andric     // The consumer optionally consumes LoopProducer in the same iteration
14498bcb0991SDimitry Andric     // (because the producer is scheduled at an earlier cycle than the consumer)
14508bcb0991SDimitry Andric     // or the initial value. To facilitate this we create an illegal block here
14518bcb0991SDimitry Andric     // by embedding a phi in the middle of the block. We will fix this up
14528bcb0991SDimitry Andric     // immediately prior to pruning.
14538bcb0991SDimitry Andric     auto RC = MRI.getRegClass(Reg);
14548bcb0991SDimitry Andric     Register R = MRI.createVirtualRegister(RC);
14555ffd83dbSDimitry Andric     MachineInstr *IllegalPhi =
14568bcb0991SDimitry Andric         BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
145781ad6265SDimitry Andric             .addReg(*IllegalPhiDefault)
14588bcb0991SDimitry Andric             .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
14598bcb0991SDimitry Andric             .addReg(LoopReg)
14608bcb0991SDimitry Andric             .addMBB(BB); // Block choice is arbitrary and has no effect.
14615ffd83dbSDimitry Andric     // Illegal phi should belong to the producer stage so that it can be
14625ffd83dbSDimitry Andric     // filtered correctly during peeling.
14635ffd83dbSDimitry Andric     S.setStage(IllegalPhi, LoopProducerStage);
14648bcb0991SDimitry Andric     return R;
14658bcb0991SDimitry Andric   }
14668bcb0991SDimitry Andric 
14678bcb0991SDimitry Andric   return LoopReg;
14688bcb0991SDimitry Andric }
14698bcb0991SDimitry Andric 
1470bdd1243dSDimitry Andric Register KernelRewriter::phi(Register LoopReg, std::optional<Register> InitReg,
14718bcb0991SDimitry Andric                              const TargetRegisterClass *RC) {
14728bcb0991SDimitry Andric   // If the init register is not undef, try and find an existing phi.
147381ad6265SDimitry Andric   if (InitReg) {
1474bdd1243dSDimitry Andric     auto I = Phis.find({LoopReg, *InitReg});
14758bcb0991SDimitry Andric     if (I != Phis.end())
14768bcb0991SDimitry Andric       return I->second;
14778bcb0991SDimitry Andric   } else {
14788bcb0991SDimitry Andric     for (auto &KV : Phis) {
14798bcb0991SDimitry Andric       if (KV.first.first == LoopReg)
14808bcb0991SDimitry Andric         return KV.second;
14818bcb0991SDimitry Andric     }
14828bcb0991SDimitry Andric   }
14838bcb0991SDimitry Andric 
14848bcb0991SDimitry Andric   // InitReg is either undef or no existing phi takes InitReg as input. Try and
14858bcb0991SDimitry Andric   // find a phi that takes undef as input.
14868bcb0991SDimitry Andric   auto I = UndefPhis.find(LoopReg);
14878bcb0991SDimitry Andric   if (I != UndefPhis.end()) {
14888bcb0991SDimitry Andric     Register R = I->second;
148981ad6265SDimitry Andric     if (!InitReg)
14908bcb0991SDimitry Andric       // Found a phi taking undef as input, and this input is undef so return
14918bcb0991SDimitry Andric       // without any more changes.
14928bcb0991SDimitry Andric       return R;
14938bcb0991SDimitry Andric     // Found a phi taking undef as input, so rewrite it to take InitReg.
14948bcb0991SDimitry Andric     MachineInstr *MI = MRI.getVRegDef(R);
1495bdd1243dSDimitry Andric     MI->getOperand(1).setReg(*InitReg);
1496bdd1243dSDimitry Andric     Phis.insert({{LoopReg, *InitReg}, R});
149781ad6265SDimitry Andric     const TargetRegisterClass *ConstrainRegClass =
1498bdd1243dSDimitry Andric         MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
149981ad6265SDimitry Andric     assert(ConstrainRegClass && "Expected a valid constrained register class!");
150081ad6265SDimitry Andric     (void)ConstrainRegClass;
15018bcb0991SDimitry Andric     UndefPhis.erase(I);
15028bcb0991SDimitry Andric     return R;
15038bcb0991SDimitry Andric   }
15048bcb0991SDimitry Andric 
15058bcb0991SDimitry Andric   // Failed to find any existing phi to reuse, so create a new one.
15068bcb0991SDimitry Andric   if (!RC)
15078bcb0991SDimitry Andric     RC = MRI.getRegClass(LoopReg);
15088bcb0991SDimitry Andric   Register R = MRI.createVirtualRegister(RC);
150981ad6265SDimitry Andric   if (InitReg) {
151081ad6265SDimitry Andric     const TargetRegisterClass *ConstrainRegClass =
15118bcb0991SDimitry Andric         MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
151281ad6265SDimitry Andric     assert(ConstrainRegClass && "Expected a valid constrained register class!");
151381ad6265SDimitry Andric     (void)ConstrainRegClass;
151481ad6265SDimitry Andric   }
15158bcb0991SDimitry Andric   BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
151681ad6265SDimitry Andric       .addReg(InitReg ? *InitReg : undef(RC))
15178bcb0991SDimitry Andric       .addMBB(PreheaderBB)
15188bcb0991SDimitry Andric       .addReg(LoopReg)
15198bcb0991SDimitry Andric       .addMBB(BB);
152081ad6265SDimitry Andric   if (!InitReg)
15218bcb0991SDimitry Andric     UndefPhis[LoopReg] = R;
15228bcb0991SDimitry Andric   else
15238bcb0991SDimitry Andric     Phis[{LoopReg, *InitReg}] = R;
15248bcb0991SDimitry Andric   return R;
15258bcb0991SDimitry Andric }
15268bcb0991SDimitry Andric 
15278bcb0991SDimitry Andric Register KernelRewriter::undef(const TargetRegisterClass *RC) {
15288bcb0991SDimitry Andric   Register &R = Undefs[RC];
15298bcb0991SDimitry Andric   if (R == 0) {
15308bcb0991SDimitry Andric     // Create an IMPLICIT_DEF that defines this register if we need it.
15318bcb0991SDimitry Andric     // All uses of this should be removed by the time we have finished unrolling
15328bcb0991SDimitry Andric     // prologs and epilogs.
15338bcb0991SDimitry Andric     R = MRI.createVirtualRegister(RC);
15348bcb0991SDimitry Andric     auto *InsertBB = &PreheaderBB->getParent()->front();
15358bcb0991SDimitry Andric     BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
15368bcb0991SDimitry Andric             TII->get(TargetOpcode::IMPLICIT_DEF), R);
15378bcb0991SDimitry Andric   }
15388bcb0991SDimitry Andric   return R;
15398bcb0991SDimitry Andric }
15408bcb0991SDimitry Andric 
15418bcb0991SDimitry Andric namespace {
15428bcb0991SDimitry Andric /// Describes an operand in the kernel of a pipelined loop. Characteristics of
15438bcb0991SDimitry Andric /// the operand are discovered, such as how many in-loop PHIs it has to jump
15448bcb0991SDimitry Andric /// through and defaults for these phis.
15458bcb0991SDimitry Andric class KernelOperandInfo {
15468bcb0991SDimitry Andric   MachineBasicBlock *BB;
15478bcb0991SDimitry Andric   MachineRegisterInfo &MRI;
15488bcb0991SDimitry Andric   SmallVector<Register, 4> PhiDefaults;
15498bcb0991SDimitry Andric   MachineOperand *Source;
15508bcb0991SDimitry Andric   MachineOperand *Target;
15518bcb0991SDimitry Andric 
15528bcb0991SDimitry Andric public:
15538bcb0991SDimitry Andric   KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
15548bcb0991SDimitry Andric                     const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
15558bcb0991SDimitry Andric       : MRI(MRI) {
15568bcb0991SDimitry Andric     Source = MO;
15578bcb0991SDimitry Andric     BB = MO->getParent()->getParent();
15588bcb0991SDimitry Andric     while (isRegInLoop(MO)) {
15598bcb0991SDimitry Andric       MachineInstr *MI = MRI.getVRegDef(MO->getReg());
15608bcb0991SDimitry Andric       if (MI->isFullCopy()) {
15618bcb0991SDimitry Andric         MO = &MI->getOperand(1);
15628bcb0991SDimitry Andric         continue;
15638bcb0991SDimitry Andric       }
15648bcb0991SDimitry Andric       if (!MI->isPHI())
15658bcb0991SDimitry Andric         break;
15668bcb0991SDimitry Andric       // If this is an illegal phi, don't count it in distance.
15678bcb0991SDimitry Andric       if (IllegalPhis.count(MI)) {
15688bcb0991SDimitry Andric         MO = &MI->getOperand(3);
15698bcb0991SDimitry Andric         continue;
15708bcb0991SDimitry Andric       }
15718bcb0991SDimitry Andric 
15728bcb0991SDimitry Andric       Register Default = getInitPhiReg(*MI, BB);
15738bcb0991SDimitry Andric       MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
15748bcb0991SDimitry Andric                                             : &MI->getOperand(3);
15758bcb0991SDimitry Andric       PhiDefaults.push_back(Default);
15768bcb0991SDimitry Andric     }
15778bcb0991SDimitry Andric     Target = MO;
15788bcb0991SDimitry Andric   }
15798bcb0991SDimitry Andric 
15808bcb0991SDimitry Andric   bool operator==(const KernelOperandInfo &Other) const {
15818bcb0991SDimitry Andric     return PhiDefaults.size() == Other.PhiDefaults.size();
15828bcb0991SDimitry Andric   }
15838bcb0991SDimitry Andric 
15848bcb0991SDimitry Andric   void print(raw_ostream &OS) const {
15858bcb0991SDimitry Andric     OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
15868bcb0991SDimitry Andric        << *Source->getParent();
15878bcb0991SDimitry Andric   }
15888bcb0991SDimitry Andric 
15898bcb0991SDimitry Andric private:
15908bcb0991SDimitry Andric   bool isRegInLoop(MachineOperand *MO) {
15918bcb0991SDimitry Andric     return MO->isReg() && MO->getReg().isVirtual() &&
15928bcb0991SDimitry Andric            MRI.getVRegDef(MO->getReg())->getParent() == BB;
15938bcb0991SDimitry Andric   }
15948bcb0991SDimitry Andric };
15958bcb0991SDimitry Andric } // namespace
15968bcb0991SDimitry Andric 
15978bcb0991SDimitry Andric MachineBasicBlock *
15988bcb0991SDimitry Andric PeelingModuloScheduleExpander::peelKernel(LoopPeelDirection LPD) {
15998bcb0991SDimitry Andric   MachineBasicBlock *NewBB = PeelSingleBlockLoop(LPD, BB, MRI, TII);
16008bcb0991SDimitry Andric   if (LPD == LPD_Front)
16018bcb0991SDimitry Andric     PeeledFront.push_back(NewBB);
16028bcb0991SDimitry Andric   else
16038bcb0991SDimitry Andric     PeeledBack.push_front(NewBB);
16048bcb0991SDimitry Andric   for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
16058bcb0991SDimitry Andric        ++I, ++NI) {
16068bcb0991SDimitry Andric     CanonicalMIs[&*I] = &*I;
16078bcb0991SDimitry Andric     CanonicalMIs[&*NI] = &*I;
16088bcb0991SDimitry Andric     BlockMIs[{NewBB, &*I}] = &*NI;
16098bcb0991SDimitry Andric     BlockMIs[{BB, &*I}] = &*I;
16108bcb0991SDimitry Andric   }
16118bcb0991SDimitry Andric   return NewBB;
16128bcb0991SDimitry Andric }
16138bcb0991SDimitry Andric 
1614480093f4SDimitry Andric void PeelingModuloScheduleExpander::filterInstructions(MachineBasicBlock *MB,
1615480093f4SDimitry Andric                                                        int MinStage) {
1616480093f4SDimitry Andric   for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
1617480093f4SDimitry Andric        I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
1618480093f4SDimitry Andric     MachineInstr *MI = &*I++;
1619480093f4SDimitry Andric     int Stage = getStage(MI);
1620480093f4SDimitry Andric     if (Stage == -1 || Stage >= MinStage)
1621480093f4SDimitry Andric       continue;
1622480093f4SDimitry Andric 
1623480093f4SDimitry Andric     for (MachineOperand &DefMO : MI->defs()) {
1624480093f4SDimitry Andric       SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1625480093f4SDimitry Andric       for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1626480093f4SDimitry Andric         // Only PHIs can use values from this block by construction.
1627480093f4SDimitry Andric         // Match with the equivalent PHI in B.
1628480093f4SDimitry Andric         assert(UseMI.isPHI());
1629480093f4SDimitry Andric         Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1630480093f4SDimitry Andric                                                MI->getParent());
1631480093f4SDimitry Andric         Subs.emplace_back(&UseMI, Reg);
1632480093f4SDimitry Andric       }
1633480093f4SDimitry Andric       for (auto &Sub : Subs)
1634480093f4SDimitry Andric         Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1635480093f4SDimitry Andric                                       *MRI.getTargetRegisterInfo());
1636480093f4SDimitry Andric     }
1637480093f4SDimitry Andric     if (LIS)
1638480093f4SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*MI);
1639480093f4SDimitry Andric     MI->eraseFromParent();
1640480093f4SDimitry Andric   }
1641480093f4SDimitry Andric }
1642480093f4SDimitry Andric 
1643480093f4SDimitry Andric void PeelingModuloScheduleExpander::moveStageBetweenBlocks(
1644480093f4SDimitry Andric     MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
1645480093f4SDimitry Andric   auto InsertPt = DestBB->getFirstNonPHI();
1646480093f4SDimitry Andric   DenseMap<Register, Register> Remaps;
1647349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(
1648349cc55cSDimitry Andric            llvm::make_range(SourceBB->getFirstNonPHI(), SourceBB->end()))) {
1649349cc55cSDimitry Andric     if (MI.isPHI()) {
1650480093f4SDimitry Andric       // This is an illegal PHI. If we move any instructions using an illegal
16515ffd83dbSDimitry Andric       // PHI, we need to create a legal Phi.
1652349cc55cSDimitry Andric       if (getStage(&MI) != Stage) {
16535ffd83dbSDimitry Andric         // The legal Phi is not necessary if the illegal phi's stage
16545ffd83dbSDimitry Andric         // is being moved.
1655349cc55cSDimitry Andric         Register PhiR = MI.getOperand(0).getReg();
1656480093f4SDimitry Andric         auto RC = MRI.getRegClass(PhiR);
1657480093f4SDimitry Andric         Register NR = MRI.createVirtualRegister(RC);
16585ffd83dbSDimitry Andric         MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(),
16595ffd83dbSDimitry Andric                                    DebugLoc(), TII->get(TargetOpcode::PHI), NR)
1660480093f4SDimitry Andric                                .addReg(PhiR)
1661480093f4SDimitry Andric                                .addMBB(SourceBB);
1662349cc55cSDimitry Andric         BlockMIs[{DestBB, CanonicalMIs[&MI]}] = NI;
1663349cc55cSDimitry Andric         CanonicalMIs[NI] = CanonicalMIs[&MI];
1664480093f4SDimitry Andric         Remaps[PhiR] = NR;
16655ffd83dbSDimitry Andric       }
1666480093f4SDimitry Andric     }
1667349cc55cSDimitry Andric     if (getStage(&MI) != Stage)
1668480093f4SDimitry Andric       continue;
1669349cc55cSDimitry Andric     MI.removeFromParent();
1670349cc55cSDimitry Andric     DestBB->insert(InsertPt, &MI);
1671349cc55cSDimitry Andric     auto *KernelMI = CanonicalMIs[&MI];
1672349cc55cSDimitry Andric     BlockMIs[{DestBB, KernelMI}] = &MI;
1673480093f4SDimitry Andric     BlockMIs.erase({SourceBB, KernelMI});
1674480093f4SDimitry Andric   }
1675480093f4SDimitry Andric   SmallVector<MachineInstr *, 4> PhiToDelete;
1676480093f4SDimitry Andric   for (MachineInstr &MI : DestBB->phis()) {
1677480093f4SDimitry Andric     assert(MI.getNumOperands() == 3);
1678480093f4SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
1679480093f4SDimitry Andric     // If the instruction referenced by the phi is moved inside the block
1680480093f4SDimitry Andric     // we don't need the phi anymore.
1681480093f4SDimitry Andric     if (getStage(Def) == Stage) {
1682480093f4SDimitry Andric       Register PhiReg = MI.getOperand(0).getReg();
16830fca6ea1SDimitry Andric       assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg(),
16840fca6ea1SDimitry Andric                                             /*TRI=*/nullptr) != -1);
16855ffd83dbSDimitry Andric       MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
1686480093f4SDimitry Andric       MI.getOperand(0).setReg(PhiReg);
1687480093f4SDimitry Andric       PhiToDelete.push_back(&MI);
1688480093f4SDimitry Andric     }
1689480093f4SDimitry Andric   }
1690480093f4SDimitry Andric   for (auto *P : PhiToDelete)
1691480093f4SDimitry Andric     P->eraseFromParent();
1692480093f4SDimitry Andric   InsertPt = DestBB->getFirstNonPHI();
1693480093f4SDimitry Andric   // Helper to clone Phi instructions into the destination block. We clone Phi
1694480093f4SDimitry Andric   // greedily to avoid combinatorial explosion of Phi instructions.
1695480093f4SDimitry Andric   auto clonePhi = [&](MachineInstr *Phi) {
1696480093f4SDimitry Andric     MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
1697480093f4SDimitry Andric     DestBB->insert(InsertPt, NewMI);
1698480093f4SDimitry Andric     Register OrigR = Phi->getOperand(0).getReg();
1699480093f4SDimitry Andric     Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
1700480093f4SDimitry Andric     NewMI->getOperand(0).setReg(R);
1701480093f4SDimitry Andric     NewMI->getOperand(1).setReg(OrigR);
1702480093f4SDimitry Andric     NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
1703480093f4SDimitry Andric     Remaps[OrigR] = R;
1704480093f4SDimitry Andric     CanonicalMIs[NewMI] = CanonicalMIs[Phi];
1705480093f4SDimitry Andric     BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
1706480093f4SDimitry Andric     PhiNodeLoopIteration[NewMI] = PhiNodeLoopIteration[Phi];
1707480093f4SDimitry Andric     return R;
1708480093f4SDimitry Andric   };
1709480093f4SDimitry Andric   for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
1710480093f4SDimitry Andric     for (MachineOperand &MO : I->uses()) {
1711480093f4SDimitry Andric       if (!MO.isReg())
1712480093f4SDimitry Andric         continue;
1713480093f4SDimitry Andric       if (Remaps.count(MO.getReg()))
1714480093f4SDimitry Andric         MO.setReg(Remaps[MO.getReg()]);
1715480093f4SDimitry Andric       else {
1716480093f4SDimitry Andric         // If we are using a phi from the source block we need to add a new phi
1717480093f4SDimitry Andric         // pointing to the old one.
1718480093f4SDimitry Andric         MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
1719480093f4SDimitry Andric         if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
1720480093f4SDimitry Andric           Register R = clonePhi(Use);
1721480093f4SDimitry Andric           MO.setReg(R);
1722480093f4SDimitry Andric         }
1723480093f4SDimitry Andric       }
1724480093f4SDimitry Andric     }
1725480093f4SDimitry Andric   }
1726480093f4SDimitry Andric }
1727480093f4SDimitry Andric 
1728480093f4SDimitry Andric Register
1729480093f4SDimitry Andric PeelingModuloScheduleExpander::getPhiCanonicalReg(MachineInstr *CanonicalPhi,
1730480093f4SDimitry Andric                                                   MachineInstr *Phi) {
1731480093f4SDimitry Andric   unsigned distance = PhiNodeLoopIteration[Phi];
1732480093f4SDimitry Andric   MachineInstr *CanonicalUse = CanonicalPhi;
17335ffd83dbSDimitry Andric   Register CanonicalUseReg = CanonicalUse->getOperand(0).getReg();
1734480093f4SDimitry Andric   for (unsigned I = 0; I < distance; ++I) {
1735480093f4SDimitry Andric     assert(CanonicalUse->isPHI());
1736480093f4SDimitry Andric     assert(CanonicalUse->getNumOperands() == 5);
1737480093f4SDimitry Andric     unsigned LoopRegIdx = 3, InitRegIdx = 1;
1738480093f4SDimitry Andric     if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
1739480093f4SDimitry Andric       std::swap(LoopRegIdx, InitRegIdx);
17405ffd83dbSDimitry Andric     CanonicalUseReg = CanonicalUse->getOperand(LoopRegIdx).getReg();
17415ffd83dbSDimitry Andric     CanonicalUse = MRI.getVRegDef(CanonicalUseReg);
1742480093f4SDimitry Andric   }
17435ffd83dbSDimitry Andric   return CanonicalUseReg;
1744480093f4SDimitry Andric }
1745480093f4SDimitry Andric 
17468bcb0991SDimitry Andric void PeelingModuloScheduleExpander::peelPrologAndEpilogs() {
17478bcb0991SDimitry Andric   BitVector LS(Schedule.getNumStages(), true);
17488bcb0991SDimitry Andric   BitVector AS(Schedule.getNumStages(), true);
17498bcb0991SDimitry Andric   LiveStages[BB] = LS;
17508bcb0991SDimitry Andric   AvailableStages[BB] = AS;
17518bcb0991SDimitry Andric 
17528bcb0991SDimitry Andric   // Peel out the prologs.
17538bcb0991SDimitry Andric   LS.reset();
17548bcb0991SDimitry Andric   for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
175504eeddc0SDimitry Andric     LS[I] = true;
17568bcb0991SDimitry Andric     Prologs.push_back(peelKernel(LPD_Front));
17578bcb0991SDimitry Andric     LiveStages[Prologs.back()] = LS;
17588bcb0991SDimitry Andric     AvailableStages[Prologs.back()] = LS;
17598bcb0991SDimitry Andric   }
17608bcb0991SDimitry Andric 
17618bcb0991SDimitry Andric   // Create a block that will end up as the new loop exiting block (dominated by
17628bcb0991SDimitry Andric   // all prologs and epilogs). It will only contain PHIs, in the same order as
17638bcb0991SDimitry Andric   // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
17648bcb0991SDimitry Andric   // that the exiting block is a (sub) clone of BB. This in turn gives us the
17658bcb0991SDimitry Andric   // property that any value deffed in BB but used outside of BB is used by a
17668bcb0991SDimitry Andric   // PHI in the exiting block.
17678bcb0991SDimitry Andric   MachineBasicBlock *ExitingBB = CreateLCSSAExitingBlock();
1768480093f4SDimitry Andric   EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
17698bcb0991SDimitry Andric   // Push out the epilogs, again in reverse order.
17708bcb0991SDimitry Andric   // We can't assume anything about the minumum loop trip count at this point,
1771480093f4SDimitry Andric   // so emit a fairly complex epilog.
1772480093f4SDimitry Andric 
1773480093f4SDimitry Andric   // We first peel number of stages minus one epilogue. Then we remove dead
1774480093f4SDimitry Andric   // stages and reorder instructions based on their stage. If we have 3 stages
1775480093f4SDimitry Andric   // we generate first:
1776480093f4SDimitry Andric   // E0[3, 2, 1]
1777480093f4SDimitry Andric   // E1[3', 2']
1778480093f4SDimitry Andric   // E2[3'']
1779480093f4SDimitry Andric   // And then we move instructions based on their stages to have:
1780480093f4SDimitry Andric   // E0[3]
1781480093f4SDimitry Andric   // E1[2, 3']
1782480093f4SDimitry Andric   // E2[1, 2', 3'']
1783480093f4SDimitry Andric   // The transformation is legal because we only move instructions past
1784480093f4SDimitry Andric   // instructions of a previous loop iteration.
17858bcb0991SDimitry Andric   for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
1786480093f4SDimitry Andric     Epilogs.push_back(peelKernel(LPD_Back));
1787480093f4SDimitry Andric     MachineBasicBlock *B = Epilogs.back();
1788480093f4SDimitry Andric     filterInstructions(B, Schedule.getNumStages() - I);
1789480093f4SDimitry Andric     // Keep track at which iteration each phi belongs to. We need it to know
1790480093f4SDimitry Andric     // what version of the variable to use during prologue/epilogue stitching.
1791480093f4SDimitry Andric     EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1792349cc55cSDimitry Andric     for (MachineInstr &Phi : B->phis())
1793349cc55cSDimitry Andric       PhiNodeLoopIteration[&Phi] = Schedule.getNumStages() - I;
17948bcb0991SDimitry Andric   }
1795480093f4SDimitry Andric   for (size_t I = 0; I < Epilogs.size(); I++) {
1796480093f4SDimitry Andric     LS.reset();
1797480093f4SDimitry Andric     for (size_t J = I; J < Epilogs.size(); J++) {
1798480093f4SDimitry Andric       int Iteration = J;
1799480093f4SDimitry Andric       unsigned Stage = Schedule.getNumStages() - 1 + I - J;
1800480093f4SDimitry Andric       // Move stage one block at a time so that Phi nodes are updated correctly.
1801480093f4SDimitry Andric       for (size_t K = Iteration; K > I; K--)
1802480093f4SDimitry Andric         moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
180304eeddc0SDimitry Andric       LS[Stage] = true;
1804480093f4SDimitry Andric     }
1805480093f4SDimitry Andric     LiveStages[Epilogs[I]] = LS;
1806480093f4SDimitry Andric     AvailableStages[Epilogs[I]] = AS;
18078bcb0991SDimitry Andric   }
18088bcb0991SDimitry Andric 
18098bcb0991SDimitry Andric   // Now we've defined all the prolog and epilog blocks as a fallthrough
18108bcb0991SDimitry Andric   // sequence, add the edges that will be followed if the loop trip count is
18118bcb0991SDimitry Andric   // lower than the number of stages (connecting prologs directly with epilogs).
18128bcb0991SDimitry Andric   auto PI = Prologs.begin();
18138bcb0991SDimitry Andric   auto EI = Epilogs.begin();
18148bcb0991SDimitry Andric   assert(Prologs.size() == Epilogs.size());
18158bcb0991SDimitry Andric   for (; PI != Prologs.end(); ++PI, ++EI) {
18168bcb0991SDimitry Andric     MachineBasicBlock *Pred = *(*EI)->pred_begin();
18178bcb0991SDimitry Andric     (*PI)->addSuccessor(*EI);
18188bcb0991SDimitry Andric     for (MachineInstr &MI : (*EI)->phis()) {
18198bcb0991SDimitry Andric       Register Reg = MI.getOperand(1).getReg();
18208bcb0991SDimitry Andric       MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
1821480093f4SDimitry Andric       if (Use && Use->getParent() == Pred) {
1822480093f4SDimitry Andric         MachineInstr *CanonicalUse = CanonicalMIs[Use];
1823480093f4SDimitry Andric         if (CanonicalUse->isPHI()) {
1824480093f4SDimitry Andric           // If the use comes from a phi we need to skip as many phi as the
1825480093f4SDimitry Andric           // distance between the epilogue and the kernel. Trace through the phi
1826480093f4SDimitry Andric           // chain to find the right value.
1827480093f4SDimitry Andric           Reg = getPhiCanonicalReg(CanonicalUse, Use);
1828480093f4SDimitry Andric         }
18298bcb0991SDimitry Andric         Reg = getEquivalentRegisterIn(Reg, *PI);
1830480093f4SDimitry Andric       }
18318bcb0991SDimitry Andric       MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
18328bcb0991SDimitry Andric       MI.addOperand(MachineOperand::CreateMBB(*PI));
18338bcb0991SDimitry Andric     }
18348bcb0991SDimitry Andric   }
18358bcb0991SDimitry Andric 
18368bcb0991SDimitry Andric   // Create a list of all blocks in order.
18378bcb0991SDimitry Andric   SmallVector<MachineBasicBlock *, 8> Blocks;
18388bcb0991SDimitry Andric   llvm::copy(PeeledFront, std::back_inserter(Blocks));
18398bcb0991SDimitry Andric   Blocks.push_back(BB);
18408bcb0991SDimitry Andric   llvm::copy(PeeledBack, std::back_inserter(Blocks));
18418bcb0991SDimitry Andric 
18428bcb0991SDimitry Andric   // Iterate in reverse order over all instructions, remapping as we go.
18438bcb0991SDimitry Andric   for (MachineBasicBlock *B : reverse(Blocks)) {
184481ad6265SDimitry Andric     for (auto I = B->instr_rbegin();
18458bcb0991SDimitry Andric          I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
184681ad6265SDimitry Andric       MachineBasicBlock::reverse_instr_iterator MI = I++;
184781ad6265SDimitry Andric       rewriteUsesOf(&*MI);
18488bcb0991SDimitry Andric     }
18498bcb0991SDimitry Andric   }
1850480093f4SDimitry Andric   for (auto *MI : IllegalPhisToDelete) {
1851480093f4SDimitry Andric     if (LIS)
1852480093f4SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*MI);
1853480093f4SDimitry Andric     MI->eraseFromParent();
1854480093f4SDimitry Andric   }
1855480093f4SDimitry Andric   IllegalPhisToDelete.clear();
1856480093f4SDimitry Andric 
18578bcb0991SDimitry Andric   // Now all remapping has been done, we're free to optimize the generated code.
18588bcb0991SDimitry Andric   for (MachineBasicBlock *B : reverse(Blocks))
18598bcb0991SDimitry Andric     EliminateDeadPhis(B, MRI, LIS);
18608bcb0991SDimitry Andric   EliminateDeadPhis(ExitingBB, MRI, LIS);
18618bcb0991SDimitry Andric }
18628bcb0991SDimitry Andric 
18638bcb0991SDimitry Andric MachineBasicBlock *PeelingModuloScheduleExpander::CreateLCSSAExitingBlock() {
18648bcb0991SDimitry Andric   MachineFunction &MF = *BB->getParent();
18658bcb0991SDimitry Andric   MachineBasicBlock *Exit = *BB->succ_begin();
18668bcb0991SDimitry Andric   if (Exit == BB)
18678bcb0991SDimitry Andric     Exit = *std::next(BB->succ_begin());
18688bcb0991SDimitry Andric 
18698bcb0991SDimitry Andric   MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
18708bcb0991SDimitry Andric   MF.insert(std::next(BB->getIterator()), NewBB);
18718bcb0991SDimitry Andric 
18728bcb0991SDimitry Andric   // Clone all phis in BB into NewBB and rewrite.
18738bcb0991SDimitry Andric   for (MachineInstr &MI : BB->phis()) {
18748bcb0991SDimitry Andric     auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
18758bcb0991SDimitry Andric     Register OldR = MI.getOperand(3).getReg();
18768bcb0991SDimitry Andric     Register R = MRI.createVirtualRegister(RC);
18778bcb0991SDimitry Andric     SmallVector<MachineInstr *, 4> Uses;
18788bcb0991SDimitry Andric     for (MachineInstr &Use : MRI.use_instructions(OldR))
18798bcb0991SDimitry Andric       if (Use.getParent() != BB)
18808bcb0991SDimitry Andric         Uses.push_back(&Use);
18818bcb0991SDimitry Andric     for (MachineInstr *Use : Uses)
18828bcb0991SDimitry Andric       Use->substituteRegister(OldR, R, /*SubIdx=*/0,
18838bcb0991SDimitry Andric                               *MRI.getTargetRegisterInfo());
18848bcb0991SDimitry Andric     MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
18858bcb0991SDimitry Andric         .addReg(OldR)
18868bcb0991SDimitry Andric         .addMBB(BB);
18878bcb0991SDimitry Andric     BlockMIs[{NewBB, &MI}] = NI;
18888bcb0991SDimitry Andric     CanonicalMIs[NI] = &MI;
18898bcb0991SDimitry Andric   }
18908bcb0991SDimitry Andric   BB->replaceSuccessor(Exit, NewBB);
18918bcb0991SDimitry Andric   Exit->replacePhiUsesWith(BB, NewBB);
18928bcb0991SDimitry Andric   NewBB->addSuccessor(Exit);
18938bcb0991SDimitry Andric 
18948bcb0991SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
18958bcb0991SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
18968bcb0991SDimitry Andric   bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
18978bcb0991SDimitry Andric   (void)CanAnalyzeBr;
18988bcb0991SDimitry Andric   assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
18998bcb0991SDimitry Andric   TII->removeBranch(*BB);
19008bcb0991SDimitry Andric   TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
19018bcb0991SDimitry Andric                     Cond, DebugLoc());
19028bcb0991SDimitry Andric   TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
19038bcb0991SDimitry Andric   return NewBB;
19048bcb0991SDimitry Andric }
19058bcb0991SDimitry Andric 
19068bcb0991SDimitry Andric Register
19078bcb0991SDimitry Andric PeelingModuloScheduleExpander::getEquivalentRegisterIn(Register Reg,
19088bcb0991SDimitry Andric                                                        MachineBasicBlock *BB) {
19098bcb0991SDimitry Andric   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
19100fca6ea1SDimitry Andric   unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
19118bcb0991SDimitry Andric   return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
19128bcb0991SDimitry Andric }
19138bcb0991SDimitry Andric 
19148bcb0991SDimitry Andric void PeelingModuloScheduleExpander::rewriteUsesOf(MachineInstr *MI) {
19158bcb0991SDimitry Andric   if (MI->isPHI()) {
19168bcb0991SDimitry Andric     // This is an illegal PHI. The loop-carried (desired) value is operand 3,
19178bcb0991SDimitry Andric     // and it is produced by this block.
19188bcb0991SDimitry Andric     Register PhiR = MI->getOperand(0).getReg();
19198bcb0991SDimitry Andric     Register R = MI->getOperand(3).getReg();
19208bcb0991SDimitry Andric     int RMIStage = getStage(MRI.getUniqueVRegDef(R));
19218bcb0991SDimitry Andric     if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
19228bcb0991SDimitry Andric       R = MI->getOperand(1).getReg();
19238bcb0991SDimitry Andric     MRI.setRegClass(R, MRI.getRegClass(PhiR));
19248bcb0991SDimitry Andric     MRI.replaceRegWith(PhiR, R);
1925480093f4SDimitry Andric     // Postpone deleting the Phi as it may be referenced by BlockMIs and used
1926480093f4SDimitry Andric     // later to figure out how to remap registers.
1927480093f4SDimitry Andric     MI->getOperand(0).setReg(PhiR);
1928480093f4SDimitry Andric     IllegalPhisToDelete.push_back(MI);
19298bcb0991SDimitry Andric     return;
19308bcb0991SDimitry Andric   }
19318bcb0991SDimitry Andric 
19328bcb0991SDimitry Andric   int Stage = getStage(MI);
19338bcb0991SDimitry Andric   if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
19348bcb0991SDimitry Andric       LiveStages[MI->getParent()].test(Stage))
19358bcb0991SDimitry Andric     // Instruction is live, no rewriting to do.
19368bcb0991SDimitry Andric     return;
19378bcb0991SDimitry Andric 
19388bcb0991SDimitry Andric   for (MachineOperand &DefMO : MI->defs()) {
19398bcb0991SDimitry Andric     SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
19408bcb0991SDimitry Andric     for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
19418bcb0991SDimitry Andric       // Only PHIs can use values from this block by construction.
19428bcb0991SDimitry Andric       // Match with the equivalent PHI in B.
19438bcb0991SDimitry Andric       assert(UseMI.isPHI());
19448bcb0991SDimitry Andric       Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
19458bcb0991SDimitry Andric                                              MI->getParent());
19468bcb0991SDimitry Andric       Subs.emplace_back(&UseMI, Reg);
19478bcb0991SDimitry Andric     }
19488bcb0991SDimitry Andric     for (auto &Sub : Subs)
19498bcb0991SDimitry Andric       Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
19508bcb0991SDimitry Andric                                     *MRI.getTargetRegisterInfo());
19518bcb0991SDimitry Andric   }
19528bcb0991SDimitry Andric   if (LIS)
19538bcb0991SDimitry Andric     LIS->RemoveMachineInstrFromMaps(*MI);
19548bcb0991SDimitry Andric   MI->eraseFromParent();
19558bcb0991SDimitry Andric }
19568bcb0991SDimitry Andric 
19578bcb0991SDimitry Andric void PeelingModuloScheduleExpander::fixupBranches() {
19588bcb0991SDimitry Andric   // Work outwards from the kernel.
19598bcb0991SDimitry Andric   bool KernelDisposed = false;
19608bcb0991SDimitry Andric   int TC = Schedule.getNumStages() - 1;
19618bcb0991SDimitry Andric   for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
19628bcb0991SDimitry Andric        ++PI, ++EI, --TC) {
19638bcb0991SDimitry Andric     MachineBasicBlock *Prolog = *PI;
19648bcb0991SDimitry Andric     MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
19658bcb0991SDimitry Andric     MachineBasicBlock *Epilog = *EI;
19668bcb0991SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
19678bcb0991SDimitry Andric     TII->removeBranch(*Prolog);
1968bdd1243dSDimitry Andric     std::optional<bool> StaticallyGreater =
19695ffd83dbSDimitry Andric         LoopInfo->createTripCountGreaterCondition(TC, *Prolog, Cond);
197081ad6265SDimitry Andric     if (!StaticallyGreater) {
19718bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
19728bcb0991SDimitry Andric       // Dynamically branch based on Cond.
19738bcb0991SDimitry Andric       TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
19748bcb0991SDimitry Andric     } else if (*StaticallyGreater == false) {
19758bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
19768bcb0991SDimitry Andric       // Prolog never falls through; branch to epilog and orphan interior
19778bcb0991SDimitry Andric       // blocks. Leave it to unreachable-block-elim to clean up.
19788bcb0991SDimitry Andric       Prolog->removeSuccessor(Fallthrough);
19798bcb0991SDimitry Andric       for (MachineInstr &P : Fallthrough->phis()) {
198081ad6265SDimitry Andric         P.removeOperand(2);
198181ad6265SDimitry Andric         P.removeOperand(1);
19828bcb0991SDimitry Andric       }
19838bcb0991SDimitry Andric       TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
19848bcb0991SDimitry Andric       KernelDisposed = true;
19858bcb0991SDimitry Andric     } else {
19868bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
19878bcb0991SDimitry Andric       // Prolog always falls through; remove incoming values in epilog.
19888bcb0991SDimitry Andric       Prolog->removeSuccessor(Epilog);
19898bcb0991SDimitry Andric       for (MachineInstr &P : Epilog->phis()) {
199081ad6265SDimitry Andric         P.removeOperand(4);
199181ad6265SDimitry Andric         P.removeOperand(3);
19928bcb0991SDimitry Andric       }
19938bcb0991SDimitry Andric     }
19948bcb0991SDimitry Andric   }
19958bcb0991SDimitry Andric 
19968bcb0991SDimitry Andric   if (!KernelDisposed) {
19975ffd83dbSDimitry Andric     LoopInfo->adjustTripCount(-(Schedule.getNumStages() - 1));
19985ffd83dbSDimitry Andric     LoopInfo->setPreheader(Prologs.back());
19998bcb0991SDimitry Andric   } else {
20005ffd83dbSDimitry Andric     LoopInfo->disposed();
20018bcb0991SDimitry Andric   }
20028bcb0991SDimitry Andric }
20038bcb0991SDimitry Andric 
20048bcb0991SDimitry Andric void PeelingModuloScheduleExpander::rewriteKernel() {
2005fe6060f1SDimitry Andric   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
20068bcb0991SDimitry Andric   KR.rewrite();
20078bcb0991SDimitry Andric }
20088bcb0991SDimitry Andric 
20098bcb0991SDimitry Andric void PeelingModuloScheduleExpander::expand() {
20108bcb0991SDimitry Andric   BB = Schedule.getLoop()->getTopBlock();
20118bcb0991SDimitry Andric   Preheader = Schedule.getLoop()->getLoopPreheader();
20128bcb0991SDimitry Andric   LLVM_DEBUG(Schedule.dump());
20135ffd83dbSDimitry Andric   LoopInfo = TII->analyzeLoopForPipelining(BB);
20145ffd83dbSDimitry Andric   assert(LoopInfo);
20158bcb0991SDimitry Andric 
20168bcb0991SDimitry Andric   rewriteKernel();
20178bcb0991SDimitry Andric   peelPrologAndEpilogs();
20188bcb0991SDimitry Andric   fixupBranches();
20198bcb0991SDimitry Andric }
20208bcb0991SDimitry Andric 
20218bcb0991SDimitry Andric void PeelingModuloScheduleExpander::validateAgainstModuloScheduleExpander() {
20228bcb0991SDimitry Andric   BB = Schedule.getLoop()->getTopBlock();
20238bcb0991SDimitry Andric   Preheader = Schedule.getLoop()->getLoopPreheader();
20248bcb0991SDimitry Andric 
20258bcb0991SDimitry Andric   // Dump the schedule before we invalidate and remap all its instructions.
20268bcb0991SDimitry Andric   // Stash it in a string so we can print it if we found an error.
20278bcb0991SDimitry Andric   std::string ScheduleDump;
20288bcb0991SDimitry Andric   raw_string_ostream OS(ScheduleDump);
20298bcb0991SDimitry Andric   Schedule.print(OS);
20308bcb0991SDimitry Andric   OS.flush();
20318bcb0991SDimitry Andric 
20328bcb0991SDimitry Andric   // First, run the normal ModuleScheduleExpander. We don't support any
20338bcb0991SDimitry Andric   // InstrChanges.
20348bcb0991SDimitry Andric   assert(LIS && "Requires LiveIntervals!");
20358bcb0991SDimitry Andric   ModuloScheduleExpander MSE(MF, Schedule, *LIS,
20368bcb0991SDimitry Andric                              ModuloScheduleExpander::InstrChangesTy());
20378bcb0991SDimitry Andric   MSE.expand();
20388bcb0991SDimitry Andric   MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
20398bcb0991SDimitry Andric   if (!ExpandedKernel) {
20408bcb0991SDimitry Andric     // The expander optimized away the kernel. We can't do any useful checking.
20418bcb0991SDimitry Andric     MSE.cleanup();
20428bcb0991SDimitry Andric     return;
20438bcb0991SDimitry Andric   }
20448bcb0991SDimitry Andric   // Before running the KernelRewriter, re-add BB into the CFG.
20458bcb0991SDimitry Andric   Preheader->addSuccessor(BB);
20468bcb0991SDimitry Andric 
20478bcb0991SDimitry Andric   // Now run the new expansion algorithm.
2048fe6060f1SDimitry Andric   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
20498bcb0991SDimitry Andric   KR.rewrite();
20508bcb0991SDimitry Andric   peelPrologAndEpilogs();
20518bcb0991SDimitry Andric 
20528bcb0991SDimitry Andric   // Collect all illegal phis that the new algorithm created. We'll give these
20538bcb0991SDimitry Andric   // to KernelOperandInfo.
20548bcb0991SDimitry Andric   SmallPtrSet<MachineInstr *, 4> IllegalPhis;
20558bcb0991SDimitry Andric   for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
20568bcb0991SDimitry Andric     if (NI->isPHI())
20578bcb0991SDimitry Andric       IllegalPhis.insert(&*NI);
20588bcb0991SDimitry Andric   }
20598bcb0991SDimitry Andric 
20608bcb0991SDimitry Andric   // Co-iterate across both kernels. We expect them to be identical apart from
20618bcb0991SDimitry Andric   // phis and full COPYs (we look through both).
20628bcb0991SDimitry Andric   SmallVector<std::pair<KernelOperandInfo, KernelOperandInfo>, 8> KOIs;
20638bcb0991SDimitry Andric   auto OI = ExpandedKernel->begin();
20648bcb0991SDimitry Andric   auto NI = BB->begin();
20658bcb0991SDimitry Andric   for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
20668bcb0991SDimitry Andric     while (OI->isPHI() || OI->isFullCopy())
20678bcb0991SDimitry Andric       ++OI;
20688bcb0991SDimitry Andric     while (NI->isPHI() || NI->isFullCopy())
20698bcb0991SDimitry Andric       ++NI;
20708bcb0991SDimitry Andric     assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
20718bcb0991SDimitry Andric     // Analyze every operand separately.
20728bcb0991SDimitry Andric     for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
20738bcb0991SDimitry Andric          OOpI != OI->operands_end(); ++OOpI, ++NOpI)
20748bcb0991SDimitry Andric       KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
20758bcb0991SDimitry Andric                         KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
20768bcb0991SDimitry Andric   }
20778bcb0991SDimitry Andric 
20788bcb0991SDimitry Andric   bool Failed = false;
20798bcb0991SDimitry Andric   for (auto &OldAndNew : KOIs) {
20808bcb0991SDimitry Andric     if (OldAndNew.first == OldAndNew.second)
20818bcb0991SDimitry Andric       continue;
20828bcb0991SDimitry Andric     Failed = true;
20838bcb0991SDimitry Andric     errs() << "Modulo kernel validation error: [\n";
20848bcb0991SDimitry Andric     errs() << " [golden] ";
20858bcb0991SDimitry Andric     OldAndNew.first.print(errs());
20868bcb0991SDimitry Andric     errs() << "          ";
20878bcb0991SDimitry Andric     OldAndNew.second.print(errs());
20888bcb0991SDimitry Andric     errs() << "]\n";
20898bcb0991SDimitry Andric   }
20908bcb0991SDimitry Andric 
20918bcb0991SDimitry Andric   if (Failed) {
20928bcb0991SDimitry Andric     errs() << "Golden reference kernel:\n";
20938bcb0991SDimitry Andric     ExpandedKernel->print(errs());
20948bcb0991SDimitry Andric     errs() << "New kernel:\n";
20958bcb0991SDimitry Andric     BB->print(errs());
20968bcb0991SDimitry Andric     errs() << ScheduleDump;
20978bcb0991SDimitry Andric     report_fatal_error(
20988bcb0991SDimitry Andric         "Modulo kernel validation (-pipeliner-experimental-cg) failed");
20998bcb0991SDimitry Andric   }
21008bcb0991SDimitry Andric 
21018bcb0991SDimitry Andric   // Cleanup by removing BB from the CFG again as the original
21028bcb0991SDimitry Andric   // ModuloScheduleExpander intended.
21038bcb0991SDimitry Andric   Preheader->removeSuccessor(BB);
21048bcb0991SDimitry Andric   MSE.cleanup();
21058bcb0991SDimitry Andric }
21068bcb0991SDimitry Andric 
21070fca6ea1SDimitry Andric MachineInstr *ModuloScheduleExpanderMVE::cloneInstr(MachineInstr *OldMI) {
21080fca6ea1SDimitry Andric   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
21090fca6ea1SDimitry Andric 
21100fca6ea1SDimitry Andric   // TODO: Offset information needs to be corrected.
21110fca6ea1SDimitry Andric   NewMI->dropMemRefs(MF);
21120fca6ea1SDimitry Andric 
21130fca6ea1SDimitry Andric   return NewMI;
21140fca6ea1SDimitry Andric }
21150fca6ea1SDimitry Andric 
21160fca6ea1SDimitry Andric /// Create a dedicated exit for Loop. Exit is the original exit for Loop.
21170fca6ea1SDimitry Andric /// If it is already dedicated exit, return it. Otherwise, insert a new
21180fca6ea1SDimitry Andric /// block between them and return the new block.
21190fca6ea1SDimitry Andric static MachineBasicBlock *createDedicatedExit(MachineBasicBlock *Loop,
21200fca6ea1SDimitry Andric                                               MachineBasicBlock *Exit) {
21210fca6ea1SDimitry Andric   if (Exit->pred_size() == 1)
21220fca6ea1SDimitry Andric     return Exit;
21230fca6ea1SDimitry Andric 
21240fca6ea1SDimitry Andric   MachineFunction *MF = Loop->getParent();
21250fca6ea1SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21260fca6ea1SDimitry Andric 
21270fca6ea1SDimitry Andric   MachineBasicBlock *NewExit =
21280fca6ea1SDimitry Andric       MF->CreateMachineBasicBlock(Loop->getBasicBlock());
21290fca6ea1SDimitry Andric   MF->insert(Loop->getIterator(), NewExit);
21300fca6ea1SDimitry Andric 
21310fca6ea1SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
21320fca6ea1SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
21330fca6ea1SDimitry Andric   TII->analyzeBranch(*Loop, TBB, FBB, Cond);
21340fca6ea1SDimitry Andric   if (TBB == Loop)
21350fca6ea1SDimitry Andric     FBB = NewExit;
21360fca6ea1SDimitry Andric   else if (FBB == Loop)
21370fca6ea1SDimitry Andric     TBB = NewExit;
21380fca6ea1SDimitry Andric   else
21390fca6ea1SDimitry Andric     llvm_unreachable("unexpected loop structure");
21400fca6ea1SDimitry Andric   TII->removeBranch(*Loop);
21410fca6ea1SDimitry Andric   TII->insertBranch(*Loop, TBB, FBB, Cond, DebugLoc());
21420fca6ea1SDimitry Andric   Loop->replaceSuccessor(Exit, NewExit);
21430fca6ea1SDimitry Andric   TII->insertUnconditionalBranch(*NewExit, Exit, DebugLoc());
21440fca6ea1SDimitry Andric   NewExit->addSuccessor(Exit);
21450fca6ea1SDimitry Andric 
21460fca6ea1SDimitry Andric   Exit->replacePhiUsesWith(Loop, NewExit);
21470fca6ea1SDimitry Andric 
21480fca6ea1SDimitry Andric   return NewExit;
21490fca6ea1SDimitry Andric }
21500fca6ea1SDimitry Andric 
21510fca6ea1SDimitry Andric /// Insert branch code into the end of MBB. It branches to GreaterThan if the
21520fca6ea1SDimitry Andric /// remaining trip count for instructions in LastStage0Insts is greater than
21530fca6ea1SDimitry Andric /// RequiredTC, and to Otherwise otherwise.
21540fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::insertCondBranch(MachineBasicBlock &MBB,
21550fca6ea1SDimitry Andric                                                  int RequiredTC,
21560fca6ea1SDimitry Andric                                                  InstrMapTy &LastStage0Insts,
21570fca6ea1SDimitry Andric                                                  MachineBasicBlock &GreaterThan,
21580fca6ea1SDimitry Andric                                                  MachineBasicBlock &Otherwise) {
21590fca6ea1SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
21600fca6ea1SDimitry Andric   LoopInfo->createRemainingIterationsGreaterCondition(RequiredTC, MBB, Cond,
21610fca6ea1SDimitry Andric                                                       LastStage0Insts);
21620fca6ea1SDimitry Andric 
21630fca6ea1SDimitry Andric   if (SwapBranchTargetsMVE) {
21640fca6ea1SDimitry Andric     // Set SwapBranchTargetsMVE to true if a target prefers to replace TBB and
21650fca6ea1SDimitry Andric     // FBB for optimal performance.
21660fca6ea1SDimitry Andric     if (TII->reverseBranchCondition(Cond))
21670fca6ea1SDimitry Andric       llvm_unreachable("can not reverse branch condition");
21680fca6ea1SDimitry Andric     TII->insertBranch(MBB, &Otherwise, &GreaterThan, Cond, DebugLoc());
21690fca6ea1SDimitry Andric   } else {
21700fca6ea1SDimitry Andric     TII->insertBranch(MBB, &GreaterThan, &Otherwise, Cond, DebugLoc());
21710fca6ea1SDimitry Andric   }
21720fca6ea1SDimitry Andric }
21730fca6ea1SDimitry Andric 
21740fca6ea1SDimitry Andric /// Generate a pipelined loop that is unrolled by using MVE algorithm and any
21750fca6ea1SDimitry Andric /// other necessary blocks. The control flow is modified to execute the
21760fca6ea1SDimitry Andric /// pipelined loop if the trip count satisfies the condition, otherwise the
21770fca6ea1SDimitry Andric /// original loop. The original loop is also used to execute the remainder
21780fca6ea1SDimitry Andric /// iterations which occur due to unrolling.
21790fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::generatePipelinedLoop() {
21800fca6ea1SDimitry Andric   // The control flow for pipelining with MVE:
21810fca6ea1SDimitry Andric   //
21820fca6ea1SDimitry Andric   // OrigPreheader:
21830fca6ea1SDimitry Andric   //   // The block that is originally the loop preheader
21840fca6ea1SDimitry Andric   //   goto Check
21850fca6ea1SDimitry Andric   //
21860fca6ea1SDimitry Andric   // Check:
21870fca6ea1SDimitry Andric   //   // Check whether the trip count satisfies the requirements to pipeline.
21880fca6ea1SDimitry Andric   //   if (LoopCounter > NumStages + NumUnroll - 2)
21890fca6ea1SDimitry Andric   //     // The minimum number of iterations to pipeline =
21900fca6ea1SDimitry Andric   //     //   iterations executed in prolog/epilog (NumStages-1) +
21910fca6ea1SDimitry Andric   //     //   iterations executed in one kernel run (NumUnroll)
21920fca6ea1SDimitry Andric   //     goto Prolog
21930fca6ea1SDimitry Andric   //   // fallback to the original loop
21940fca6ea1SDimitry Andric   //   goto NewPreheader
21950fca6ea1SDimitry Andric   //
21960fca6ea1SDimitry Andric   // Prolog:
21970fca6ea1SDimitry Andric   //   // All prolog stages. There are no direct branches to the epilogue.
21980fca6ea1SDimitry Andric   //   goto NewKernel
21990fca6ea1SDimitry Andric   //
22000fca6ea1SDimitry Andric   // NewKernel:
22010fca6ea1SDimitry Andric   //   // NumUnroll copies of the kernel
22020fca6ea1SDimitry Andric   //   if (LoopCounter > MVE-1)
22030fca6ea1SDimitry Andric   //     goto NewKernel
22040fca6ea1SDimitry Andric   //   goto Epilog
22050fca6ea1SDimitry Andric   //
22060fca6ea1SDimitry Andric   // Epilog:
22070fca6ea1SDimitry Andric   //   // All epilog stages.
22080fca6ea1SDimitry Andric   //   if (LoopCounter > 0)
22090fca6ea1SDimitry Andric   //     // The remainder is executed in the original loop
22100fca6ea1SDimitry Andric   //     goto NewPreheader
22110fca6ea1SDimitry Andric   //   goto NewExit
22120fca6ea1SDimitry Andric   //
22130fca6ea1SDimitry Andric   // NewPreheader:
22140fca6ea1SDimitry Andric   //   // Newly created preheader for the original loop.
22150fca6ea1SDimitry Andric   //   // The initial values of the phis in the loop are merged from two paths.
22160fca6ea1SDimitry Andric   //   NewInitVal = Phi OrigInitVal, Check, PipelineLastVal, Epilog
22170fca6ea1SDimitry Andric   //   goto OrigKernel
22180fca6ea1SDimitry Andric   //
22190fca6ea1SDimitry Andric   // OrigKernel:
22200fca6ea1SDimitry Andric   //   // The original loop block.
22210fca6ea1SDimitry Andric   //   if (LoopCounter != 0)
22220fca6ea1SDimitry Andric   //     goto OrigKernel
22230fca6ea1SDimitry Andric   //   goto NewExit
22240fca6ea1SDimitry Andric   //
22250fca6ea1SDimitry Andric   // NewExit:
22260fca6ea1SDimitry Andric   //   // Newly created dedicated exit for the original loop.
22270fca6ea1SDimitry Andric   //   // Merge values which are referenced after the loop
22280fca6ea1SDimitry Andric   //   Merged = Phi OrigVal, OrigKernel, PipelineVal, Epilog
22290fca6ea1SDimitry Andric   //   goto OrigExit
22300fca6ea1SDimitry Andric   //
22310fca6ea1SDimitry Andric   // OrigExit:
22320fca6ea1SDimitry Andric   //   // The block that is originally the loop exit.
22330fca6ea1SDimitry Andric   //   // If it is already deicated exit, NewExit is not created.
22340fca6ea1SDimitry Andric 
22350fca6ea1SDimitry Andric   // An example of where each stage is executed:
22360fca6ea1SDimitry Andric   // Assume #Stages 3, #MVE 4, #Iterations 12
22370fca6ea1SDimitry Andric   // Iter   0 1 2 3 4 5 6 7 8 9 10-11
22380fca6ea1SDimitry Andric   // -------------------------------------------------
22390fca6ea1SDimitry Andric   // Stage  0                          Prolog#0
22400fca6ea1SDimitry Andric   // Stage  1 0                        Prolog#1
22410fca6ea1SDimitry Andric   // Stage  2 1 0                      Kernel Unroll#0 Iter#0
22420fca6ea1SDimitry Andric   // Stage    2 1 0                    Kernel Unroll#1 Iter#0
22430fca6ea1SDimitry Andric   // Stage      2 1 0                  Kernel Unroll#2 Iter#0
22440fca6ea1SDimitry Andric   // Stage        2 1 0                Kernel Unroll#3 Iter#0
22450fca6ea1SDimitry Andric   // Stage          2 1 0              Kernel Unroll#0 Iter#1
22460fca6ea1SDimitry Andric   // Stage            2 1 0            Kernel Unroll#1 Iter#1
22470fca6ea1SDimitry Andric   // Stage              2 1 0          Kernel Unroll#2 Iter#1
22480fca6ea1SDimitry Andric   // Stage                2 1 0        Kernel Unroll#3 Iter#1
22490fca6ea1SDimitry Andric   // Stage                  2 1        Epilog#0
22500fca6ea1SDimitry Andric   // Stage                    2        Epilog#1
22510fca6ea1SDimitry Andric   // Stage                      0-2    OrigKernel
22520fca6ea1SDimitry Andric 
22530fca6ea1SDimitry Andric   LoopInfo = TII->analyzeLoopForPipelining(OrigKernel);
22540fca6ea1SDimitry Andric   assert(LoopInfo && "Must be able to analyze loop!");
22550fca6ea1SDimitry Andric 
22560fca6ea1SDimitry Andric   calcNumUnroll();
22570fca6ea1SDimitry Andric 
22580fca6ea1SDimitry Andric   Check = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
22590fca6ea1SDimitry Andric   Prolog = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
22600fca6ea1SDimitry Andric   NewKernel = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
22610fca6ea1SDimitry Andric   Epilog = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
22620fca6ea1SDimitry Andric   NewPreheader = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
22630fca6ea1SDimitry Andric 
22640fca6ea1SDimitry Andric   MF.insert(OrigKernel->getIterator(), Check);
22650fca6ea1SDimitry Andric   MF.insert(OrigKernel->getIterator(), Prolog);
22660fca6ea1SDimitry Andric   MF.insert(OrigKernel->getIterator(), NewKernel);
22670fca6ea1SDimitry Andric   MF.insert(OrigKernel->getIterator(), Epilog);
22680fca6ea1SDimitry Andric   MF.insert(OrigKernel->getIterator(), NewPreheader);
22690fca6ea1SDimitry Andric 
22700fca6ea1SDimitry Andric   NewExit = createDedicatedExit(OrigKernel, OrigExit);
22710fca6ea1SDimitry Andric 
22720fca6ea1SDimitry Andric   NewPreheader->transferSuccessorsAndUpdatePHIs(OrigPreheader);
22730fca6ea1SDimitry Andric   TII->insertUnconditionalBranch(*NewPreheader, OrigKernel, DebugLoc());
22740fca6ea1SDimitry Andric 
22750fca6ea1SDimitry Andric   OrigPreheader->addSuccessor(Check);
22760fca6ea1SDimitry Andric   TII->removeBranch(*OrigPreheader);
22770fca6ea1SDimitry Andric   TII->insertUnconditionalBranch(*OrigPreheader, Check, DebugLoc());
22780fca6ea1SDimitry Andric 
22790fca6ea1SDimitry Andric   Check->addSuccessor(Prolog);
22800fca6ea1SDimitry Andric   Check->addSuccessor(NewPreheader);
22810fca6ea1SDimitry Andric 
22820fca6ea1SDimitry Andric   Prolog->addSuccessor(NewKernel);
22830fca6ea1SDimitry Andric 
22840fca6ea1SDimitry Andric   NewKernel->addSuccessor(NewKernel);
22850fca6ea1SDimitry Andric   NewKernel->addSuccessor(Epilog);
22860fca6ea1SDimitry Andric 
22870fca6ea1SDimitry Andric   Epilog->addSuccessor(NewPreheader);
22880fca6ea1SDimitry Andric   Epilog->addSuccessor(NewExit);
22890fca6ea1SDimitry Andric 
22900fca6ea1SDimitry Andric   InstrMapTy LastStage0Insts;
22910fca6ea1SDimitry Andric   insertCondBranch(*Check, Schedule.getNumStages() + NumUnroll - 2,
22920fca6ea1SDimitry Andric                    LastStage0Insts, *Prolog, *NewPreheader);
22930fca6ea1SDimitry Andric 
22940fca6ea1SDimitry Andric   // VRMaps map (prolog/kernel/epilog phase#, original register#) to new
22950fca6ea1SDimitry Andric   // register#
22960fca6ea1SDimitry Andric   SmallVector<ValueMapTy> PrologVRMap, KernelVRMap, EpilogVRMap;
22970fca6ea1SDimitry Andric   generateProlog(PrologVRMap);
22980fca6ea1SDimitry Andric   generateKernel(PrologVRMap, KernelVRMap, LastStage0Insts);
22990fca6ea1SDimitry Andric   generateEpilog(KernelVRMap, EpilogVRMap, LastStage0Insts);
23000fca6ea1SDimitry Andric }
23010fca6ea1SDimitry Andric 
23020fca6ea1SDimitry Andric /// Replace MI's use operands according to the maps.
23030fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::updateInstrUse(
23040fca6ea1SDimitry Andric     MachineInstr *MI, int StageNum, int PhaseNum,
23050fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &CurVRMap,
23060fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> *PrevVRMap) {
23070fca6ea1SDimitry Andric   // If MI is in the prolog/kernel/epilog block, CurVRMap is
23080fca6ea1SDimitry Andric   // PrologVRMap/KernelVRMap/EpilogVRMap respectively.
23090fca6ea1SDimitry Andric   // PrevVRMap is nullptr/PhiVRMap/KernelVRMap respectively.
23100fca6ea1SDimitry Andric   // Refer to the appropriate map according to the stage difference between
23110fca6ea1SDimitry Andric   // MI and the definition of an operand.
23120fca6ea1SDimitry Andric 
23130fca6ea1SDimitry Andric   for (MachineOperand &UseMO : MI->uses()) {
23140fca6ea1SDimitry Andric     if (!UseMO.isReg() || !UseMO.getReg().isVirtual())
23150fca6ea1SDimitry Andric       continue;
23160fca6ea1SDimitry Andric     int DiffStage = 0;
23170fca6ea1SDimitry Andric     Register OrigReg = UseMO.getReg();
23180fca6ea1SDimitry Andric     MachineInstr *DefInst = MRI.getVRegDef(OrigReg);
23190fca6ea1SDimitry Andric     if (!DefInst || DefInst->getParent() != OrigKernel)
23200fca6ea1SDimitry Andric       continue;
23210fca6ea1SDimitry Andric     unsigned InitReg = 0;
23220fca6ea1SDimitry Andric     unsigned DefReg = OrigReg;
23230fca6ea1SDimitry Andric     if (DefInst->isPHI()) {
23240fca6ea1SDimitry Andric       ++DiffStage;
23250fca6ea1SDimitry Andric       unsigned LoopReg;
23260fca6ea1SDimitry Andric       getPhiRegs(*DefInst, OrigKernel, InitReg, LoopReg);
23270fca6ea1SDimitry Andric       // LoopReg is guaranteed to be defined within the loop by canApply()
23280fca6ea1SDimitry Andric       DefReg = LoopReg;
23290fca6ea1SDimitry Andric       DefInst = MRI.getVRegDef(LoopReg);
23300fca6ea1SDimitry Andric     }
23310fca6ea1SDimitry Andric     unsigned DefStageNum = Schedule.getStage(DefInst);
23320fca6ea1SDimitry Andric     DiffStage += StageNum - DefStageNum;
23330fca6ea1SDimitry Andric     Register NewReg;
23340fca6ea1SDimitry Andric     if (PhaseNum >= DiffStage && CurVRMap[PhaseNum - DiffStage].count(DefReg))
23350fca6ea1SDimitry Andric       // NewReg is defined in a previous phase of the same block
23360fca6ea1SDimitry Andric       NewReg = CurVRMap[PhaseNum - DiffStage][DefReg];
23370fca6ea1SDimitry Andric     else if (!PrevVRMap)
23380fca6ea1SDimitry Andric       // Since this is the first iteration, refer the initial register of the
23390fca6ea1SDimitry Andric       // loop
23400fca6ea1SDimitry Andric       NewReg = InitReg;
23410fca6ea1SDimitry Andric     else
23420fca6ea1SDimitry Andric       // Cases where DiffStage is larger than PhaseNum.
23430fca6ea1SDimitry Andric       // If MI is in the kernel block, the value is defined by the previous
23440fca6ea1SDimitry Andric       // iteration and PhiVRMap is referenced. If MI is in the epilog block, the
23450fca6ea1SDimitry Andric       // value is defined in the kernel block and KernelVRMap is referenced.
23460fca6ea1SDimitry Andric       NewReg = (*PrevVRMap)[PrevVRMap->size() - (DiffStage - PhaseNum)][DefReg];
23470fca6ea1SDimitry Andric 
23480fca6ea1SDimitry Andric     const TargetRegisterClass *NRC =
23490fca6ea1SDimitry Andric         MRI.constrainRegClass(NewReg, MRI.getRegClass(OrigReg));
23500fca6ea1SDimitry Andric     if (NRC)
23510fca6ea1SDimitry Andric       UseMO.setReg(NewReg);
23520fca6ea1SDimitry Andric     else {
23530fca6ea1SDimitry Andric       Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OrigReg));
23540fca6ea1SDimitry Andric       BuildMI(*OrigKernel, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
23550fca6ea1SDimitry Andric               SplitReg)
23560fca6ea1SDimitry Andric           .addReg(NewReg);
23570fca6ea1SDimitry Andric       UseMO.setReg(SplitReg);
23580fca6ea1SDimitry Andric     }
23590fca6ea1SDimitry Andric   }
23600fca6ea1SDimitry Andric }
23610fca6ea1SDimitry Andric 
23620fca6ea1SDimitry Andric /// Return a phi if Reg is referenced by the phi.
23630fca6ea1SDimitry Andric /// canApply() guarantees that at most only one such phi exists.
23640fca6ea1SDimitry Andric static MachineInstr *getLoopPhiUser(Register Reg, MachineBasicBlock *Loop) {
23650fca6ea1SDimitry Andric   for (MachineInstr &Phi : Loop->phis()) {
23660fca6ea1SDimitry Andric     unsigned InitVal, LoopVal;
23670fca6ea1SDimitry Andric     getPhiRegs(Phi, Loop, InitVal, LoopVal);
23680fca6ea1SDimitry Andric     if (LoopVal == Reg)
23690fca6ea1SDimitry Andric       return &Phi;
23700fca6ea1SDimitry Andric   }
23710fca6ea1SDimitry Andric   return nullptr;
23720fca6ea1SDimitry Andric }
23730fca6ea1SDimitry Andric 
23740fca6ea1SDimitry Andric /// Generate phis for registers defined by OrigMI.
23750fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::generatePhi(
23760fca6ea1SDimitry Andric     MachineInstr *OrigMI, int UnrollNum,
23770fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &PrologVRMap,
23780fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &KernelVRMap,
23790fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &PhiVRMap) {
23800fca6ea1SDimitry Andric   int StageNum = Schedule.getStage(OrigMI);
23810fca6ea1SDimitry Andric   bool UsePrologReg;
23820fca6ea1SDimitry Andric   if (Schedule.getNumStages() - NumUnroll + UnrollNum - 1 >= StageNum)
23830fca6ea1SDimitry Andric     UsePrologReg = true;
23840fca6ea1SDimitry Andric   else if (Schedule.getNumStages() - NumUnroll + UnrollNum == StageNum)
23850fca6ea1SDimitry Andric     UsePrologReg = false;
23860fca6ea1SDimitry Andric   else
23870fca6ea1SDimitry Andric     return;
23880fca6ea1SDimitry Andric 
23890fca6ea1SDimitry Andric   // Examples that show which stages are merged by phi.
23900fca6ea1SDimitry Andric   // Meaning of the symbol following the stage number:
23910fca6ea1SDimitry Andric   //   a/b: Stages with the same letter are merged (UsePrologReg == true)
23920fca6ea1SDimitry Andric   //   +: Merged with the initial value (UsePrologReg == false)
23930fca6ea1SDimitry Andric   //   *: No phis required
23940fca6ea1SDimitry Andric   //
23950fca6ea1SDimitry Andric   // #Stages 3, #MVE 4
23960fca6ea1SDimitry Andric   // Iter   0 1 2 3 4 5 6 7 8
23970fca6ea1SDimitry Andric   // -----------------------------------------
23980fca6ea1SDimitry Andric   // Stage  0a                 Prolog#0
23990fca6ea1SDimitry Andric   // Stage  1a 0b              Prolog#1
24000fca6ea1SDimitry Andric   // Stage  2* 1* 0*           Kernel Unroll#0
24010fca6ea1SDimitry Andric   // Stage     2* 1* 0+        Kernel Unroll#1
24020fca6ea1SDimitry Andric   // Stage        2* 1+ 0a     Kernel Unroll#2
24030fca6ea1SDimitry Andric   // Stage           2+ 1a 0b  Kernel Unroll#3
24040fca6ea1SDimitry Andric   //
24050fca6ea1SDimitry Andric   // #Stages 3, #MVE 2
24060fca6ea1SDimitry Andric   // Iter   0 1 2 3 4 5 6 7 8
24070fca6ea1SDimitry Andric   // -----------------------------------------
24080fca6ea1SDimitry Andric   // Stage  0a                 Prolog#0
24090fca6ea1SDimitry Andric   // Stage  1a 0b              Prolog#1
24100fca6ea1SDimitry Andric   // Stage  2* 1+ 0a           Kernel Unroll#0
24110fca6ea1SDimitry Andric   // Stage     2+ 1a 0b        Kernel Unroll#1
24120fca6ea1SDimitry Andric   //
24130fca6ea1SDimitry Andric   // #Stages 3, #MVE 1
24140fca6ea1SDimitry Andric   // Iter   0 1 2 3 4 5 6 7 8
24150fca6ea1SDimitry Andric   // -----------------------------------------
24160fca6ea1SDimitry Andric   // Stage  0*                 Prolog#0
24170fca6ea1SDimitry Andric   // Stage  1a 0b              Prolog#1
24180fca6ea1SDimitry Andric   // Stage  2+ 1a 0b           Kernel Unroll#0
24190fca6ea1SDimitry Andric 
24200fca6ea1SDimitry Andric   for (MachineOperand &DefMO : OrigMI->defs()) {
24210fca6ea1SDimitry Andric     if (!DefMO.isReg() || DefMO.isDead())
24220fca6ea1SDimitry Andric       continue;
24230fca6ea1SDimitry Andric     Register OrigReg = DefMO.getReg();
24240fca6ea1SDimitry Andric     auto NewReg = KernelVRMap[UnrollNum].find(OrigReg);
24250fca6ea1SDimitry Andric     if (NewReg == KernelVRMap[UnrollNum].end())
24260fca6ea1SDimitry Andric       continue;
24270fca6ea1SDimitry Andric     Register CorrespondReg;
24280fca6ea1SDimitry Andric     if (UsePrologReg) {
24290fca6ea1SDimitry Andric       int PrologNum = Schedule.getNumStages() - NumUnroll + UnrollNum - 1;
24300fca6ea1SDimitry Andric       CorrespondReg = PrologVRMap[PrologNum][OrigReg];
24310fca6ea1SDimitry Andric     } else {
24320fca6ea1SDimitry Andric       MachineInstr *Phi = getLoopPhiUser(OrigReg, OrigKernel);
24330fca6ea1SDimitry Andric       if (!Phi)
24340fca6ea1SDimitry Andric         continue;
24350fca6ea1SDimitry Andric       CorrespondReg = getInitPhiReg(*Phi, OrigKernel);
24360fca6ea1SDimitry Andric     }
24370fca6ea1SDimitry Andric 
24380fca6ea1SDimitry Andric     assert(CorrespondReg.isValid());
24390fca6ea1SDimitry Andric     Register PhiReg = MRI.createVirtualRegister(MRI.getRegClass(OrigReg));
24400fca6ea1SDimitry Andric     BuildMI(*NewKernel, NewKernel->getFirstNonPHI(), DebugLoc(),
24410fca6ea1SDimitry Andric             TII->get(TargetOpcode::PHI), PhiReg)
24420fca6ea1SDimitry Andric         .addReg(NewReg->second)
24430fca6ea1SDimitry Andric         .addMBB(NewKernel)
24440fca6ea1SDimitry Andric         .addReg(CorrespondReg)
24450fca6ea1SDimitry Andric         .addMBB(Prolog);
24460fca6ea1SDimitry Andric     PhiVRMap[UnrollNum][OrigReg] = PhiReg;
24470fca6ea1SDimitry Andric   }
24480fca6ea1SDimitry Andric }
24490fca6ea1SDimitry Andric 
24500fca6ea1SDimitry Andric static void replacePhiSrc(MachineInstr &Phi, Register OrigReg, Register NewReg,
24510fca6ea1SDimitry Andric                           MachineBasicBlock *NewMBB) {
24520fca6ea1SDimitry Andric   for (unsigned Idx = 1; Idx < Phi.getNumOperands(); Idx += 2) {
24530fca6ea1SDimitry Andric     if (Phi.getOperand(Idx).getReg() == OrigReg) {
24540fca6ea1SDimitry Andric       Phi.getOperand(Idx).setReg(NewReg);
24550fca6ea1SDimitry Andric       Phi.getOperand(Idx + 1).setMBB(NewMBB);
24560fca6ea1SDimitry Andric       return;
24570fca6ea1SDimitry Andric     }
24580fca6ea1SDimitry Andric   }
24590fca6ea1SDimitry Andric }
24600fca6ea1SDimitry Andric 
24610fca6ea1SDimitry Andric /// Generate phis that merge values from multiple routes
24620fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::mergeRegUsesAfterPipeline(Register OrigReg,
24630fca6ea1SDimitry Andric                                                           Register NewReg) {
24640fca6ea1SDimitry Andric   SmallVector<MachineOperand *> UsesAfterLoop;
24650fca6ea1SDimitry Andric   SmallVector<MachineInstr *> LoopPhis;
24660fca6ea1SDimitry Andric   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(OrigReg),
24670fca6ea1SDimitry Andric                                          E = MRI.use_end();
24680fca6ea1SDimitry Andric        I != E; ++I) {
24690fca6ea1SDimitry Andric     MachineOperand &O = *I;
24700fca6ea1SDimitry Andric     if (O.getParent()->getParent() != OrigKernel &&
24710fca6ea1SDimitry Andric         O.getParent()->getParent() != Prolog &&
24720fca6ea1SDimitry Andric         O.getParent()->getParent() != NewKernel &&
24730fca6ea1SDimitry Andric         O.getParent()->getParent() != Epilog)
24740fca6ea1SDimitry Andric       UsesAfterLoop.push_back(&O);
24750fca6ea1SDimitry Andric     if (O.getParent()->getParent() == OrigKernel && O.getParent()->isPHI())
24760fca6ea1SDimitry Andric       LoopPhis.push_back(O.getParent());
24770fca6ea1SDimitry Andric   }
24780fca6ea1SDimitry Andric 
24790fca6ea1SDimitry Andric   // Merge the route that only execute the pipelined loop (when there are no
24800fca6ea1SDimitry Andric   // remaining iterations) with the route that execute the original loop.
24810fca6ea1SDimitry Andric   if (!UsesAfterLoop.empty()) {
24820fca6ea1SDimitry Andric     Register PhiReg = MRI.createVirtualRegister(MRI.getRegClass(OrigReg));
24830fca6ea1SDimitry Andric     BuildMI(*NewExit, NewExit->getFirstNonPHI(), DebugLoc(),
24840fca6ea1SDimitry Andric             TII->get(TargetOpcode::PHI), PhiReg)
24850fca6ea1SDimitry Andric         .addReg(OrigReg)
24860fca6ea1SDimitry Andric         .addMBB(OrigKernel)
24870fca6ea1SDimitry Andric         .addReg(NewReg)
24880fca6ea1SDimitry Andric         .addMBB(Epilog);
24890fca6ea1SDimitry Andric 
24900fca6ea1SDimitry Andric     for (MachineOperand *MO : UsesAfterLoop)
24910fca6ea1SDimitry Andric       MO->setReg(PhiReg);
24920fca6ea1SDimitry Andric 
24930fca6ea1SDimitry Andric     if (!LIS.hasInterval(PhiReg))
24940fca6ea1SDimitry Andric       LIS.createEmptyInterval(PhiReg);
24950fca6ea1SDimitry Andric   }
24960fca6ea1SDimitry Andric 
24970fca6ea1SDimitry Andric   // Merge routes from the pipelined loop and the bypassed route before the
24980fca6ea1SDimitry Andric   // original loop
24990fca6ea1SDimitry Andric   if (!LoopPhis.empty()) {
25000fca6ea1SDimitry Andric     for (MachineInstr *Phi : LoopPhis) {
25010fca6ea1SDimitry Andric       unsigned InitReg, LoopReg;
25020fca6ea1SDimitry Andric       getPhiRegs(*Phi, OrigKernel, InitReg, LoopReg);
25030fca6ea1SDimitry Andric       Register NewInit = MRI.createVirtualRegister(MRI.getRegClass(InitReg));
25040fca6ea1SDimitry Andric       BuildMI(*NewPreheader, NewPreheader->getFirstNonPHI(), Phi->getDebugLoc(),
25050fca6ea1SDimitry Andric               TII->get(TargetOpcode::PHI), NewInit)
25060fca6ea1SDimitry Andric           .addReg(InitReg)
25070fca6ea1SDimitry Andric           .addMBB(Check)
25080fca6ea1SDimitry Andric           .addReg(NewReg)
25090fca6ea1SDimitry Andric           .addMBB(Epilog);
25100fca6ea1SDimitry Andric       replacePhiSrc(*Phi, InitReg, NewInit, NewPreheader);
25110fca6ea1SDimitry Andric     }
25120fca6ea1SDimitry Andric   }
25130fca6ea1SDimitry Andric }
25140fca6ea1SDimitry Andric 
25150fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::generateProlog(
25160fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &PrologVRMap) {
25170fca6ea1SDimitry Andric   PrologVRMap.clear();
25180fca6ea1SDimitry Andric   PrologVRMap.resize(Schedule.getNumStages() - 1);
25190fca6ea1SDimitry Andric   DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
25200fca6ea1SDimitry Andric   for (int PrologNum = 0; PrologNum < Schedule.getNumStages() - 1;
25210fca6ea1SDimitry Andric        ++PrologNum) {
25220fca6ea1SDimitry Andric     for (MachineInstr *MI : Schedule.getInstructions()) {
25230fca6ea1SDimitry Andric       if (MI->isPHI())
25240fca6ea1SDimitry Andric         continue;
25250fca6ea1SDimitry Andric       int StageNum = Schedule.getStage(MI);
25260fca6ea1SDimitry Andric       if (StageNum > PrologNum)
25270fca6ea1SDimitry Andric         continue;
25280fca6ea1SDimitry Andric       MachineInstr *NewMI = cloneInstr(MI);
25290fca6ea1SDimitry Andric       updateInstrDef(NewMI, PrologVRMap[PrologNum], false);
25300fca6ea1SDimitry Andric       NewMIMap[NewMI] = {PrologNum, StageNum};
25310fca6ea1SDimitry Andric       Prolog->push_back(NewMI);
25320fca6ea1SDimitry Andric     }
25330fca6ea1SDimitry Andric   }
25340fca6ea1SDimitry Andric 
25350fca6ea1SDimitry Andric   for (auto I : NewMIMap) {
25360fca6ea1SDimitry Andric     MachineInstr *MI = I.first;
25370fca6ea1SDimitry Andric     int PrologNum = I.second.first;
25380fca6ea1SDimitry Andric     int StageNum = I.second.second;
25390fca6ea1SDimitry Andric     updateInstrUse(MI, StageNum, PrologNum, PrologVRMap, nullptr);
25400fca6ea1SDimitry Andric   }
25410fca6ea1SDimitry Andric 
25420fca6ea1SDimitry Andric   LLVM_DEBUG({
25430fca6ea1SDimitry Andric     dbgs() << "prolog:\n";
25440fca6ea1SDimitry Andric     Prolog->dump();
25450fca6ea1SDimitry Andric   });
25460fca6ea1SDimitry Andric }
25470fca6ea1SDimitry Andric 
25480fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::generateKernel(
25490fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &PrologVRMap,
25500fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &KernelVRMap, InstrMapTy &LastStage0Insts) {
25510fca6ea1SDimitry Andric   KernelVRMap.clear();
25520fca6ea1SDimitry Andric   KernelVRMap.resize(NumUnroll);
25530fca6ea1SDimitry Andric   SmallVector<ValueMapTy> PhiVRMap;
25540fca6ea1SDimitry Andric   PhiVRMap.resize(NumUnroll);
25550fca6ea1SDimitry Andric   DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
25560fca6ea1SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> MIMapLastStage0;
25570fca6ea1SDimitry Andric   for (int UnrollNum = 0; UnrollNum < NumUnroll; ++UnrollNum) {
25580fca6ea1SDimitry Andric     for (MachineInstr *MI : Schedule.getInstructions()) {
25590fca6ea1SDimitry Andric       if (MI->isPHI())
25600fca6ea1SDimitry Andric         continue;
25610fca6ea1SDimitry Andric       int StageNum = Schedule.getStage(MI);
25620fca6ea1SDimitry Andric       MachineInstr *NewMI = cloneInstr(MI);
25630fca6ea1SDimitry Andric       if (UnrollNum == NumUnroll - 1)
25640fca6ea1SDimitry Andric         LastStage0Insts[MI] = NewMI;
25650fca6ea1SDimitry Andric       updateInstrDef(NewMI, KernelVRMap[UnrollNum],
25660fca6ea1SDimitry Andric                      (UnrollNum == NumUnroll - 1 && StageNum == 0));
25670fca6ea1SDimitry Andric       generatePhi(MI, UnrollNum, PrologVRMap, KernelVRMap, PhiVRMap);
25680fca6ea1SDimitry Andric       NewMIMap[NewMI] = {UnrollNum, StageNum};
25690fca6ea1SDimitry Andric       NewKernel->push_back(NewMI);
25700fca6ea1SDimitry Andric     }
25710fca6ea1SDimitry Andric   }
25720fca6ea1SDimitry Andric 
25730fca6ea1SDimitry Andric   for (auto I : NewMIMap) {
25740fca6ea1SDimitry Andric     MachineInstr *MI = I.first;
25750fca6ea1SDimitry Andric     int UnrollNum = I.second.first;
25760fca6ea1SDimitry Andric     int StageNum = I.second.second;
25770fca6ea1SDimitry Andric     updateInstrUse(MI, StageNum, UnrollNum, KernelVRMap, &PhiVRMap);
25780fca6ea1SDimitry Andric   }
25790fca6ea1SDimitry Andric 
25800fca6ea1SDimitry Andric   // If remaining trip count is greater than NumUnroll-1, loop continues
25810fca6ea1SDimitry Andric   insertCondBranch(*NewKernel, NumUnroll - 1, LastStage0Insts, *NewKernel,
25820fca6ea1SDimitry Andric                    *Epilog);
25830fca6ea1SDimitry Andric 
25840fca6ea1SDimitry Andric   LLVM_DEBUG({
25850fca6ea1SDimitry Andric     dbgs() << "kernel:\n";
25860fca6ea1SDimitry Andric     NewKernel->dump();
25870fca6ea1SDimitry Andric   });
25880fca6ea1SDimitry Andric }
25890fca6ea1SDimitry Andric 
25900fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::generateEpilog(
25910fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &KernelVRMap,
25920fca6ea1SDimitry Andric     SmallVectorImpl<ValueMapTy> &EpilogVRMap, InstrMapTy &LastStage0Insts) {
25930fca6ea1SDimitry Andric   EpilogVRMap.clear();
25940fca6ea1SDimitry Andric   EpilogVRMap.resize(Schedule.getNumStages() - 1);
25950fca6ea1SDimitry Andric   DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
25960fca6ea1SDimitry Andric   for (int EpilogNum = 0; EpilogNum < Schedule.getNumStages() - 1;
25970fca6ea1SDimitry Andric        ++EpilogNum) {
25980fca6ea1SDimitry Andric     for (MachineInstr *MI : Schedule.getInstructions()) {
25990fca6ea1SDimitry Andric       if (MI->isPHI())
26000fca6ea1SDimitry Andric         continue;
26010fca6ea1SDimitry Andric       int StageNum = Schedule.getStage(MI);
26020fca6ea1SDimitry Andric       if (StageNum <= EpilogNum)
26030fca6ea1SDimitry Andric         continue;
26040fca6ea1SDimitry Andric       MachineInstr *NewMI = cloneInstr(MI);
26050fca6ea1SDimitry Andric       updateInstrDef(NewMI, EpilogVRMap[EpilogNum], StageNum - 1 == EpilogNum);
26060fca6ea1SDimitry Andric       NewMIMap[NewMI] = {EpilogNum, StageNum};
26070fca6ea1SDimitry Andric       Epilog->push_back(NewMI);
26080fca6ea1SDimitry Andric     }
26090fca6ea1SDimitry Andric   }
26100fca6ea1SDimitry Andric 
26110fca6ea1SDimitry Andric   for (auto I : NewMIMap) {
26120fca6ea1SDimitry Andric     MachineInstr *MI = I.first;
26130fca6ea1SDimitry Andric     int EpilogNum = I.second.first;
26140fca6ea1SDimitry Andric     int StageNum = I.second.second;
26150fca6ea1SDimitry Andric     updateInstrUse(MI, StageNum, EpilogNum, EpilogVRMap, &KernelVRMap);
26160fca6ea1SDimitry Andric   }
26170fca6ea1SDimitry Andric 
26180fca6ea1SDimitry Andric   // If there are remaining iterations, they are executed in the original loop.
26190fca6ea1SDimitry Andric   // Instructions related to loop control, such as loop counter comparison,
26200fca6ea1SDimitry Andric   // are indicated by shouldIgnoreForPipelining() and are assumed to be placed
26210fca6ea1SDimitry Andric   // in stage 0. Thus, the map is for the last one in the kernel.
26220fca6ea1SDimitry Andric   insertCondBranch(*Epilog, 0, LastStage0Insts, *NewPreheader, *NewExit);
26230fca6ea1SDimitry Andric 
26240fca6ea1SDimitry Andric   LLVM_DEBUG({
26250fca6ea1SDimitry Andric     dbgs() << "epilog:\n";
26260fca6ea1SDimitry Andric     Epilog->dump();
26270fca6ea1SDimitry Andric   });
26280fca6ea1SDimitry Andric }
26290fca6ea1SDimitry Andric 
26300fca6ea1SDimitry Andric /// Calculate the number of unroll required and set it to NumUnroll
26310fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::calcNumUnroll() {
26320fca6ea1SDimitry Andric   DenseMap<MachineInstr *, unsigned> Inst2Idx;
26330fca6ea1SDimitry Andric   NumUnroll = 1;
26340fca6ea1SDimitry Andric   for (unsigned I = 0; I < Schedule.getInstructions().size(); ++I)
26350fca6ea1SDimitry Andric     Inst2Idx[Schedule.getInstructions()[I]] = I;
26360fca6ea1SDimitry Andric 
26370fca6ea1SDimitry Andric   for (MachineInstr *MI : Schedule.getInstructions()) {
26380fca6ea1SDimitry Andric     if (MI->isPHI())
26390fca6ea1SDimitry Andric       continue;
26400fca6ea1SDimitry Andric     int StageNum = Schedule.getStage(MI);
26410fca6ea1SDimitry Andric     for (const MachineOperand &MO : MI->uses()) {
26420fca6ea1SDimitry Andric       if (!MO.isReg() || !MO.getReg().isVirtual())
26430fca6ea1SDimitry Andric         continue;
26440fca6ea1SDimitry Andric       MachineInstr *DefMI = MRI.getVRegDef(MO.getReg());
26450fca6ea1SDimitry Andric       if (DefMI->getParent() != OrigKernel)
26460fca6ea1SDimitry Andric         continue;
26470fca6ea1SDimitry Andric 
26480fca6ea1SDimitry Andric       int NumUnrollLocal = 1;
26490fca6ea1SDimitry Andric       if (DefMI->isPHI()) {
26500fca6ea1SDimitry Andric         ++NumUnrollLocal;
26510fca6ea1SDimitry Andric         // canApply() guarantees that DefMI is not phi and is an instruction in
26520fca6ea1SDimitry Andric         // the loop
26530fca6ea1SDimitry Andric         DefMI = MRI.getVRegDef(getLoopPhiReg(*DefMI, OrigKernel));
26540fca6ea1SDimitry Andric       }
26550fca6ea1SDimitry Andric       NumUnrollLocal += StageNum - Schedule.getStage(DefMI);
26560fca6ea1SDimitry Andric       if (Inst2Idx[MI] <= Inst2Idx[DefMI])
26570fca6ea1SDimitry Andric         --NumUnrollLocal;
26580fca6ea1SDimitry Andric       NumUnroll = std::max(NumUnroll, NumUnrollLocal);
26590fca6ea1SDimitry Andric     }
26600fca6ea1SDimitry Andric   }
26610fca6ea1SDimitry Andric   LLVM_DEBUG(dbgs() << "NumUnroll: " << NumUnroll << "\n");
26620fca6ea1SDimitry Andric }
26630fca6ea1SDimitry Andric 
26640fca6ea1SDimitry Andric /// Create new virtual registers for definitions of NewMI and update NewMI.
26650fca6ea1SDimitry Andric /// If the definitions are referenced after the pipelined loop, phis are
26660fca6ea1SDimitry Andric /// created to merge with other routes.
26670fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::updateInstrDef(MachineInstr *NewMI,
26680fca6ea1SDimitry Andric                                                ValueMapTy &VRMap,
26690fca6ea1SDimitry Andric                                                bool LastDef) {
26700fca6ea1SDimitry Andric   for (MachineOperand &MO : NewMI->operands()) {
26710fca6ea1SDimitry Andric     if (!MO.isReg() || !MO.getReg().isVirtual() || !MO.isDef())
26720fca6ea1SDimitry Andric       continue;
26730fca6ea1SDimitry Andric     Register Reg = MO.getReg();
26740fca6ea1SDimitry Andric     const TargetRegisterClass *RC = MRI.getRegClass(Reg);
26750fca6ea1SDimitry Andric     Register NewReg = MRI.createVirtualRegister(RC);
26760fca6ea1SDimitry Andric     MO.setReg(NewReg);
26770fca6ea1SDimitry Andric     VRMap[Reg] = NewReg;
26780fca6ea1SDimitry Andric     if (LastDef)
26790fca6ea1SDimitry Andric       mergeRegUsesAfterPipeline(Reg, NewReg);
26800fca6ea1SDimitry Andric   }
26810fca6ea1SDimitry Andric }
26820fca6ea1SDimitry Andric 
26830fca6ea1SDimitry Andric void ModuloScheduleExpanderMVE::expand() {
26840fca6ea1SDimitry Andric   OrigKernel = Schedule.getLoop()->getTopBlock();
26850fca6ea1SDimitry Andric   OrigPreheader = Schedule.getLoop()->getLoopPreheader();
26860fca6ea1SDimitry Andric   OrigExit = Schedule.getLoop()->getExitBlock();
26870fca6ea1SDimitry Andric 
26880fca6ea1SDimitry Andric   LLVM_DEBUG(Schedule.dump());
26890fca6ea1SDimitry Andric 
26900fca6ea1SDimitry Andric   generatePipelinedLoop();
26910fca6ea1SDimitry Andric }
26920fca6ea1SDimitry Andric 
26930fca6ea1SDimitry Andric /// Check if ModuloScheduleExpanderMVE can be applied to L
26940fca6ea1SDimitry Andric bool ModuloScheduleExpanderMVE::canApply(MachineLoop &L) {
26950fca6ea1SDimitry Andric   if (!L.getExitBlock()) {
26960fca6ea1SDimitry Andric     LLVM_DEBUG(
26970fca6ea1SDimitry Andric         dbgs() << "Can not apply MVE expander: No single exit block.\n";);
26980fca6ea1SDimitry Andric     return false;
26990fca6ea1SDimitry Andric   }
27000fca6ea1SDimitry Andric 
27010fca6ea1SDimitry Andric   MachineBasicBlock *BB = L.getTopBlock();
27020fca6ea1SDimitry Andric   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
27030fca6ea1SDimitry Andric 
27040fca6ea1SDimitry Andric   // Put some constraints on the operands of the phis to simplify the
27050fca6ea1SDimitry Andric   // transformation
27060fca6ea1SDimitry Andric   DenseSet<unsigned> UsedByPhi;
27070fca6ea1SDimitry Andric   for (MachineInstr &MI : BB->phis()) {
27080fca6ea1SDimitry Andric     // Registers defined by phis must be used only inside the loop and be never
27090fca6ea1SDimitry Andric     // used by phis.
27100fca6ea1SDimitry Andric     for (MachineOperand &MO : MI.defs())
27110fca6ea1SDimitry Andric       if (MO.isReg())
27120fca6ea1SDimitry Andric         for (MachineInstr &Ref : MRI.use_instructions(MO.getReg()))
27130fca6ea1SDimitry Andric           if (Ref.getParent() != BB || Ref.isPHI()) {
27140fca6ea1SDimitry Andric             LLVM_DEBUG(dbgs()
27150fca6ea1SDimitry Andric                            << "Can not apply MVE expander: A phi result is "
27160fca6ea1SDimitry Andric                               "referenced outside of the loop or by phi.\n";);
27170fca6ea1SDimitry Andric             return false;
27180fca6ea1SDimitry Andric           }
27190fca6ea1SDimitry Andric 
27200fca6ea1SDimitry Andric     // A source register from the loop block must be defined inside the loop.
27210fca6ea1SDimitry Andric     // A register defined inside the loop must be referenced by only one phi at
27220fca6ea1SDimitry Andric     // most.
27230fca6ea1SDimitry Andric     unsigned InitVal, LoopVal;
27240fca6ea1SDimitry Andric     getPhiRegs(MI, MI.getParent(), InitVal, LoopVal);
27250fca6ea1SDimitry Andric     if (!Register(LoopVal).isVirtual() ||
27260fca6ea1SDimitry Andric         MRI.getVRegDef(LoopVal)->getParent() != BB) {
27270fca6ea1SDimitry Andric       LLVM_DEBUG(
27280fca6ea1SDimitry Andric           dbgs() << "Can not apply MVE expander: A phi source value coming "
27290fca6ea1SDimitry Andric                     "from the loop is not defined in the loop.\n";);
27300fca6ea1SDimitry Andric       return false;
27310fca6ea1SDimitry Andric     }
27320fca6ea1SDimitry Andric     if (UsedByPhi.count(LoopVal)) {
27330fca6ea1SDimitry Andric       LLVM_DEBUG(dbgs() << "Can not apply MVE expander: A value defined in the "
27340fca6ea1SDimitry Andric                            "loop is referenced by two or more phis.\n";);
27350fca6ea1SDimitry Andric       return false;
27360fca6ea1SDimitry Andric     }
27370fca6ea1SDimitry Andric     UsedByPhi.insert(LoopVal);
27380fca6ea1SDimitry Andric   }
27390fca6ea1SDimitry Andric 
27400fca6ea1SDimitry Andric   return true;
27410fca6ea1SDimitry Andric }
27420fca6ea1SDimitry Andric 
27438bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
27448bcb0991SDimitry Andric // ModuloScheduleTestPass implementation
27458bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
27468bcb0991SDimitry Andric // This pass constructs a ModuloSchedule from its module and runs
27478bcb0991SDimitry Andric // ModuloScheduleExpander.
27488bcb0991SDimitry Andric //
27498bcb0991SDimitry Andric // The module is expected to contain a single-block analyzable loop.
27508bcb0991SDimitry Andric // The total order of instructions is taken from the loop as-is.
27518bcb0991SDimitry Andric // Instructions are expected to be annotated with a PostInstrSymbol.
27528bcb0991SDimitry Andric // This PostInstrSymbol must have the following format:
27538bcb0991SDimitry Andric //  "Stage=%d Cycle=%d".
27548bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
27558bcb0991SDimitry Andric 
27568bcb0991SDimitry Andric namespace {
27578bcb0991SDimitry Andric class ModuloScheduleTest : public MachineFunctionPass {
27588bcb0991SDimitry Andric public:
27598bcb0991SDimitry Andric   static char ID;
27608bcb0991SDimitry Andric 
27618bcb0991SDimitry Andric   ModuloScheduleTest() : MachineFunctionPass(ID) {
27628bcb0991SDimitry Andric     initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
27638bcb0991SDimitry Andric   }
27648bcb0991SDimitry Andric 
27658bcb0991SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
27668bcb0991SDimitry Andric   void runOnLoop(MachineFunction &MF, MachineLoop &L);
27678bcb0991SDimitry Andric 
27688bcb0991SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
27690fca6ea1SDimitry Andric     AU.addRequired<MachineLoopInfoWrapperPass>();
27700fca6ea1SDimitry Andric     AU.addRequired<LiveIntervalsWrapperPass>();
27718bcb0991SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
27728bcb0991SDimitry Andric   }
27738bcb0991SDimitry Andric };
27748bcb0991SDimitry Andric } // namespace
27758bcb0991SDimitry Andric 
27768bcb0991SDimitry Andric char ModuloScheduleTest::ID = 0;
27778bcb0991SDimitry Andric 
27788bcb0991SDimitry Andric INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
27798bcb0991SDimitry Andric                       "Modulo Schedule test pass", false, false)
27800fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
27810fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
27828bcb0991SDimitry Andric INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
27838bcb0991SDimitry Andric                     "Modulo Schedule test pass", false, false)
27848bcb0991SDimitry Andric 
27858bcb0991SDimitry Andric bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
27860fca6ea1SDimitry Andric   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
27878bcb0991SDimitry Andric   for (auto *L : MLI) {
27888bcb0991SDimitry Andric     if (L->getTopBlock() != L->getBottomBlock())
27898bcb0991SDimitry Andric       continue;
27908bcb0991SDimitry Andric     runOnLoop(MF, *L);
27918bcb0991SDimitry Andric     return false;
27928bcb0991SDimitry Andric   }
27938bcb0991SDimitry Andric   return false;
27948bcb0991SDimitry Andric }
27958bcb0991SDimitry Andric 
27968bcb0991SDimitry Andric static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
27978bcb0991SDimitry Andric   std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
27988bcb0991SDimitry Andric   std::pair<StringRef, StringRef> StageTokenAndValue =
27998bcb0991SDimitry Andric       getToken(StageAndCycle.first, "-");
28008bcb0991SDimitry Andric   std::pair<StringRef, StringRef> CycleTokenAndValue =
28018bcb0991SDimitry Andric       getToken(StageAndCycle.second, "-");
28028bcb0991SDimitry Andric   if (StageTokenAndValue.first != "Stage" ||
28038bcb0991SDimitry Andric       CycleTokenAndValue.first != "_Cycle") {
28048bcb0991SDimitry Andric     llvm_unreachable(
28058bcb0991SDimitry Andric         "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
28068bcb0991SDimitry Andric     return;
28078bcb0991SDimitry Andric   }
28088bcb0991SDimitry Andric 
28098bcb0991SDimitry Andric   StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
28108bcb0991SDimitry Andric   CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
28118bcb0991SDimitry Andric 
28128bcb0991SDimitry Andric   dbgs() << "  Stage=" << Stage << ", Cycle=" << Cycle << "\n";
28138bcb0991SDimitry Andric }
28148bcb0991SDimitry Andric 
28158bcb0991SDimitry Andric void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
28160fca6ea1SDimitry Andric   LiveIntervals &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
28178bcb0991SDimitry Andric   MachineBasicBlock *BB = L.getTopBlock();
28188bcb0991SDimitry Andric   dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
28198bcb0991SDimitry Andric 
28208bcb0991SDimitry Andric   DenseMap<MachineInstr *, int> Cycle, Stage;
28218bcb0991SDimitry Andric   std::vector<MachineInstr *> Instrs;
28228bcb0991SDimitry Andric   for (MachineInstr &MI : *BB) {
28238bcb0991SDimitry Andric     if (MI.isTerminator())
28248bcb0991SDimitry Andric       continue;
28258bcb0991SDimitry Andric     Instrs.push_back(&MI);
28268bcb0991SDimitry Andric     if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
28278bcb0991SDimitry Andric       dbgs() << "Parsing post-instr symbol for " << MI;
28288bcb0991SDimitry Andric       parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
28298bcb0991SDimitry Andric     }
28308bcb0991SDimitry Andric   }
28318bcb0991SDimitry Andric 
28328bcb0991SDimitry Andric   ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
28338bcb0991SDimitry Andric                     std::move(Stage));
28348bcb0991SDimitry Andric   ModuloScheduleExpander MSE(
28358bcb0991SDimitry Andric       MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
28368bcb0991SDimitry Andric   MSE.expand();
28378bcb0991SDimitry Andric   MSE.cleanup();
28388bcb0991SDimitry Andric }
28398bcb0991SDimitry Andric 
28408bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
28418bcb0991SDimitry Andric // ModuloScheduleTestAnnotater implementation
28428bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
28438bcb0991SDimitry Andric 
28448bcb0991SDimitry Andric void ModuloScheduleTestAnnotater::annotate() {
28458bcb0991SDimitry Andric   for (MachineInstr *MI : S.getInstructions()) {
28468bcb0991SDimitry Andric     SmallVector<char, 16> SV;
28478bcb0991SDimitry Andric     raw_svector_ostream OS(SV);
28488bcb0991SDimitry Andric     OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
28498bcb0991SDimitry Andric     MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
28508bcb0991SDimitry Andric     MI->setPostInstrSymbol(MF, Sym);
28518bcb0991SDimitry Andric   }
28528bcb0991SDimitry Andric }
2853