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