LLVM 24.0.0git
ModuloSchedule.cpp
Go to the documentation of this file.
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
10#include "CodeGenOptions.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/Support/Debug.h"
23
24#define DEBUG_TYPE "pipeliner"
25using namespace llvm;
26
29 for (MachineInstr &MI : *MBB)
31 MBB->clear();
32
34 while (!MBB->succ_empty()) {
35 Updates.push_back({MachineDominatorTree::Delete, MBB, *MBB->succ_begin()});
36 MBB->removeSuccessor(MBB->succ_begin());
37 }
38
39 MDTU.applyUpdates(Updates);
40 MDTU.deleteBB(MBB);
41}
42
44 for (MachineInstr *MI : ScheduledInstrs)
45 OS << "[stage " << getStage(MI) << " @" << getCycle(MI) << "c] " << *MI;
46}
47
48//===----------------------------------------------------------------------===//
49// ModuloScheduleExpander implementation
50//===----------------------------------------------------------------------===//
51
52/// Return the register values for the operands of a Phi instruction.
53/// This function assume the instruction is a Phi.
55 Register &InitVal, Register &LoopVal) {
56 assert(Phi.isPHI() && "Expecting a Phi.");
57
58 InitVal = Register();
59 LoopVal = Register();
60 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
61 if (Phi.getOperand(i + 1).getMBB() != Loop)
62 InitVal = Phi.getOperand(i).getReg();
63 else
64 LoopVal = Phi.getOperand(i).getReg();
65
66 assert(InitVal && LoopVal && "Unexpected Phi structure.");
67}
68
69/// Return the Phi register value that comes from the incoming block.
71 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
72 if (Phi.getOperand(i + 1).getMBB() != LoopBB)
73 return Phi.getOperand(i).getReg();
74 return Register();
75}
76
77/// Return the Phi register value that comes the loop block.
79 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
80 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
81 return Phi.getOperand(i).getReg();
82 return Register();
83}
84
86 BB = Schedule.getLoop()->getTopBlock();
87 Preheader = *BB->pred_begin();
88 if (Preheader == BB)
89 Preheader = *std::next(BB->pred_begin());
90
91 // Iterate over the definitions in each instruction, and compute the
92 // stage difference for each use. Keep the maximum value.
93 for (MachineInstr *MI : Schedule.getInstructions()) {
94 int DefStage = Schedule.getStage(MI);
95 for (const MachineOperand &Op : MI->all_defs()) {
96 Register Reg = Op.getReg();
97 unsigned MaxDiff = 0;
98 bool PhiIsSwapped = false;
99 for (MachineInstr &UseMI : MRI.use_instructions(Reg)) {
100 int UseStage = Schedule.getStage(&UseMI);
101 unsigned Diff = 0;
102 if (UseStage != -1 && UseStage >= DefStage)
103 Diff = UseStage - DefStage;
104 if (MI->isPHI()) {
105 if (isLoopCarried(*MI))
106 ++Diff;
107 else
108 PhiIsSwapped = true;
109 }
110 MaxDiff = std::max(Diff, MaxDiff);
111 }
112 RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
113 }
114 }
115
116 generatePipelinedLoop();
117}
118
119void ModuloScheduleExpander::generatePipelinedLoop() {
120 LoopInfo = TII->analyzeLoopForPipelining(BB);
121 assert(LoopInfo && "Must be able to analyze loop!");
122
123 // Create a new basic block for the kernel and add it to the CFG.
125
126 unsigned MaxStageCount = Schedule.getNumStages() - 1;
127
128 // Remember the registers that are used in different stages. The index is
129 // the iteration, or stage, that the instruction is scheduled in. This is
130 // a map between register names in the original block and the names created
131 // in each stage of the pipelined loop.
132 ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
133
134 // The renaming destination by Phis for the registers across stages.
135 // This map is updated during Phis generation to point to the most recent
136 // renaming destination.
137 ValueMapTy *VRMapPhi = new ValueMapTy[(MaxStageCount + 1) * 2];
138
139 InstrMapTy InstrMap;
140
142
143 // Generate the prolog instructions that set up the pipeline.
144 generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
145 MF.insert(BB->getIterator(), KernelBB);
146 LIS.insertMBBInMaps(KernelBB);
147
148 // Rearrange the instructions to generate the new, pipelined loop,
149 // and update register names as needed.
150 for (MachineInstr *CI : Schedule.getInstructions()) {
151 if (CI->isPHI())
152 continue;
153 unsigned StageNum = Schedule.getStage(CI);
154 MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
155 updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
156 KernelBB->push_back(NewMI);
157 LIS.InsertMachineInstrInMaps(*NewMI);
158 InstrMap[NewMI] = CI;
159 }
160
161 // Copy any terminator instructions to the new kernel, and update
162 // names as needed.
163 for (MachineInstr &MI : BB->terminators()) {
164 MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
165 updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
166 KernelBB->push_back(NewMI);
167 LIS.InsertMachineInstrInMaps(*NewMI);
168 InstrMap[NewMI] = &MI;
169 }
170
171 NewKernel = KernelBB;
172 KernelBB->transferSuccessors(BB);
173 KernelBB->replaceSuccessor(BB, KernelBB);
174
176 {MachineDominatorTree::Insert, PrologBBs.back(), KernelBB}};
177 for (MachineBasicBlock *Succ : KernelBB->successors())
178 Updates.push_back({MachineDominatorTree::Insert, KernelBB, Succ});
179
180 Updates.push_back({MachineDominatorTree::Delete, PrologBBs.back(), BB});
181
182 for (MachineBasicBlock *Succ : KernelBB->successors()) {
183 Updates.push_back(
184 {MachineDominatorTree::Delete, BB, Succ == KernelBB ? BB : Succ});
185 }
186
187 MDTU.applyUpdates(Updates);
188
189 generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
190 VRMapPhi, InstrMap, MaxStageCount, MaxStageCount, false);
191 generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, VRMapPhi,
192 InstrMap, MaxStageCount, MaxStageCount, false);
193
194 LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
195
196 SmallVector<MachineBasicBlock *, 4> EpilogBBs;
197 // Generate the epilog instructions to complete the pipeline.
198 generateEpilog(MaxStageCount, KernelBB, BB, VRMap, VRMapPhi, EpilogBBs,
199 PrologBBs);
200
201 // We need this step because the register allocation doesn't handle some
202 // situations well, so we insert copies to help out.
203 splitLifetimes(KernelBB, EpilogBBs);
204
205 // Remove dead instructions due to loop induction variables.
206 removeDeadInstructions(KernelBB, EpilogBBs);
207
208 // Add branches between prolog and epilog blocks.
209 addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
210
211 delete[] VRMap;
212 delete[] VRMapPhi;
213}
214
216 // Remove the original loop since it's no longer referenced.
217 eraseBlock(BB, LIS, MDTU);
218}
219
220/// Generate the pipeline prolog code.
221void ModuloScheduleExpander::generateProlog(unsigned LastStage,
222 MachineBasicBlock *KernelBB,
223 ValueMapTy *VRMap,
224 MBBVectorTy &PrologBBs) {
225 MachineBasicBlock *PredBB = Preheader;
226 InstrMapTy InstrMap;
227
228 // Generate a basic block for each stage, not including the last stage,
229 // which will be generated in the kernel. Each basic block may contain
230 // instructions from multiple stages/iterations.
231 for (unsigned i = 0; i < LastStage; ++i) {
232 // Create and insert the prolog basic block prior to the original loop
233 // basic block. The original loop is removed later.
235 PrologBBs.push_back(NewBB);
236 MF.insert(BB->getIterator(), NewBB);
237 NewBB->transferSuccessors(PredBB);
238 PredBB->addSuccessor(NewBB);
239 MDTU.splitCriticalEdge(PredBB, BB, NewBB);
240 PredBB = NewBB;
241 LIS.insertMBBInMaps(NewBB);
242
243 // Generate instructions for each appropriate stage. Process instructions
244 // in original program order.
245 for (int StageNum = i; StageNum >= 0; --StageNum) {
247 BBE = BB->getFirstTerminator();
248 BBI != BBE; ++BBI) {
249 if (Schedule.getStage(&*BBI) == StageNum) {
250 if (BBI->isPHI())
251 continue;
252 MachineInstr *NewMI =
253 cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
254 updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
255 NewBB->push_back(NewMI);
256 LIS.InsertMachineInstrInMaps(*NewMI);
257 InstrMap[NewMI] = &*BBI;
258 }
259 }
260 }
261 rewritePhiValues(NewBB, i, VRMap, InstrMap);
262 LLVM_DEBUG({
263 dbgs() << "prolog:\n";
264 NewBB->dump();
265 });
266 }
267
268 PredBB->replaceSuccessor(BB, KernelBB);
269
270 // Check if we need to remove the branch from the preheader to the original
271 // loop, and replace it with a branch to the new loop.
272 unsigned numBranches = TII->removeBranch(*Preheader);
273 if (numBranches) {
275 TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
276 }
277}
278
279/// Generate the pipeline epilog code. The epilog code finishes the iterations
280/// that were started in either the prolog or the kernel. We create a basic
281/// block for each stage that needs to complete.
282void ModuloScheduleExpander::generateEpilog(
283 unsigned LastStage, MachineBasicBlock *KernelBB, MachineBasicBlock *OrigBB,
284 ValueMapTy *VRMap, ValueMapTy *VRMapPhi, MBBVectorTy &EpilogBBs,
285 MBBVectorTy &PrologBBs) {
286 // We need to change the branch from the kernel to the first epilog block, so
287 // this call to analyze branch uses the kernel rather than the original BB.
288 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
289 SmallVector<MachineOperand, 4> Cond;
290 bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
291 assert(!checkBranch && "generateEpilog must be able to analyze the branch");
292 if (checkBranch)
293 return;
294
295 MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
296 if (*LoopExitI == KernelBB)
297 ++LoopExitI;
298 assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
299 MachineBasicBlock *LoopExitBB = *LoopExitI;
300
301 MachineBasicBlock *PredBB = KernelBB;
302 MachineBasicBlock *EpilogStart = LoopExitBB;
303 InstrMapTy InstrMap;
304
305 // Generate a basic block for each stage, not including the last stage,
306 // which was generated for the kernel. Each basic block may contain
307 // instructions from multiple stages/iterations.
308 int EpilogStage = LastStage + 1;
309 for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
310 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
311 EpilogBBs.push_back(NewBB);
312 MF.insert(BB->getIterator(), NewBB);
313
314 PredBB->replaceSuccessor(LoopExitBB, NewBB);
315 NewBB->addSuccessor(LoopExitBB);
316 MDTU.splitCriticalEdge(PredBB, LoopExitBB, NewBB);
317 LIS.insertMBBInMaps(NewBB);
318
319 if (EpilogStart == LoopExitBB)
320 EpilogStart = NewBB;
321
322 // Add instructions to the epilog depending on the current block.
323 // Process instructions in original program order.
324 for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
325 for (auto &BBI : *BB) {
326 if (BBI.isPHI())
327 continue;
328 MachineInstr *In = &BBI;
329 if ((unsigned)Schedule.getStage(In) == StageNum) {
330 // Instructions with memoperands in the epilog are updated with
331 // conservative values.
332 MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
333 updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
334 NewBB->push_back(NewMI);
335 LIS.InsertMachineInstrInMaps(*NewMI);
336 InstrMap[NewMI] = In;
337 }
338 }
339 }
340 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
341 VRMapPhi, InstrMap, LastStage, EpilogStage, i == 1);
342 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, VRMapPhi,
343 InstrMap, LastStage, EpilogStage, i == 1);
344 PredBB = NewBB;
345
346 LLVM_DEBUG({
347 dbgs() << "epilog:\n";
348 NewBB->dump();
349 });
350 }
351
352 // Fix any Phi nodes in the loop exit block.
353 LoopExitBB->replacePhiUsesWith(BB, PredBB);
354
355 // Create a branch to the new epilog from the kernel.
356 // Remove the original branch and add a new branch to the epilog.
357 TII->removeBranch(*KernelBB);
358 assert((OrigBB == TBB || OrigBB == FBB) &&
359 "Unable to determine looping branch direction");
360 if (OrigBB != TBB)
361 TII->insertBranch(*KernelBB, EpilogStart, KernelBB, Cond, DebugLoc());
362 else
363 TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
364 // Add a branch to the loop exit.
365 if (EpilogBBs.size() > 0) {
366 MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
367 SmallVector<MachineOperand, 4> Cond1;
368 TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
369 }
370}
371
372/// Replace all uses of FromReg that appear outside the specified
373/// basic block with ToReg.
374static void replaceRegUsesAfterLoop(Register FromReg, Register ToReg,
377 for (MachineOperand &O :
378 llvm::make_early_inc_range(MRI.use_operands(FromReg)))
379 if (O.getParent()->getParent() != MBB)
380 O.setReg(ToReg);
381}
382
383/// Return true if the register has a use that occurs outside the
384/// specified loop.
387 for (const MachineInstr &UseMI : MRI.use_instructions(Reg))
388 if (UseMI.getParent() != BB)
389 return true;
390 return false;
391}
392
393/// Generate Phis for the specific block in the generated pipelined code.
394/// This function looks at the Phis from the original code to guide the
395/// creation of new Phis.
396void ModuloScheduleExpander::generateExistingPhis(
398 MachineBasicBlock *KernelBB, ValueMapTy *VRMap, ValueMapTy *VRMapPhi,
399 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
400 bool IsLast) {
401 // Compute the stage number for the initial value of the Phi, which
402 // comes from the prolog. The prolog to use depends on to which kernel/
403 // epilog that we're adding the Phi.
404 unsigned PrologStage = 0;
405 unsigned PrevStage = 0;
406 bool InKernel = (LastStageNum == CurStageNum);
407 if (InKernel) {
408 PrologStage = LastStageNum - 1;
409 PrevStage = CurStageNum;
410 } else {
411 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
412 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
413 }
414
415 for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
416 BBE = BB->getFirstNonPHI();
417 BBI != BBE; ++BBI) {
418 Register Def = BBI->getOperand(0).getReg();
419
420 Register InitVal;
421 Register LoopVal;
422 getPhiRegs(*BBI, BB, InitVal, LoopVal);
423
424 Register PhiOp1;
425 // The Phi value from the loop body typically is defined in the loop, but
426 // not always. So, we need to check if the value is defined in the loop.
427 Register PhiOp2 = LoopVal;
428 if (auto It = VRMap[LastStageNum].find(LoopVal);
429 It != VRMap[LastStageNum].end())
430 PhiOp2 = It->second;
431
432 int StageScheduled = Schedule.getStage(&*BBI);
433 int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
434 unsigned NumStages = getStagesForReg(Def, CurStageNum);
435 if (NumStages == 0) {
436 // We don't need to generate a Phi anymore, but we need to rename any uses
437 // of the Phi value.
438 Register NewReg = VRMap[PrevStage][LoopVal];
439 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
440 InitVal, NewReg);
441 auto It = VRMap[CurStageNum].find(LoopVal);
442 if (It != VRMap[CurStageNum].end()) {
443 Register Reg = It->second;
444 VRMap[CurStageNum][Def] = Reg;
445 }
446 }
447 // Adjust the number of Phis needed depending on the number of prologs left,
448 // and the distance from where the Phi is first scheduled. The number of
449 // Phis cannot exceed the number of prolog stages. Each stage can
450 // potentially define two values.
451 unsigned MaxPhis = PrologStage + 2;
452 if (!InKernel && (int)PrologStage <= LoopValStage)
453 MaxPhis = std::max((int)MaxPhis - LoopValStage, 1);
454 unsigned NumPhis = std::min(NumStages, MaxPhis);
455
456 Register NewReg;
457 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
458 // In the epilog, we may need to look back one stage to get the correct
459 // Phi name, because the epilog and prolog blocks execute the same stage.
460 // The correct name is from the previous block only when the Phi has
461 // been completely scheduled prior to the epilog, and Phi value is not
462 // needed in multiple stages.
463 int StageDiff = 0;
464 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
465 NumPhis == 1)
466 StageDiff = 1;
467 // Adjust the computations below when the phi and the loop definition
468 // are scheduled in different stages.
469 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
470 StageDiff = StageScheduled - LoopValStage;
471 for (unsigned np = 0; np < NumPhis; ++np) {
472 // If the Phi hasn't been scheduled, then use the initial Phi operand
473 // value. Otherwise, use the scheduled version of the instruction. This
474 // is a little complicated when a Phi references another Phi.
475 if (np > PrologStage || StageScheduled >= (int)LastStageNum)
476 PhiOp1 = InitVal;
477 // Check if the Phi has already been scheduled in a prolog stage.
478 else if (PrologStage >= AccessStage + StageDiff + np &&
479 VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
480 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
481 // Check if the Phi has already been scheduled, but the loop instruction
482 // is either another Phi, or doesn't occur in the loop.
483 else if (PrologStage >= AccessStage + StageDiff + np) {
484 // If the Phi references another Phi, we need to examine the other
485 // Phi to get the correct value.
486 PhiOp1 = LoopVal;
487 MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
488 int Indirects = 1;
489 while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
490 int PhiStage = Schedule.getStage(InstOp1);
491 if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
492 PhiOp1 = getInitPhiReg(*InstOp1, BB);
493 else
494 PhiOp1 = getLoopPhiReg(*InstOp1, BB);
495 InstOp1 = MRI.getVRegDef(PhiOp1);
496 int PhiOpStage = Schedule.getStage(InstOp1);
497 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
498 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np) {
499 auto &M = VRMap[PrologStage - StageAdj - Indirects - np];
500 if (auto It = M.find(PhiOp1); It != M.end()) {
501 PhiOp1 = It->second;
502 break;
503 }
504 }
505 ++Indirects;
506 }
507 } else
508 PhiOp1 = InitVal;
509 // If this references a generated Phi in the kernel, get the Phi operand
510 // from the incoming block.
511 if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
512 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
513 PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
514
515 MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
516 bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
517 // In the epilog, a map lookup is needed to get the value from the kernel,
518 // or previous epilog block. How is does this depends on if the
519 // instruction is scheduled in the previous block.
520 if (!InKernel) {
521 int StageDiffAdj = 0;
522 if (LoopValStage != -1 && StageScheduled > LoopValStage)
523 StageDiffAdj = StageScheduled - LoopValStage;
524 // Use the loop value defined in the kernel, unless the kernel
525 // contains the last definition of the Phi.
526 if (np == 0 && PrevStage == LastStageNum &&
527 (StageScheduled != 0 || LoopValStage != 0) &&
528 getMapPhiReg(VRMap, VRMapPhi, PrevStage - StageDiffAdj, LoopVal))
529 PhiOp2 =
530 getMapPhiReg(VRMap, VRMapPhi, PrevStage - StageDiffAdj, LoopVal);
531 // Use the value defined by the Phi. We add one because we switch
532 // from looking at the loop value to the Phi definition.
533 else if (np > 0 && PrevStage == LastStageNum &&
534 getMapPhiReg(VRMap, VRMapPhi, PrevStage - np + 1, Def))
535 PhiOp2 = getMapPhiReg(VRMap, VRMapPhi, PrevStage - np + 1, Def);
536 // Use the loop value defined in the kernel.
537 else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
538 getMapPhiReg(VRMap, VRMapPhi, PrevStage - StageDiffAdj - np,
539 LoopVal))
540 PhiOp2 = getMapPhiReg(VRMap, VRMapPhi, PrevStage - StageDiffAdj - np,
541 LoopVal);
542 // Use the value defined by the Phi, unless we're generating the first
543 // epilog and the Phi refers to a Phi in a different stage.
544 else if (getMapPhiReg(VRMap, VRMapPhi, PrevStage - np, Def) &&
545 (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
546 (LoopValStage == StageScheduled)))
547 PhiOp2 = getMapPhiReg(VRMap, VRMapPhi, PrevStage - np, Def);
548 }
549
550 // Check if we can reuse an existing Phi. This occurs when a Phi
551 // references another Phi, and the other Phi is scheduled in an
552 // earlier stage. We can try to reuse an existing Phi up until the last
553 // stage of the current Phi.
554 if (LoopDefIsPhi) {
555 if (static_cast<int>(PrologStage - np) >= StageScheduled) {
556 int LVNumStages = getStagesForPhi(LoopVal);
557 int StageDiff = (StageScheduled - LoopValStage);
558 LVNumStages -= StageDiff;
559 // Make sure the loop value Phi has been processed already.
560 if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
561 NewReg = PhiOp2;
562 unsigned ReuseStage = CurStageNum;
563 if (isLoopCarried(*PhiInst))
564 ReuseStage -= LVNumStages;
565 // Check if the Phi to reuse has been generated yet. If not, then
566 // there is nothing to reuse.
567 if (VRMap[ReuseStage - np].count(LoopVal)) {
568 NewReg = VRMap[ReuseStage - np][LoopVal];
569
570 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
571 Def, NewReg);
572 // Update the map with the new Phi name.
573 VRMap[CurStageNum - np][Def] = NewReg;
574 PhiOp2 = NewReg;
575 if (VRMap[LastStageNum - np - 1].count(LoopVal))
576 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
577
578 if (IsLast && np == NumPhis - 1)
579 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI);
580 continue;
581 }
582 }
583 }
584 if (InKernel && StageDiff > 0 &&
585 VRMap[CurStageNum - StageDiff - np].count(LoopVal))
586 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
587 }
588
589 const TargetRegisterClass *RC = MRI.getRegClass(Def);
590 NewReg = MRI.createVirtualRegister(RC);
591
592 MachineInstrBuilder NewPhi =
593 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
594 TII->get(TargetOpcode::PHI), NewReg);
595 NewPhi.addReg(PhiOp1).addMBB(BB1);
596 NewPhi.addReg(PhiOp2).addMBB(BB2);
597 LIS.InsertMachineInstrInMaps(*NewPhi);
598 if (np == 0)
599 InstrMap[NewPhi] = &*BBI;
600
601 // We define the Phis after creating the new pipelined code, so
602 // we need to rename the Phi values in scheduled instructions.
603
604 Register PrevReg;
605 if (InKernel && VRMap[PrevStage - np].count(LoopVal))
606 PrevReg = VRMap[PrevStage - np][LoopVal];
607 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
608 NewReg, PrevReg);
609 // If the Phi has been scheduled, use the new name for rewriting.
610 if (VRMap[CurStageNum - np].count(Def)) {
611 Register R = VRMap[CurStageNum - np][Def];
612 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
613 NewReg);
614 }
615
616 // Check if we need to rename any uses that occurs after the loop. The
617 // register to replace depends on whether the Phi is scheduled in the
618 // epilog.
619 if (IsLast && np == NumPhis - 1)
620 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI);
621
622 // In the kernel, a dependent Phi uses the value from this Phi.
623 if (InKernel)
624 PhiOp2 = NewReg;
625
626 // Update the map with the new Phi name.
627 VRMap[CurStageNum - np][Def] = NewReg;
628 }
629
630 while (NumPhis++ < NumStages) {
631 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
632 NewReg, 0);
633 }
634
635 // Check if we need to rename a Phi that has been eliminated due to
636 // scheduling.
637 if (NumStages == 0 && IsLast) {
638 auto &CurStageMap = VRMap[CurStageNum];
639 auto It = CurStageMap.find(LoopVal);
640 if (It != CurStageMap.end())
641 replaceRegUsesAfterLoop(Def, It->second, BB, MRI);
642 }
643 }
644}
645
646/// Generate Phis for the specified block in the generated pipelined code.
647/// These are new Phis needed because the definition is scheduled after the
648/// use in the pipelined sequence.
649void ModuloScheduleExpander::generatePhis(
651 MachineBasicBlock *KernelBB, ValueMapTy *VRMap, ValueMapTy *VRMapPhi,
652 InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
653 bool IsLast) {
654 // Compute the stage number that contains the initial Phi value, and
655 // the Phi from the previous stage.
656 unsigned PrologStage = 0;
657 unsigned PrevStage = 0;
658 unsigned StageDiff = CurStageNum - LastStageNum;
659 bool InKernel = (StageDiff == 0);
660 if (InKernel) {
661 PrologStage = LastStageNum - 1;
662 PrevStage = CurStageNum;
663 } else {
664 PrologStage = LastStageNum - StageDiff;
665 PrevStage = LastStageNum + StageDiff - 1;
666 }
667
668 for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
669 BBE = BB->instr_end();
670 BBI != BBE; ++BBI) {
671 for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
672 MachineOperand &MO = BBI->getOperand(i);
673 if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
674 continue;
675
676 int StageScheduled = Schedule.getStage(&*BBI);
677 assert(StageScheduled != -1 && "Expecting scheduled instruction.");
678 Register Def = MO.getReg();
679 unsigned NumPhis = getStagesForReg(Def, CurStageNum);
680 // An instruction scheduled in stage 0 and is used after the loop
681 // requires a phi in the epilog for the last definition from either
682 // the kernel or prolog.
683 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
684 hasUseAfterLoop(Def, BB, MRI))
685 NumPhis = 1;
686 if (!InKernel && (unsigned)StageScheduled > PrologStage)
687 continue;
688
689 Register PhiOp2;
690 if (InKernel) {
691 PhiOp2 = VRMap[PrevStage][Def];
692 if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
693 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
694 PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
695 }
696 // The number of Phis can't exceed the number of prolog stages. The
697 // prolog stage number is zero based.
698 if (NumPhis > PrologStage + 1 - StageScheduled)
699 NumPhis = PrologStage + 1 - StageScheduled;
700 for (unsigned np = 0; np < NumPhis; ++np) {
701 // Example for
702 // Org:
703 // %Org = ... (Scheduled at Stage#0, NumPhi = 2)
704 //
705 // Prolog0 (Stage0):
706 // %Clone0 = ...
707 // Prolog1 (Stage1):
708 // %Clone1 = ...
709 // Kernel (Stage2):
710 // %Phi0 = Phi %Clone1, Prolog1, %Clone2, Kernel
711 // %Phi1 = Phi %Clone0, Prolog1, %Phi0, Kernel
712 // %Clone2 = ...
713 // Epilog0 (Stage3):
714 // %Phi2 = Phi %Clone1, Prolog1, %Clone2, Kernel
715 // %Phi3 = Phi %Clone0, Prolog1, %Phi0, Kernel
716 // Epilog1 (Stage4):
717 // %Phi4 = Phi %Clone0, Prolog0, %Phi2, Epilog0
718 //
719 // VRMap = {0: %Clone0, 1: %Clone1, 2: %Clone2}
720 // VRMapPhi (after Kernel) = {0: %Phi1, 1: %Phi0}
721 // VRMapPhi (after Epilog0) = {0: %Phi3, 1: %Phi2}
722
723 Register PhiOp1 = VRMap[PrologStage][Def];
724 if (np <= PrologStage)
725 PhiOp1 = VRMap[PrologStage - np][Def];
726 if (!InKernel) {
727 if (PrevStage == LastStageNum && np == 0)
728 PhiOp2 = VRMap[LastStageNum][Def];
729 else
730 PhiOp2 = VRMapPhi[PrevStage - np][Def];
731 }
732
733 const TargetRegisterClass *RC = MRI.getRegClass(Def);
734 Register NewReg = MRI.createVirtualRegister(RC);
735
736 MachineInstrBuilder NewPhi =
737 BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
738 TII->get(TargetOpcode::PHI), NewReg);
739 NewPhi.addReg(PhiOp1).addMBB(BB1);
740 NewPhi.addReg(PhiOp2).addMBB(BB2);
741 LIS.InsertMachineInstrInMaps(*NewPhi);
742 if (np == 0)
743 InstrMap[NewPhi] = &*BBI;
744
745 // Rewrite uses and update the map. The actions depend upon whether
746 // we generating code for the kernel or epilog blocks.
747 if (InKernel) {
748 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
749 NewReg);
750 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
751 NewReg);
752
753 PhiOp2 = NewReg;
754 VRMapPhi[PrevStage - np - 1][Def] = NewReg;
755 } else {
756 VRMapPhi[CurStageNum - np][Def] = NewReg;
757 if (np == NumPhis - 1)
758 rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
759 NewReg);
760 }
761 if (IsLast && np == NumPhis - 1)
762 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI);
763 }
764 }
765 }
766}
767
768/// Remove instructions that generate values with no uses.
769/// Typically, these are induction variable operations that generate values
770/// used in the loop itself. A dead instruction has a definition with
771/// no uses, or uses that occur in the original loop only.
772void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
773 MBBVectorTy &EpilogBBs) {
774 // For each epilog block, check that the value defined by each instruction
775 // is used. If not, delete it.
776 for (MachineBasicBlock *MBB : llvm::reverse(EpilogBBs))
778 ME = MBB->instr_rend();
779 MI != ME;) {
780 // From DeadMachineInstructionElem. Don't delete inline assembly.
781 if (MI->isInlineAsm()) {
782 ++MI;
783 continue;
784 }
785 bool SawStore = false;
786 // Check if it's safe to remove the instruction due to side effects.
787 // We can, and want to, remove Phis here.
788 if (!MI->isSafeToMove(SawStore) && !MI->isPHI()) {
789 ++MI;
790 continue;
791 }
792 bool used = true;
793 for (const MachineOperand &MO : MI->all_defs()) {
794 Register reg = MO.getReg();
795 // Assume physical registers are used, unless they are marked dead.
796 if (reg.isPhysical()) {
797 used = !MO.isDead();
798 if (used)
799 break;
800 continue;
801 }
802 unsigned realUses = 0;
803 for (const MachineInstr &UseMI : MRI.use_instructions(reg)) {
804 // Check if there are any uses that occur only in the original
805 // loop. If so, that's not a real use.
806 if (UseMI.getParent() != BB) {
807 realUses++;
808 used = true;
809 break;
810 }
811 }
812 if (realUses > 0)
813 break;
814 used = false;
815 }
816 if (!used) {
817 LIS.RemoveMachineInstrFromMaps(*MI);
818 MI++->eraseFromParent();
819 continue;
820 }
821 ++MI;
822 }
823 // In the kernel block, check if we can remove a Phi that generates a value
824 // used in an instruction removed in the epilog block.
825 for (MachineInstr &MI : llvm::make_early_inc_range(KernelBB->phis())) {
826 Register reg = MI.getOperand(0).getReg();
827 if (MRI.use_begin(reg) == MRI.use_end()) {
828 LIS.RemoveMachineInstrFromMaps(MI);
829 MI.eraseFromParent();
830 }
831 }
832}
833
834/// For loop carried definitions, we split the lifetime of a virtual register
835/// that has uses past the definition in the next iteration. A copy with a new
836/// virtual register is inserted before the definition, which helps with
837/// generating a better register assignment.
838///
839/// v1 = phi(a, v2) v1 = phi(a, v2)
840/// v2 = phi(b, v3) v2 = phi(b, v3)
841/// v3 = .. v4 = copy v1
842/// .. = V1 v3 = ..
843/// .. = v4
844void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
845 MBBVectorTy &EpilogBBs) {
846 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
847 for (auto &PHI : KernelBB->phis()) {
848 Register Def = PHI.getOperand(0).getReg();
849 // Check for any Phi definition that used as an operand of another Phi
850 // in the same block.
851 for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
852 E = MRI.use_instr_end();
853 I != E; ++I) {
854 if (I->isPHI() && I->getParent() == KernelBB) {
855 // Get the loop carried definition.
856 Register LCDef = getLoopPhiReg(PHI, KernelBB);
857 if (!LCDef)
858 continue;
859 MachineInstr *MI = MRI.getVRegDef(LCDef);
860 if (!MI || MI->getParent() != KernelBB || MI->isPHI())
861 continue;
862 // Search through the rest of the block looking for uses of the Phi
863 // definition. If one occurs, then split the lifetime.
864 Register SplitReg;
866 KernelBB->instr_end()))
867 if (BBJ.readsRegister(Def, /*TRI=*/nullptr)) {
868 // We split the lifetime when we find the first use.
869 if (!SplitReg) {
870 SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
871 MachineInstr *newCopy =
872 BuildMI(*KernelBB, MI, MI->getDebugLoc(),
873 TII->get(TargetOpcode::COPY), SplitReg)
874 .addReg(Def);
875 LIS.InsertMachineInstrInMaps(*newCopy);
876 }
877 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
878 }
879 if (!SplitReg)
880 continue;
881 // Search through each of the epilog blocks for any uses to be renamed.
882 for (auto &Epilog : EpilogBBs)
883 for (auto &I : *Epilog)
884 if (I.readsRegister(Def, /*TRI=*/nullptr))
885 I.substituteRegister(Def, SplitReg, 0, *TRI);
886 break;
887 }
888 }
889 }
890}
891
892/// Create branches from each prolog basic block to the appropriate epilog
893/// block. These edges are needed if the loop ends before reaching the
894/// kernel.
895void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
896 MBBVectorTy &PrologBBs,
897 MachineBasicBlock *KernelBB,
898 MBBVectorTy &EpilogBBs,
899 ValueMapTy *VRMap) {
900 assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
901 MachineBasicBlock *LastPro = KernelBB;
902 MachineBasicBlock *LastEpi = KernelBB;
903
904 // Start from the blocks connected to the kernel and work "out"
905 // to the first prolog and the last epilog blocks.
906 unsigned MaxIter = PrologBBs.size() - 1;
907 for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
908 // Add branches to the prolog that go to the corresponding
909 // epilog, and the fall-thru prolog/kernel block.
910 MachineBasicBlock *Prolog = PrologBBs[j];
911 MachineBasicBlock *Epilog = EpilogBBs[i];
912
913 SmallVector<MachineOperand, 4> Cond;
914 std::optional<bool> StaticallyGreater =
915 LoopInfo->createTripCountGreaterCondition(j + 1, *Prolog, Cond);
916 unsigned numAdded = 0;
917 if (!StaticallyGreater) {
918 Prolog->addSuccessor(Epilog);
919 MDTU.applyUpdates({{MachineDominatorTree::Insert, Prolog, Epilog}});
920 numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
921 } else if (*StaticallyGreater == false) {
922 Prolog->addSuccessor(Epilog);
923 Prolog->removeSuccessor(LastPro);
924 LastEpi->removeSuccessor(Epilog);
925 MDTU.applyUpdates({{MachineDominatorTree::Insert, Prolog, Epilog},
928 numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
929 Epilog->removePHIsIncomingValuesForPredecessor(*LastEpi);
930 // Remove the blocks that are no longer referenced.
931 if (LastPro == KernelBB) {
932 LoopInfo->disposed(&LIS);
933 NewKernel = nullptr;
934 }
935 eraseBlock(LastPro, LIS, MDTU);
936 if (LastPro != LastEpi)
937 eraseBlock(LastEpi, LIS, MDTU);
938 } else {
939 numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
940 Epilog->removePHIsIncomingValuesForPredecessor(*Prolog);
941 }
942 LastPro = Prolog;
943 LastEpi = Epilog;
945 E = Prolog->instr_rend();
946 I != E && numAdded > 0; ++I, --numAdded)
947 updateInstruction(&*I, false, j, 0, VRMap);
948 }
949
950 if (NewKernel) {
951 LoopInfo->setPreheader(PrologBBs[MaxIter]);
952 LoopInfo->adjustTripCount(-(MaxIter + 1));
953 }
954}
955
956/// Return true if we can compute the amount the instruction changes
957/// during each iteration. Set Delta to the amount of the change.
958bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
959 const MachineOperand *BaseOp;
960 int64_t Offset;
961 bool OffsetIsScalable;
962 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable))
963 return false;
964
965 // FIXME: This algorithm assumes instructions have fixed-size offsets.
966 if (OffsetIsScalable)
967 return false;
968
969 if (!BaseOp->isReg())
970 return false;
971
972 Register BaseReg = BaseOp->getReg();
973 if (!BaseReg.isVirtual())
974 return false;
975
976 MachineRegisterInfo &MRI = MF.getRegInfo();
977 // Check if there is a Phi. If so, get the definition in the loop.
978 MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
979 if (BaseDef && BaseDef->isPHI()) {
980 BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
981 BaseDef = MRI.getVRegDef(BaseReg);
982 }
983 if (!BaseDef)
984 return false;
985
986 int D = 0;
987 if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
988 return false;
989
990 Delta = D;
991 return true;
992}
993
994/// Update the memory operand with a new offset when the pipeliner
995/// generates a new copy of the instruction that refers to a
996/// different memory location.
997void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
998 MachineInstr &OldMI,
999 unsigned Num) {
1000 if (Num == 0)
1001 return;
1002 // If the instruction has memory operands, then adjust the offset
1003 // when the instruction appears in different stages.
1004 if (NewMI.memoperands_empty())
1005 return;
1007 for (MachineMemOperand *MMO : NewMI.memoperands()) {
1008 // TODO: Figure out whether isAtomic is really necessary (see D57601).
1009 if (MMO->isVolatile() || MMO->isAtomic() ||
1010 (MMO->isInvariant() && MMO->isDereferenceable()) ||
1011 (!MMO->getValue())) {
1012 NewMMOs.push_back(MMO);
1013 continue;
1014 }
1015 unsigned Delta;
1016 if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
1017 int64_t AdjOffset = static_cast<int64_t>(Delta) * Num;
1018 NewMMOs.push_back(
1019 MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
1020 } else {
1021 NewMMOs.push_back(MF.getMachineMemOperand(
1023 }
1024 }
1025 NewMI.setMemRefs(MF, NewMMOs);
1026}
1027
1028/// Clone the instruction for the new pipelined loop and update the
1029/// memory operands, if needed.
1030MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
1031 unsigned CurStageNum,
1032 unsigned InstStageNum) {
1033 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
1034 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
1035 return NewMI;
1036}
1037
1038/// Clone the instruction for the new pipelined loop. If needed, this
1039/// function updates the instruction using the values saved in the
1040/// InstrChanges structure.
1041MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
1042 MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
1043 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
1044 auto It = InstrChanges.find(OldMI);
1045 if (It != InstrChanges.end()) {
1046 std::pair<Register, int64_t> RegAndOffset = It->second;
1047 unsigned BasePos, OffsetPos;
1048 if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
1049 return nullptr;
1050 int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
1051 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
1052 if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
1053 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
1054 NewMI->getOperand(OffsetPos).setImm(NewOffset);
1055 }
1056 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
1057 return NewMI;
1058}
1059
1060/// Update the machine instruction with new virtual registers. This
1061/// function may change the definitions and/or uses.
1062void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
1063 bool LastDef,
1064 unsigned CurStageNum,
1065 unsigned InstrStageNum,
1066 ValueMapTy *VRMap) {
1067 for (MachineOperand &MO : NewMI->operands()) {
1068 if (!MO.isReg() || !MO.getReg().isVirtual())
1069 continue;
1070 Register reg = MO.getReg();
1071 if (MO.isDef()) {
1072 // Create a new virtual register for the definition.
1073 const TargetRegisterClass *RC = MRI.getRegClass(reg);
1074 Register NewReg = MRI.createVirtualRegister(RC);
1075 MO.setReg(NewReg);
1076 VRMap[CurStageNum][reg] = NewReg;
1077 if (LastDef)
1078 replaceRegUsesAfterLoop(reg, NewReg, BB, MRI);
1079 } else if (MO.isUse()) {
1080 MachineInstr *Def = MRI.getVRegDef(reg);
1081 // Compute the stage that contains the last definition for instruction.
1082 int DefStageNum = Schedule.getStage(Def);
1083 unsigned StageNum = CurStageNum;
1084 if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
1085 // Compute the difference in stages between the defintion and the use.
1086 unsigned StageDiff = (InstrStageNum - DefStageNum);
1087 // Make an adjustment to get the last definition.
1088 StageNum -= StageDiff;
1089 }
1090 if (auto It = VRMap[StageNum].find(reg); It != VRMap[StageNum].end())
1091 MO.setReg(It->second);
1092 }
1093 }
1094}
1095
1096/// Return the instruction in the loop that defines the register.
1097/// If the definition is a Phi, then follow the Phi operand to
1098/// the instruction in the loop.
1099MachineInstr *ModuloScheduleExpander::findDefInLoop(Register Reg) {
1100 SmallPtrSet<MachineInstr *, 8> Visited;
1101 MachineInstr *Def = MRI.getVRegDef(Reg);
1102 while (Def->isPHI()) {
1103 if (!Visited.insert(Def).second)
1104 break;
1105 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
1106 if (Def->getOperand(i + 1).getMBB() == BB) {
1107 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
1108 break;
1109 }
1110 }
1111 return Def;
1112}
1113
1114/// Return the new name for the value from the previous stage.
1115Register ModuloScheduleExpander::getPrevMapVal(
1116 unsigned StageNum, unsigned PhiStage, Register LoopVal, unsigned LoopStage,
1117 ValueMapTy *VRMap, MachineBasicBlock *BB) {
1118 Register PrevVal;
1119 if (StageNum > PhiStage) {
1120 MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
1121 if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
1122 // The name is defined in the previous stage.
1123 PrevVal = VRMap[StageNum - 1][LoopVal];
1124 else if (VRMap[StageNum].count(LoopVal))
1125 // The previous name is defined in the current stage when the instruction
1126 // order is swapped.
1127 PrevVal = VRMap[StageNum][LoopVal];
1128 else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
1129 // The loop value hasn't yet been scheduled.
1130 PrevVal = LoopVal;
1131 else if (StageNum == PhiStage + 1)
1132 // The loop value is another phi, which has not been scheduled.
1133 PrevVal = getInitPhiReg(*LoopInst, BB);
1134 else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
1135 // The loop value is another phi, which has been scheduled.
1136 PrevVal =
1137 getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
1138 LoopStage, VRMap, BB);
1139 }
1140 return PrevVal;
1141}
1142
1143/// Rewrite the Phi values in the specified block to use the mappings
1144/// from the initial operand. Once the Phi is scheduled, we switch
1145/// to using the loop value instead of the Phi value, so those names
1146/// do not need to be rewritten.
1147void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
1148 unsigned StageNum,
1149 ValueMapTy *VRMap,
1150 InstrMapTy &InstrMap) {
1151 for (auto &PHI : BB->phis()) {
1152 Register InitVal;
1153 Register LoopVal;
1154 getPhiRegs(PHI, BB, InitVal, LoopVal);
1155 Register PhiDef = PHI.getOperand(0).getReg();
1156
1157 unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
1158 unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
1159 unsigned NumPhis = getStagesForPhi(PhiDef);
1160 if (NumPhis > StageNum)
1161 NumPhis = StageNum;
1162 for (unsigned np = 0; np <= NumPhis; ++np) {
1163 Register NewVal =
1164 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
1165 if (!NewVal)
1166 NewVal = InitVal;
1167 rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
1168 NewVal);
1169 }
1170 }
1171}
1172
1173/// Rewrite a previously scheduled instruction to use the register value
1174/// from the new instruction. Make sure the instruction occurs in the
1175/// basic block, and we don't change the uses in the new instruction.
1176void ModuloScheduleExpander::rewriteScheduledInstr(
1177 MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
1178 unsigned PhiNum, MachineInstr *Phi, Register OldReg, Register NewReg,
1179 Register PrevReg) {
1180 bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
1181 int StagePhi = Schedule.getStage(Phi) + PhiNum;
1182 // Rewrite uses that have been scheduled already to use the new
1183 // Phi register.
1184 for (MachineOperand &UseOp :
1185 llvm::make_early_inc_range(MRI.use_operands(OldReg))) {
1186 MachineInstr *UseMI = UseOp.getParent();
1187 if (UseMI->getParent() != BB)
1188 continue;
1189 if (UseMI->isPHI()) {
1190 if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
1191 continue;
1192 if (getLoopPhiReg(*UseMI, BB) != OldReg)
1193 continue;
1194 }
1195 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
1196 assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
1197 MachineInstr *OrigMI = OrigInstr->second;
1198 int StageSched = Schedule.getStage(OrigMI);
1199 int CycleSched = Schedule.getCycle(OrigMI);
1200 Register ReplaceReg;
1201 // This is the stage for the scheduled instruction.
1202 if (StagePhi == StageSched && Phi->isPHI()) {
1203 int CyclePhi = Schedule.getCycle(Phi);
1204 if (PrevReg && InProlog)
1205 ReplaceReg = PrevReg;
1206 else if (PrevReg && !isLoopCarried(*Phi) &&
1207 (CyclePhi <= CycleSched || OrigMI->isPHI()))
1208 ReplaceReg = PrevReg;
1209 else
1210 ReplaceReg = NewReg;
1211 }
1212 // The scheduled instruction occurs before the scheduled Phi, and the
1213 // Phi is not loop carried.
1214 if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
1215 ReplaceReg = NewReg;
1216 if (StagePhi > StageSched && Phi->isPHI())
1217 ReplaceReg = NewReg;
1218 if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
1219 ReplaceReg = NewReg;
1220 if (ReplaceReg) {
1221 const TargetRegisterClass *NRC =
1222 MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
1223 if (NRC)
1224 UseOp.setReg(ReplaceReg);
1225 else {
1226 Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
1227 MachineInstr *newCopy = BuildMI(*BB, UseMI, UseMI->getDebugLoc(),
1228 TII->get(TargetOpcode::COPY), SplitReg)
1229 .addReg(ReplaceReg);
1230 UseOp.setReg(SplitReg);
1231 LIS.InsertMachineInstrInMaps(*newCopy);
1232 }
1233 }
1234 }
1235}
1236
1237bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
1238 if (!Phi.isPHI())
1239 return false;
1240 int DefCycle = Schedule.getCycle(&Phi);
1241 int DefStage = Schedule.getStage(&Phi);
1242
1243 Register InitVal;
1244 Register LoopVal;
1245 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
1246 MachineInstr *Use = MRI.getVRegDef(LoopVal);
1247 if (!Use || Use->isPHI())
1248 return true;
1249 int LoopCycle = Schedule.getCycle(Use);
1250 int LoopStage = Schedule.getStage(Use);
1251 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
1252}
1253
1254//===----------------------------------------------------------------------===//
1255// PeelingModuloScheduleExpander implementation
1256//===----------------------------------------------------------------------===//
1257// This is a reimplementation of ModuloScheduleExpander that works by creating
1258// a fully correct steady-state kernel and peeling off the prolog and epilogs.
1259//===----------------------------------------------------------------------===//
1260
1261namespace {
1262// Remove any dead phis in MBB. Dead phis either have only one block as input
1263// (in which case they are the identity) or have no uses.
1264void EliminateDeadPhis(MachineBasicBlock *MBB, MachineRegisterInfo &MRI,
1265 LiveIntervals *LIS, bool KeepSingleSrcPhi = false) {
1266 bool Changed = true;
1267 while (Changed) {
1268 Changed = false;
1270 assert(MI.isPHI());
1271 if (MRI.use_empty(MI.getOperand(0).getReg())) {
1272 if (LIS)
1274 MI.eraseFromParent();
1275 Changed = true;
1276 } else if (!KeepSingleSrcPhi && MI.getNumExplicitOperands() == 3) {
1277 const TargetRegisterClass *ConstrainRegClass =
1278 MRI.constrainRegClass(MI.getOperand(1).getReg(),
1279 MRI.getRegClass(MI.getOperand(0).getReg()));
1280 assert(ConstrainRegClass &&
1281 "Expected a valid constrained register class!");
1282 (void)ConstrainRegClass;
1283 MRI.replaceRegWith(MI.getOperand(0).getReg(),
1284 MI.getOperand(1).getReg());
1285 if (LIS)
1287 MI.eraseFromParent();
1288 Changed = true;
1289 }
1290 }
1291 }
1292}
1293
1294/// Rewrites the kernel block in-place to adhere to the given schedule.
1295/// KernelRewriter holds all of the state required to perform the rewriting.
1296class KernelRewriter {
1297 ModuloSchedule &S;
1298 MachineBasicBlock *BB;
1299 MachineBasicBlock *PreheaderBB;
1300 MachineRegisterInfo &MRI;
1301 const TargetInstrInfo *TII;
1302 LiveIntervals *LIS;
1303
1304 // Map from register class to canonical undef register for that class.
1305 DenseMap<const TargetRegisterClass *, Register> Undefs;
1306 // Map from <LoopReg, InitReg> to phi register for all created phis. Note that
1307 // this map is only used when InitReg is non-undef.
1308 DenseMap<std::pair<Register, Register>, Register> Phis;
1309 // Map from LoopReg to phi register where the InitReg is undef.
1310 DenseMap<Register, Register> UndefPhis;
1311
1312 // Reg is used by MI. Return the new register MI should use to adhere to the
1313 // schedule. Insert phis as necessary.
1314 Register remapUse(Register Reg, MachineInstr &MI);
1315 // Insert a phi that carries LoopReg from the loop body and InitReg otherwise.
1316 // If InitReg is not given it is chosen arbitrarily. It will either be undef
1317 // or will be chosen so as to share another phi.
1318 Register phi(Register LoopReg, std::optional<Register> InitReg = {},
1319 const TargetRegisterClass *RC = nullptr);
1320 // Create an undef register of the given register class.
1321 Register undef(const TargetRegisterClass *RC);
1322
1323public:
1324 KernelRewriter(MachineLoop &L, ModuloSchedule &S, MachineBasicBlock *LoopBB,
1325 LiveIntervals *LIS = nullptr);
1326 void rewrite();
1327};
1328} // namespace
1329
1330KernelRewriter::KernelRewriter(MachineLoop &L, ModuloSchedule &S,
1331 MachineBasicBlock *LoopBB, LiveIntervals *LIS)
1332 : S(S), BB(LoopBB), PreheaderBB(L.getLoopPreheader()),
1333 MRI(BB->getParent()->getRegInfo()),
1334 TII(BB->getParent()->getSubtarget().getInstrInfo()), LIS(LIS) {
1335 PreheaderBB = *BB->pred_begin();
1336 if (PreheaderBB == BB)
1337 PreheaderBB = *std::next(BB->pred_begin());
1338}
1339
1340void KernelRewriter::rewrite() {
1341 // Rearrange the loop to be in schedule order. Note that the schedule may
1342 // contain instructions that are not owned by the loop block (InstrChanges and
1343 // friends), so we gracefully handle unowned instructions and delete any
1344 // instructions that weren't in the schedule.
1345 auto InsertPt = BB->getFirstTerminator();
1346 MachineInstr *FirstMI = nullptr;
1347 for (MachineInstr *MI : S.getInstructions()) {
1348 if (MI->isPHI())
1349 continue;
1350 if (MI->getParent())
1351 MI->removeFromParent();
1352 BB->insert(InsertPt, MI);
1353 if (!FirstMI)
1354 FirstMI = MI;
1355 }
1356 assert(FirstMI && "Failed to find first MI in schedule");
1357
1358 // At this point all of the scheduled instructions are between FirstMI
1359 // and the end of the block. Kill from the first non-phi to FirstMI.
1360 for (auto I = BB->getFirstNonPHI(); I != FirstMI->getIterator();) {
1361 if (LIS)
1363 (I++)->eraseFromParent();
1364 }
1365
1366 // Now remap every instruction in the loop.
1367 for (MachineInstr &MI : *BB) {
1368 if (MI.isPHI() || MI.isTerminator())
1369 continue;
1370 for (MachineOperand &MO : MI.uses()) {
1371 if (!MO.isReg() || MO.getReg().isPhysical() || MO.isImplicit())
1372 continue;
1373 Register Reg = remapUse(MO.getReg(), MI);
1374 MO.setReg(Reg);
1375 }
1376 }
1377 EliminateDeadPhis(BB, MRI, LIS);
1378
1379 // Ensure a phi exists for all instructions that are either referenced by
1380 // an illegal phi or by an instruction outside the loop. This allows us to
1381 // treat remaps of these values the same as "normal" values that come from
1382 // loop-carried phis.
1383 for (auto MI = BB->getFirstNonPHI(); MI != BB->end(); ++MI) {
1384 if (MI->isPHI()) {
1385 Register R = MI->getOperand(0).getReg();
1386 phi(R);
1387 continue;
1388 }
1389
1390 for (MachineOperand &Def : MI->defs()) {
1391 for (MachineInstr &MI : MRI.use_instructions(Def.getReg())) {
1392 if (MI.getParent() != BB) {
1393 phi(Def.getReg());
1394 break;
1395 }
1396 }
1397 }
1398 }
1399}
1400
1401Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
1402 MachineInstr *Producer = MRI.getUniqueVRegDef(Reg);
1403 if (!Producer)
1404 return Reg;
1405
1406 if (Producer->getParent() != BB)
1407 // Producer was not inside the loop. Use the register as-is.
1408 return Reg;
1409
1410 int ConsumerStage = S.getStage(&MI);
1411 if (!Producer->isPHI()) {
1412 // Non-phi producers are simple to remap. Insert as many phis as the
1413 // difference between the consumer and producer stages.
1414 int ProducerStage = S.getStage(Producer);
1415 assert(ConsumerStage != -1 &&
1416 "In-loop consumer should always be scheduled!");
1417 assert(ConsumerStage >= ProducerStage);
1418 unsigned StageDiff = ConsumerStage - ProducerStage;
1419
1420 for (unsigned I = 0; I < StageDiff; ++I)
1421 Reg = phi(Reg);
1422 return Reg;
1423 }
1424
1425 // First, dive through the phi chain to find the defaults for the generated
1426 // phis.
1428 Register LoopReg = Reg;
1429 auto LoopProducer = Producer;
1430 while (LoopProducer->isPHI() && LoopProducer->getParent() == BB) {
1431 LoopReg = getLoopPhiReg(*LoopProducer, BB);
1432 Defaults.emplace_back(getInitPhiReg(*LoopProducer, BB));
1433 LoopProducer = MRI.getUniqueVRegDef(LoopReg);
1434 assert(LoopProducer);
1435 }
1436 int LoopProducerStage = S.getStage(LoopProducer);
1437 if (LoopProducerStage == -1) {
1438 assert(LoopProducer->getParent() != BB &&
1439 "In-loop producer should always be scheduled!");
1440 // The loop-carried value of the in-loop phi chain is defined outside the
1441 // loop, so it is available at stage 0 of every iteration.
1442 LoopProducerStage = 0;
1443 }
1444
1445 std::optional<Register> IllegalPhiDefault;
1446
1447 if (LoopProducerStage > ConsumerStage) {
1448 // This schedule is only representable if ProducerStage == ConsumerStage+1.
1449 // In addition, Consumer's cycle must be scheduled after Producer in the
1450 // rescheduled loop. This is enforced by the pipeliner's ASAP and ALAP
1451 // functions.
1452#ifndef NDEBUG // Silence unused variables in non-asserts mode.
1453 int LoopProducerCycle = S.getCycle(LoopProducer);
1454 int ConsumerCycle = S.getCycle(&MI);
1455#endif
1456 assert(LoopProducerCycle <= ConsumerCycle);
1457 assert(LoopProducerStage == ConsumerStage + 1);
1458 // Peel off the first phi from Defaults and insert a phi between producer
1459 // and consumer. This phi will not be at the front of the block so we
1460 // consider it illegal. It will only exist during the rewrite process; it
1461 // needs to exist while we peel off prologs because these could take the
1462 // default value. After that we can replace all uses with the loop producer
1463 // value.
1464 IllegalPhiDefault = Defaults.front();
1465 Defaults.erase(Defaults.begin());
1466 } else {
1467 assert(ConsumerStage >= LoopProducerStage);
1468 int StageDiff = ConsumerStage - LoopProducerStage;
1469 if (StageDiff > 0) {
1470 LLVM_DEBUG(dbgs() << " -- padding defaults array from " << Defaults.size()
1471 << " to " << (Defaults.size() + StageDiff) << "\n");
1472 // If we need more phis than we have defaults for, pad out with undefs for
1473 // the earliest phis, which are at the end of the defaults chain (the
1474 // chain is in reverse order).
1475 Defaults.resize(Defaults.size() + StageDiff,
1476 Defaults.empty() ? std::optional<Register>()
1477 : Defaults.back());
1478 }
1479 }
1480
1481 // Now we know the number of stages to jump back, insert the phi chain.
1482 auto DefaultI = Defaults.rbegin();
1483 while (DefaultI != Defaults.rend())
1484 LoopReg = phi(LoopReg, *DefaultI++, MRI.getRegClass(Reg));
1485
1486 if (IllegalPhiDefault) {
1487 // The consumer optionally consumes LoopProducer in the same iteration
1488 // (because the producer is scheduled at an earlier cycle than the consumer)
1489 // or the initial value. To facilitate this we create an illegal block here
1490 // by embedding a phi in the middle of the block. We will fix this up
1491 // immediately prior to pruning.
1492 auto RC = MRI.getRegClass(Reg);
1494 MachineInstr *IllegalPhi =
1495 BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1496 .addReg(*IllegalPhiDefault)
1497 .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
1498 .addReg(LoopReg)
1499 .addMBB(BB); // Block choice is arbitrary and has no effect.
1500 // Illegal phi should belong to the producer stage so that it can be
1501 // filtered correctly during peeling.
1502 S.setStage(IllegalPhi, LoopProducerStage);
1503 return R;
1504 }
1505
1506 return LoopReg;
1507}
1508
1509Register KernelRewriter::phi(Register LoopReg, std::optional<Register> InitReg,
1510 const TargetRegisterClass *RC) {
1511 // If the init register is not undef, try and find an existing phi.
1512 if (InitReg) {
1513 auto I = Phis.find({LoopReg, *InitReg});
1514 if (I != Phis.end())
1515 return I->second;
1516 } else {
1517 for (auto &KV : Phis) {
1518 if (KV.first.first == LoopReg)
1519 return KV.second;
1520 }
1521 }
1522
1523 // InitReg is either undef or no existing phi takes InitReg as input. Try and
1524 // find a phi that takes undef as input.
1525 auto I = UndefPhis.find(LoopReg);
1526 if (I != UndefPhis.end()) {
1527 Register R = I->second;
1528 if (!InitReg)
1529 // Found a phi taking undef as input, and this input is undef so return
1530 // without any more changes.
1531 return R;
1532 // Found a phi taking undef as input, so rewrite it to take InitReg.
1533 MachineInstr *MI = MRI.getVRegDef(R);
1534 MI->getOperand(1).setReg(*InitReg);
1535 Phis.insert({{LoopReg, *InitReg}, R});
1536 const TargetRegisterClass *ConstrainRegClass =
1537 MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
1538 assert(ConstrainRegClass && "Expected a valid constrained register class!");
1539 (void)ConstrainRegClass;
1540 UndefPhis.erase(I);
1541 return R;
1542 }
1543
1544 // Failed to find any existing phi to reuse, so create a new one.
1545 if (!RC)
1546 RC = MRI.getRegClass(LoopReg);
1548 if (InitReg) {
1549 const TargetRegisterClass *ConstrainRegClass =
1550 MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
1551 assert(ConstrainRegClass && "Expected a valid constrained register class!");
1552 (void)ConstrainRegClass;
1553 }
1554 BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
1555 .addReg(InitReg ? *InitReg : undef(RC))
1556 .addMBB(PreheaderBB)
1557 .addReg(LoopReg)
1558 .addMBB(BB);
1559 if (!InitReg)
1560 UndefPhis[LoopReg] = R;
1561 else
1562 Phis[{LoopReg, *InitReg}] = R;
1563 return R;
1564}
1565
1566Register KernelRewriter::undef(const TargetRegisterClass *RC) {
1567 Register &R = Undefs[RC];
1568 if (R == 0) {
1569 // Create an IMPLICIT_DEF that defines this register if we need it.
1570 // All uses of this should be removed by the time we have finished unrolling
1571 // prologs and epilogs.
1573 auto *InsertBB = &PreheaderBB->getParent()->front();
1574 BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
1575 TII->get(TargetOpcode::IMPLICIT_DEF), R);
1576 }
1577 return R;
1578}
1579
1580namespace {
1581/// Describes an operand in the kernel of a pipelined loop. Characteristics of
1582/// the operand are discovered, such as how many in-loop PHIs it has to jump
1583/// through and defaults for these phis.
1584class KernelOperandInfo {
1585 MachineBasicBlock *BB;
1586 MachineRegisterInfo &MRI;
1587 SmallVector<Register, 4> PhiDefaults;
1588 MachineOperand *Source;
1589
1590public:
1591 KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
1592 const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
1593 : MRI(MRI) {
1594 Source = MO;
1595 BB = MO->getParent()->getParent();
1596 while (isRegInLoop(MO)) {
1597 MachineInstr *MI = MRI.getVRegDef(MO->getReg());
1598 if (MI->isFullCopy()) {
1599 MO = &MI->getOperand(1);
1600 continue;
1601 }
1602 if (!MI->isPHI())
1603 break;
1604 // If this is an illegal phi, don't count it in distance.
1605 if (IllegalPhis.count(MI)) {
1606 MO = &MI->getOperand(3);
1607 continue;
1608 }
1609
1611 MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
1612 : &MI->getOperand(3);
1613 PhiDefaults.push_back(Default);
1614 }
1615 }
1616
1617 bool operator==(const KernelOperandInfo &Other) const {
1618 return PhiDefaults.size() == Other.PhiDefaults.size();
1619 }
1620
1621 void print(raw_ostream &OS) const {
1622 OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
1623 << *Source->getParent();
1624 }
1625
1626private:
1627 bool isRegInLoop(MachineOperand *MO) {
1628 return MO->isReg() && MO->getReg().isVirtual() &&
1629 MRI.getVRegDef(MO->getReg())->getParent() == BB;
1630 }
1631};
1632} // namespace
1633
1634MachineBasicBlock *
1637 if (LPD == LPD_Front)
1638 PeeledFront.push_back(NewBB);
1639 else
1640 PeeledBack.push_front(NewBB);
1641 for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
1642 ++I, ++NI) {
1643 CanonicalMIs[&*I] = &*I;
1644 CanonicalMIs[&*NI] = &*I;
1645 BlockMIs[{NewBB, &*I}] = &*NI;
1646 BlockMIs[{BB, &*I}] = &*I;
1647 }
1648 return NewBB;
1649}
1650
1652 int MinStage) {
1653 for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
1654 I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
1655 MachineInstr *MI = &*I++;
1656 int Stage = getStage(MI);
1657 if (Stage == -1 || Stage >= MinStage)
1658 continue;
1659
1660 for (MachineOperand &DefMO : MI->defs()) {
1662 for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1663 // Only PHIs can use values from this block by construction.
1664 // Match with the equivalent PHI in B.
1665 assert(UseMI.isPHI());
1666 Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1667 MI->getParent());
1668 Subs.emplace_back(&UseMI, Reg);
1669 }
1670 for (auto &Sub : Subs)
1671 Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1672 *MRI.getTargetRegisterInfo());
1673 }
1674 if (LIS)
1675 LIS->RemoveMachineInstrFromMaps(*MI);
1676 MI->eraseFromParent();
1677 }
1678}
1679
1681 MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
1682 auto InsertPt = DestBB->getFirstNonPHI();
1685 llvm::make_range(SourceBB->getFirstNonPHI(), SourceBB->end()))) {
1686 if (MI.isPHI()) {
1687 // This is an illegal PHI. If we move any instructions using an illegal
1688 // PHI, we need to create a legal Phi.
1689 if (getStage(&MI) != Stage) {
1690 // The legal Phi is not necessary if the illegal phi's stage
1691 // is being moved.
1692 Register PhiR = MI.getOperand(0).getReg();
1693 auto RC = MRI.getRegClass(PhiR);
1694 Register NR = MRI.createVirtualRegister(RC);
1695 MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(),
1696 DebugLoc(), TII->get(TargetOpcode::PHI), NR)
1697 .addReg(PhiR)
1698 .addMBB(SourceBB);
1699 BlockMIs[{DestBB, CanonicalMIs[&MI]}] = NI;
1701 Remaps[PhiR] = NR;
1702 }
1703 }
1704 if (getStage(&MI) != Stage)
1705 continue;
1706 MI.removeFromParent();
1707 DestBB->insert(InsertPt, &MI);
1708 auto *KernelMI = CanonicalMIs[&MI];
1709 BlockMIs[{DestBB, KernelMI}] = &MI;
1710 BlockMIs.erase({SourceBB, KernelMI});
1711 }
1713 for (MachineInstr &MI : DestBB->phis()) {
1714 assert(MI.getNumOperands() == 3);
1715 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
1716 // If the instruction referenced by the phi is moved inside the block
1717 // we don't need the phi anymore.
1718 if (getStage(Def) == Stage) {
1719 Register PhiReg = MI.getOperand(0).getReg();
1720 assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg(),
1721 /*TRI=*/nullptr) != -1);
1722 MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
1723 MI.getOperand(0).setReg(PhiReg);
1724 PhiToDelete.push_back(&MI);
1725 }
1726 }
1727 for (auto *P : PhiToDelete)
1728 P->eraseFromParent();
1729 InsertPt = DestBB->getFirstNonPHI();
1730 // Helper to clone Phi instructions into the destination block. We clone Phi
1731 // greedily to avoid combinatorial explosion of Phi instructions.
1732 auto clonePhi = [&](MachineInstr *Phi) {
1733 MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
1734 DestBB->insert(InsertPt, NewMI);
1735 Register OrigR = Phi->getOperand(0).getReg();
1736 Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
1737 NewMI->getOperand(0).setReg(R);
1738 NewMI->getOperand(1).setReg(OrigR);
1739 NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
1740 Remaps[OrigR] = R;
1741 CanonicalMIs[NewMI] = CanonicalMIs[Phi];
1742 BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
1744 return R;
1745 };
1746 for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
1747 for (MachineOperand &MO : I->uses()) {
1748 if (!MO.isReg())
1749 continue;
1750 if (auto It = Remaps.find(MO.getReg()); It != Remaps.end())
1751 MO.setReg(It->second);
1752 else if (MO.getReg().isVirtual()) {
1753 // If we are using a phi from the source block we need to add a new phi
1754 // pointing to the old one.
1755 MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
1756 if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
1757 Register R = clonePhi(Use);
1758 MO.setReg(R);
1759 }
1760 }
1761 }
1762 }
1763}
1764
1767 MachineInstr *Phi) {
1768 unsigned distance = PhiNodeLoopIteration[Phi];
1769 MachineInstr *CanonicalUse = CanonicalPhi;
1770 Register CanonicalUseReg = CanonicalUse->getOperand(0).getReg();
1771 for (unsigned I = 0; I < distance; ++I) {
1772 assert(CanonicalUse->isPHI());
1773 assert(CanonicalUse->getNumOperands() == 5);
1774 unsigned LoopRegIdx = 3, InitRegIdx = 1;
1775 if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
1776 std::swap(LoopRegIdx, InitRegIdx);
1777 CanonicalUseReg = CanonicalUse->getOperand(LoopRegIdx).getReg();
1778 CanonicalUse = MRI.getVRegDef(CanonicalUseReg);
1779 }
1780 return CanonicalUseReg;
1781}
1782
1784 BitVector LS(Schedule.getNumStages(), true);
1785 BitVector AS(Schedule.getNumStages(), true);
1786 LiveStages[BB] = LS;
1787 AvailableStages[BB] = AS;
1788
1789 // Peel out the prologs.
1790 LS.reset();
1791 for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
1792 LS[I] = true;
1793 Prologs.push_back(peelKernel(LPD_Front));
1794 LiveStages[Prologs.back()] = LS;
1795 AvailableStages[Prologs.back()] = LS;
1796 }
1797
1798 // Create a block that will end up as the new loop exiting block (dominated by
1799 // all prologs and epilogs). It will only contain PHIs, in the same order as
1800 // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
1801 // that the exiting block is a (sub) clone of BB. This in turn gives us the
1802 // property that any value deffed in BB but used outside of BB is used by a
1803 // PHI in the exiting block.
1805 EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1806 // Push out the epilogs, again in reverse order.
1807 // We can't assume anything about the minumum loop trip count at this point,
1808 // so emit a fairly complex epilog.
1809
1810 // We first peel number of stages minus one epilogue. Then we remove dead
1811 // stages and reorder instructions based on their stage. If we have 3 stages
1812 // we generate first:
1813 // E0[3, 2, 1]
1814 // E1[3', 2']
1815 // E2[3'']
1816 // And then we move instructions based on their stages to have:
1817 // E0[3]
1818 // E1[2, 3']
1819 // E2[1, 2', 3'']
1820 // The transformation is legal because we only move instructions past
1821 // instructions of a previous loop iteration.
1822 for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
1823 Epilogs.push_back(peelKernel(LPD_Back));
1824 MachineBasicBlock *B = Epilogs.back();
1825 filterInstructions(B, Schedule.getNumStages() - I);
1826 // Keep track at which iteration each phi belongs to. We need it to know
1827 // what version of the variable to use during prologue/epilogue stitching.
1828 EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1829 for (MachineInstr &Phi : B->phis())
1830 PhiNodeLoopIteration[&Phi] = Schedule.getNumStages() - I;
1831 }
1832 for (size_t I = 0; I < Epilogs.size(); I++) {
1833 LS.reset();
1834 for (size_t J = I; J < Epilogs.size(); J++) {
1835 int Iteration = J;
1836 unsigned Stage = Schedule.getNumStages() - 1 + I - J;
1837 // Move stage one block at a time so that Phi nodes are updated correctly.
1838 for (size_t K = Iteration; K > I; K--)
1839 moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
1840 LS[Stage] = true;
1841 }
1842 LiveStages[Epilogs[I]] = LS;
1843 AvailableStages[Epilogs[I]] = AS;
1844 }
1845
1846 // Now we've defined all the prolog and epilog blocks as a fallthrough
1847 // sequence, add the edges that will be followed if the loop trip count is
1848 // lower than the number of stages (connecting prologs directly with epilogs).
1849 auto PI = Prologs.begin();
1850 auto EI = Epilogs.begin();
1851 assert(Prologs.size() == Epilogs.size());
1852 for (; PI != Prologs.end(); ++PI, ++EI) {
1853 MachineBasicBlock *Pred = *(*EI)->pred_begin();
1854 (*PI)->addSuccessor(*EI);
1855 MDTU.applyUpdates({{MachineDominatorTree::Insert, *PI, *EI}});
1856 for (MachineInstr &MI : (*EI)->phis()) {
1857 Register Reg = MI.getOperand(1).getReg();
1858 MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
1859 if (Use && Use->getParent() == Pred) {
1860 MachineInstr *CanonicalUse = CanonicalMIs[Use];
1861 if (CanonicalUse->isPHI()) {
1862 // If the use comes from a phi we need to skip as many phi as the
1863 // distance between the epilogue and the kernel. Trace through the phi
1864 // chain to find the right value.
1865 Reg = getPhiCanonicalReg(CanonicalUse, Use);
1866 }
1867 Reg = getEquivalentRegisterIn(Reg, *PI);
1868 }
1869 MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
1870 MI.addOperand(MachineOperand::CreateMBB(*PI));
1871 }
1872 }
1873
1874 // Create a list of all blocks in order.
1877 Blocks.push_back(BB);
1879
1880 // Iterate in reverse order over all instructions, remapping as we go.
1881 for (MachineBasicBlock *B : reverse(Blocks)) {
1882 for (auto I = B->instr_rbegin();
1883 I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
1885 rewriteUsesOf(&*MI);
1886 }
1887 }
1888 for (auto *MI : IllegalPhisToDelete) {
1889 if (LIS)
1890 LIS->RemoveMachineInstrFromMaps(*MI);
1891 MI->eraseFromParent();
1892 }
1893 IllegalPhisToDelete.clear();
1894
1895 // Now all remapping has been done, we're free to optimize the generated code.
1896 for (MachineBasicBlock *B : reverse(Blocks))
1897 EliminateDeadPhis(B, MRI, LIS);
1898 EliminateDeadPhis(ExitingBB, MRI, LIS);
1899}
1900
1902 MachineFunction &MF = *BB->getParent();
1903 MachineBasicBlock *Exit = *BB->succ_begin();
1904 if (Exit == BB)
1905 Exit = *std::next(BB->succ_begin());
1906
1907 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
1908 MF.insert(std::next(BB->getIterator()), NewBB);
1909
1910 // Clone all phis in BB into NewBB and rewrite.
1911 for (MachineInstr &MI : BB->phis()) {
1912 auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
1913 Register OldR = MI.getOperand(3).getReg();
1914 Register R = MRI.createVirtualRegister(RC);
1916 for (MachineInstr &Use : MRI.use_instructions(OldR))
1917 if (Use.getParent() != BB)
1918 Uses.push_back(&Use);
1919 for (MachineInstr *Use : Uses)
1920 Use->substituteRegister(OldR, R, /*SubIdx=*/0,
1921 *MRI.getTargetRegisterInfo());
1922 MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
1923 .addReg(OldR)
1924 .addMBB(BB);
1925 BlockMIs[{NewBB, &MI}] = NI;
1926 CanonicalMIs[NI] = &MI;
1927 }
1928 BB->replaceSuccessor(Exit, NewBB);
1929 Exit->replacePhiUsesWith(BB, NewBB);
1930 NewBB->addSuccessor(Exit);
1931 MDTU.splitCriticalEdge(BB, Exit, NewBB);
1932
1933 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1935 bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
1936 (void)CanAnalyzeBr;
1937 assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
1938 TII->removeBranch(*BB);
1939 TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
1940 Cond, DebugLoc());
1941 TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
1942 return NewBB;
1943}
1944
1948 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
1949 unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
1950 return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
1951}
1952
1954 if (MI->isPHI()) {
1955 // This is an illegal PHI. The loop-carried (desired) value is operand 3,
1956 // and it is produced by this block.
1957 Register PhiR = MI->getOperand(0).getReg();
1958 Register R = MI->getOperand(3).getReg();
1959 int RMIStage = getStage(MRI.getUniqueVRegDef(R));
1960 if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
1961 R = MI->getOperand(1).getReg();
1962 MRI.setRegClass(R, MRI.getRegClass(PhiR));
1963 MRI.replaceRegWith(PhiR, R);
1964 // Postpone deleting the Phi as it may be referenced by BlockMIs and used
1965 // later to figure out how to remap registers.
1966 MI->getOperand(0).setReg(PhiR);
1967 IllegalPhisToDelete.push_back(MI);
1968 return;
1969 }
1970
1971 int Stage = getStage(MI);
1972 if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
1973 LiveStages[MI->getParent()].test(Stage))
1974 // Instruction is live, no rewriting to do.
1975 return;
1976
1977 for (MachineOperand &DefMO : MI->defs()) {
1979 for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1980 // Only PHIs can use values from this block by construction.
1981 // Match with the equivalent PHI in B.
1982 assert(UseMI.isPHI());
1983 Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1984 MI->getParent());
1985 Subs.emplace_back(&UseMI, Reg);
1986 }
1987 for (auto &Sub : Subs)
1988 Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1989 *MRI.getTargetRegisterInfo());
1990 }
1991 if (LIS)
1992 LIS->RemoveMachineInstrFromMaps(*MI);
1993 MI->eraseFromParent();
1994}
1995
1997 // Work outwards from the kernel.
1998 bool KernelDisposed = false;
1999 int TC = Schedule.getNumStages() - 1;
2000 for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
2001 ++PI, ++EI, --TC) {
2003 MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
2006 TII->removeBranch(*Prolog);
2007 std::optional<bool> StaticallyGreater =
2008 LoopInfo->createTripCountGreaterCondition(TC, *Prolog, Cond);
2009 if (!StaticallyGreater) {
2010 LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
2011 // Dynamically branch based on Cond.
2012 TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
2013 } else if (*StaticallyGreater == false) {
2014 LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
2015 // Prolog never falls through; branch to epilog and orphan interior
2016 // blocks. Leave it to unreachable-block-elim to clean up.
2017 Prolog->removeSuccessor(Fallthrough);
2018 MDTU.applyUpdates({{MachineDominatorTree::Delete, Prolog, Fallthrough}});
2019 for (MachineInstr &P : Fallthrough->phis()) {
2020 P.removeOperand(2);
2021 P.removeOperand(1);
2022 }
2023 TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
2024 KernelDisposed = true;
2025 } else {
2026 LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
2027 // Prolog always falls through; remove incoming values in epilog.
2028 Prolog->removeSuccessor(Epilog);
2029 MDTU.applyUpdates({{MachineDominatorTree::Delete, Prolog, Epilog}});
2030 for (MachineInstr &P : Epilog->phis()) {
2031 P.removeOperand(4);
2032 P.removeOperand(3);
2033 }
2034 }
2035 }
2036
2037 if (!KernelDisposed) {
2038 LoopInfo->adjustTripCount(-(Schedule.getNumStages() - 1));
2039 LoopInfo->setPreheader(Prologs.back());
2040 } else {
2041 LoopInfo->disposed();
2042 }
2043}
2044
2046 KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
2047 KR.rewrite();
2048}
2049
2051 BB = Schedule.getLoop()->getTopBlock();
2052 Preheader = Schedule.getLoop()->getLoopPreheader();
2053 LLVM_DEBUG(Schedule.dump());
2054 LoopInfo = TII->analyzeLoopForPipelining(BB);
2056
2057 rewriteKernel();
2059 fixupBranches();
2060}
2061
2063 BB = Schedule.getLoop()->getTopBlock();
2064 Preheader = Schedule.getLoop()->getLoopPreheader();
2065
2066 // Dump the schedule before we invalidate and remap all its instructions.
2067 // Stash it in a string so we can print it if we found an error.
2068 std::string ScheduleDump;
2069 raw_string_ostream OS(ScheduleDump);
2070 Schedule.print(OS);
2071
2072 // First, run the normal ModuleScheduleExpander. We don't support any
2073 // InstrChanges.
2074 assert(LIS && "Requires LiveIntervals!");
2077 MDTU.hasDomTree() ? &MDTU.getDomTree() : nullptr);
2078 MSE.expand();
2079 MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
2080 if (!ExpandedKernel) {
2081 // The expander optimized away the kernel. We can't do any useful checking.
2082 MSE.cleanup();
2083 return;
2084 }
2085 // Before running the KernelRewriter, re-add BB into the CFG.
2086 Preheader->addSuccessor(BB);
2087 MDTU.applyUpdates({{MachineDominatorTree::Insert, Preheader, BB}});
2088
2089 // Now run the new expansion algorithm.
2090 KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
2091 KR.rewrite();
2093
2094 // Collect all illegal phis that the new algorithm created. We'll give these
2095 // to KernelOperandInfo.
2097 for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
2098 if (NI->isPHI())
2099 IllegalPhis.insert(&*NI);
2100 }
2101
2102 // Co-iterate across both kernels. We expect them to be identical apart from
2103 // phis and full COPYs (we look through both).
2105 auto OI = ExpandedKernel->begin();
2106 auto NI = BB->begin();
2107 for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
2108 while (OI->isPHI() || OI->isFullCopy())
2109 ++OI;
2110 while (NI->isPHI() || NI->isFullCopy())
2111 ++NI;
2112 assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
2113 // Analyze every operand separately.
2114 for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
2115 OOpI != OI->operands_end(); ++OOpI, ++NOpI)
2116 KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
2117 KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
2118 }
2119
2120 bool Failed = false;
2121 for (auto &OldAndNew : KOIs) {
2122 if (OldAndNew.first == OldAndNew.second)
2123 continue;
2124 Failed = true;
2125 errs() << "Modulo kernel validation error: [\n";
2126 errs() << " [golden] ";
2127 OldAndNew.first.print(errs());
2128 errs() << " ";
2129 OldAndNew.second.print(errs());
2130 errs() << "]\n";
2131 }
2132
2133 if (Failed) {
2134 errs() << "Golden reference kernel:\n";
2135 ExpandedKernel->print(errs());
2136 errs() << "New kernel:\n";
2137 BB->print(errs());
2138 errs() << ScheduleDump;
2140 "Modulo kernel validation (-pipeliner-experimental-cg) failed");
2141 }
2142
2143 // Cleanup by removing BB from the CFG again as the original
2144 // ModuloScheduleExpander intended.
2145 Preheader->removeSuccessor(BB);
2146 MDTU.applyUpdates({{MachineDominatorTree::Delete, Preheader, BB}});
2147 MSE.cleanup();
2148}
2149
2150MachineInstr *ModuloScheduleExpanderMVE::cloneInstr(MachineInstr *OldMI) {
2151 MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2152
2153 // TODO: Offset information needs to be corrected.
2154 NewMI->dropMemRefs(MF);
2155
2156 return NewMI;
2157}
2158
2159/// Create a dedicated exit for Loop. Exit is the original exit for Loop.
2160/// If it is already dedicated exit, return it. Otherwise, insert a new
2161/// block between them and return the new block.
2163 MachineBasicBlock *Exit,
2164 LiveIntervals &LIS,
2165 MachineDomTreeUpdater &MDTU) {
2166 if (Exit->pred_size() == 1)
2167 return Exit;
2168
2169 MachineFunction *MF = Loop->getParent();
2171
2172 MachineBasicBlock *NewExit =
2173 MF->CreateMachineBasicBlock(Loop->getBasicBlock());
2174 MF->insert(Loop->getIterator(), NewExit);
2175 LIS.insertMBBInMaps(NewExit);
2176
2177 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2179 TII->analyzeBranch(*Loop, TBB, FBB, Cond);
2180 if (TBB == Loop)
2181 FBB = NewExit;
2182 else if (FBB == Loop)
2183 TBB = NewExit;
2184 else
2185 llvm_unreachable("unexpected loop structure");
2186 TII->removeBranch(*Loop);
2187 TII->insertBranch(*Loop, TBB, FBB, Cond, DebugLoc());
2188 Loop->replaceSuccessor(Exit, NewExit);
2189 TII->insertUnconditionalBranch(*NewExit, Exit, DebugLoc());
2190 NewExit->addSuccessor(Exit);
2191 MDTU.splitCriticalEdge(Loop, Exit, NewExit);
2192
2193 Exit->replacePhiUsesWith(Loop, NewExit);
2194
2195 return NewExit;
2196}
2197
2198/// Insert branch code into the end of MBB. It branches to GreaterThan if the
2199/// remaining trip count for instructions in LastStage0Insts is greater than
2200/// RequiredTC, and to Otherwise otherwise.
2201void ModuloScheduleExpanderMVE::insertCondBranch(MachineBasicBlock &MBB,
2202 int RequiredTC,
2203 InstrMapTy &LastStage0Insts,
2204 MachineBasicBlock &GreaterThan,
2205 MachineBasicBlock &Otherwise) {
2206 SmallVector<MachineOperand, 4> Cond;
2207 LoopInfo->createRemainingIterationsGreaterCondition(RequiredTC, MBB, Cond,
2208 LastStage0Insts);
2209
2210 if (getCodeGenOptions(MF).pipeliner_swap_branch_targets_mve) {
2211 // Set -pipeliner-swap-branch-targets-mve to true if a target prefers to
2212 // replace TBB and FBB for optimal performance.
2214 llvm_unreachable("can not reverse branch condition");
2215 TII->insertBranch(MBB, &Otherwise, &GreaterThan, Cond, DebugLoc());
2216 } else {
2217 TII->insertBranch(MBB, &GreaterThan, &Otherwise, Cond, DebugLoc());
2218 }
2219}
2220
2221/// Generate a pipelined loop that is unrolled by using MVE algorithm and any
2222/// other necessary blocks. The control flow is modified to execute the
2223/// pipelined loop if the trip count satisfies the condition, otherwise the
2224/// original loop. The original loop is also used to execute the remainder
2225/// iterations which occur due to unrolling.
2226void ModuloScheduleExpanderMVE::generatePipelinedLoop() {
2227 // The control flow for pipelining with MVE:
2228 //
2229 // OrigPreheader:
2230 // // The block that is originally the loop preheader
2231 // goto Check
2232 //
2233 // Check:
2234 // // Check whether the trip count satisfies the requirements to pipeline.
2235 // if (LoopCounter > NumStages + NumUnroll - 2)
2236 // // The minimum number of iterations to pipeline =
2237 // // iterations executed in prolog/epilog (NumStages-1) +
2238 // // iterations executed in one kernel run (NumUnroll)
2239 // goto Prolog
2240 // // fallback to the original loop
2241 // goto NewPreheader
2242 //
2243 // Prolog:
2244 // // All prolog stages. There are no direct branches to the epilogue.
2245 // goto NewKernel
2246 //
2247 // NewKernel:
2248 // // NumUnroll copies of the kernel
2249 // if (LoopCounter > MVE-1)
2250 // goto NewKernel
2251 // goto Epilog
2252 //
2253 // Epilog:
2254 // // All epilog stages.
2255 // if (LoopCounter > 0)
2256 // // The remainder is executed in the original loop
2257 // goto NewPreheader
2258 // goto NewExit
2259 //
2260 // NewPreheader:
2261 // // Newly created preheader for the original loop.
2262 // // The initial values of the phis in the loop are merged from two paths.
2263 // NewInitVal = Phi OrigInitVal, Check, PipelineLastVal, Epilog
2264 // goto OrigKernel
2265 //
2266 // OrigKernel:
2267 // // The original loop block.
2268 // if (LoopCounter != 0)
2269 // goto OrigKernel
2270 // goto NewExit
2271 //
2272 // NewExit:
2273 // // Newly created dedicated exit for the original loop.
2274 // // Merge values which are referenced after the loop
2275 // Merged = Phi OrigVal, OrigKernel, PipelineVal, Epilog
2276 // goto OrigExit
2277 //
2278 // OrigExit:
2279 // // The block that is originally the loop exit.
2280 // // If it is already deicated exit, NewExit is not created.
2281
2282 // An example of where each stage is executed:
2283 // Assume #Stages 3, #MVE 4, #Iterations 12
2284 // Iter 0 1 2 3 4 5 6 7 8 9 10-11
2285 // -------------------------------------------------
2286 // Stage 0 Prolog#0
2287 // Stage 1 0 Prolog#1
2288 // Stage 2 1 0 Kernel Unroll#0 Iter#0
2289 // Stage 2 1 0 Kernel Unroll#1 Iter#0
2290 // Stage 2 1 0 Kernel Unroll#2 Iter#0
2291 // Stage 2 1 0 Kernel Unroll#3 Iter#0
2292 // Stage 2 1 0 Kernel Unroll#0 Iter#1
2293 // Stage 2 1 0 Kernel Unroll#1 Iter#1
2294 // Stage 2 1 0 Kernel Unroll#2 Iter#1
2295 // Stage 2 1 0 Kernel Unroll#3 Iter#1
2296 // Stage 2 1 Epilog#0
2297 // Stage 2 Epilog#1
2298 // Stage 0-2 OrigKernel
2299
2300 LoopInfo = TII->analyzeLoopForPipelining(OrigKernel);
2301 assert(LoopInfo && "Must be able to analyze loop!");
2302
2303 calcNumUnroll();
2304
2305 Check = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
2306 Prolog = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
2307 NewKernel = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
2308 Epilog = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
2309 NewPreheader = MF.CreateMachineBasicBlock(OrigKernel->getBasicBlock());
2310
2311 MF.insert(OrigKernel->getIterator(), Check);
2313 MF.insert(OrigKernel->getIterator(), Prolog);
2315 MF.insert(OrigKernel->getIterator(), NewKernel);
2316 LIS.insertMBBInMaps(NewKernel);
2317 MF.insert(OrigKernel->getIterator(), Epilog);
2319 MF.insert(OrigKernel->getIterator(), NewPreheader);
2320 LIS.insertMBBInMaps(NewPreheader);
2321
2322 NewExit = createDedicatedExit(OrigKernel, OrigExit, LIS, MDTU);
2323
2324 NewPreheader->transferSuccessorsAndUpdatePHIs(OrigPreheader);
2325 TII->insertUnconditionalBranch(*NewPreheader, OrigKernel, DebugLoc());
2326
2327 OrigPreheader->addSuccessor(Check);
2328 TII->removeBranch(*OrigPreheader);
2329 TII->insertUnconditionalBranch(*OrigPreheader, Check, DebugLoc());
2330
2331 Check->addSuccessor(Prolog);
2332 Check->addSuccessor(NewPreheader);
2333
2334 Prolog->addSuccessor(NewKernel);
2335
2336 NewKernel->addSuccessor(NewKernel);
2337 NewKernel->addSuccessor(Epilog);
2338
2339 Epilog->addSuccessor(NewPreheader);
2340 Epilog->addSuccessor(NewExit);
2341
2342 MDTU.applyUpdates(
2343 {{MachineDominatorTree::Insert, NewPreheader, OrigKernel},
2344 {MachineDominatorTree::Insert, OrigPreheader, Check},
2345 {MachineDominatorTree::Insert, Check, Prolog},
2346 {MachineDominatorTree::Insert, Check, NewPreheader},
2347 {MachineDominatorTree::Insert, Prolog, NewKernel},
2348 {MachineDominatorTree::Insert, NewKernel, NewKernel},
2349 {MachineDominatorTree::Insert, NewKernel, Epilog},
2350 {MachineDominatorTree::Insert, Epilog, NewPreheader},
2351 {MachineDominatorTree::Insert, Epilog, NewExit},
2352 {MachineDominatorTree::Delete, OrigPreheader, OrigKernel}});
2353
2354 InstrMapTy LastStage0Insts;
2355 insertCondBranch(*Check, Schedule.getNumStages() + NumUnroll - 2,
2356 LastStage0Insts, *Prolog, *NewPreheader);
2357
2358 // VRMaps map (prolog/kernel/epilog phase#, original register#) to new
2359 // register#
2360 SmallVector<ValueMapTy> PrologVRMap, KernelVRMap, EpilogVRMap;
2361 generateProlog(PrologVRMap);
2362 generateKernel(PrologVRMap, KernelVRMap, LastStage0Insts);
2363 generateEpilog(KernelVRMap, EpilogVRMap, LastStage0Insts);
2364}
2365
2366/// Replace MI's use operands according to the maps.
2367void ModuloScheduleExpanderMVE::updateInstrUse(
2368 MachineInstr *MI, int StageNum, int PhaseNum,
2369 SmallVectorImpl<ValueMapTy> &CurVRMap,
2370 SmallVectorImpl<ValueMapTy> *PrevVRMap) {
2371 // If MI is in the prolog/kernel/epilog block, CurVRMap is
2372 // PrologVRMap/KernelVRMap/EpilogVRMap respectively.
2373 // PrevVRMap is nullptr/PhiVRMap/KernelVRMap respectively.
2374 // Refer to the appropriate map according to the stage difference between
2375 // MI and the definition of an operand.
2376
2377 for (MachineOperand &UseMO : MI->uses()) {
2378 if (!UseMO.isReg() || !UseMO.getReg().isVirtual())
2379 continue;
2380 int DiffStage = 0;
2381 Register OrigReg = UseMO.getReg();
2382 MachineInstr *DefInst = MRI.getVRegDef(OrigReg);
2383 if (!DefInst || DefInst->getParent() != OrigKernel)
2384 continue;
2385 Register InitReg;
2386 Register DefReg = OrigReg;
2387 if (DefInst->isPHI()) {
2388 ++DiffStage;
2389 Register LoopReg;
2390 getPhiRegs(*DefInst, OrigKernel, InitReg, LoopReg);
2391 // LoopReg is guaranteed to be defined within the loop by canApply()
2392 DefReg = LoopReg;
2393 DefInst = MRI.getVRegDef(LoopReg);
2394 }
2395 unsigned DefStageNum = Schedule.getStage(DefInst);
2396 DiffStage += StageNum - DefStageNum;
2397 Register NewReg;
2398 if (PhaseNum >= DiffStage && CurVRMap[PhaseNum - DiffStage].count(DefReg))
2399 // NewReg is defined in a previous phase of the same block
2400 NewReg = CurVRMap[PhaseNum - DiffStage][DefReg];
2401 else if (!PrevVRMap)
2402 // Since this is the first iteration, refer the initial register of the
2403 // loop
2404 NewReg = InitReg;
2405 else
2406 // Cases where DiffStage is larger than PhaseNum.
2407 // If MI is in the kernel block, the value is defined by the previous
2408 // iteration and PhiVRMap is referenced. If MI is in the epilog block, the
2409 // value is defined in the kernel block and KernelVRMap is referenced.
2410 NewReg = (*PrevVRMap)[PrevVRMap->size() - (DiffStage - PhaseNum)][DefReg];
2411
2412 const TargetRegisterClass *NRC =
2413 MRI.constrainRegClass(NewReg, MRI.getRegClass(OrigReg));
2414 if (NRC)
2415 UseMO.setReg(NewReg);
2416 else {
2417 Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OrigReg));
2418 MachineInstr *NewCopy = BuildMI(*OrigKernel, MI, MI->getDebugLoc(),
2419 TII->get(TargetOpcode::COPY), SplitReg)
2420 .addReg(NewReg);
2421 LIS.InsertMachineInstrInMaps(*NewCopy);
2422 UseMO.setReg(SplitReg);
2423 }
2424 }
2425}
2426
2427/// Return a phi if Reg is referenced by the phi.
2428/// canApply() guarantees that at most only one such phi exists.
2430 for (MachineInstr &Phi : Loop->phis()) {
2431 Register InitVal, LoopVal;
2432 getPhiRegs(Phi, Loop, InitVal, LoopVal);
2433 if (LoopVal == Reg)
2434 return &Phi;
2435 }
2436 return nullptr;
2437}
2438
2439/// Generate phis for registers defined by OrigMI.
2440void ModuloScheduleExpanderMVE::generatePhi(
2441 MachineInstr *OrigMI, int UnrollNum,
2442 SmallVectorImpl<ValueMapTy> &PrologVRMap,
2443 SmallVectorImpl<ValueMapTy> &KernelVRMap,
2444 SmallVectorImpl<ValueMapTy> &PhiVRMap) {
2445 int StageNum = Schedule.getStage(OrigMI);
2446 bool UsePrologReg;
2447 if (Schedule.getNumStages() - NumUnroll + UnrollNum - 1 >= StageNum)
2448 UsePrologReg = true;
2449 else if (Schedule.getNumStages() - NumUnroll + UnrollNum == StageNum)
2450 UsePrologReg = false;
2451 else
2452 return;
2453
2454 // Examples that show which stages are merged by phi.
2455 // Meaning of the symbol following the stage number:
2456 // a/b: Stages with the same letter are merged (UsePrologReg == true)
2457 // +: Merged with the initial value (UsePrologReg == false)
2458 // *: No phis required
2459 //
2460 // #Stages 3, #MVE 4
2461 // Iter 0 1 2 3 4 5 6 7 8
2462 // -----------------------------------------
2463 // Stage 0a Prolog#0
2464 // Stage 1a 0b Prolog#1
2465 // Stage 2* 1* 0* Kernel Unroll#0
2466 // Stage 2* 1* 0+ Kernel Unroll#1
2467 // Stage 2* 1+ 0a Kernel Unroll#2
2468 // Stage 2+ 1a 0b Kernel Unroll#3
2469 //
2470 // #Stages 3, #MVE 2
2471 // Iter 0 1 2 3 4 5 6 7 8
2472 // -----------------------------------------
2473 // Stage 0a Prolog#0
2474 // Stage 1a 0b Prolog#1
2475 // Stage 2* 1+ 0a Kernel Unroll#0
2476 // Stage 2+ 1a 0b Kernel Unroll#1
2477 //
2478 // #Stages 3, #MVE 1
2479 // Iter 0 1 2 3 4 5 6 7 8
2480 // -----------------------------------------
2481 // Stage 0* Prolog#0
2482 // Stage 1a 0b Prolog#1
2483 // Stage 2+ 1a 0b Kernel Unroll#0
2484
2485 for (MachineOperand &DefMO : OrigMI->defs()) {
2486 if (!DefMO.isReg() || DefMO.isDead())
2487 continue;
2488 Register OrigReg = DefMO.getReg();
2489 auto NewReg = KernelVRMap[UnrollNum].find(OrigReg);
2490 if (NewReg == KernelVRMap[UnrollNum].end())
2491 continue;
2492 Register CorrespondReg;
2493 if (UsePrologReg) {
2494 int PrologNum = Schedule.getNumStages() - NumUnroll + UnrollNum - 1;
2495 CorrespondReg = PrologVRMap[PrologNum][OrigReg];
2496 } else {
2497 MachineInstr *Phi = getLoopPhiUser(OrigReg, OrigKernel);
2498 if (!Phi)
2499 continue;
2500 CorrespondReg = getInitPhiReg(*Phi, OrigKernel);
2501 }
2502
2503 assert(CorrespondReg.isValid());
2505 MachineInstr *NewPhi =
2506 BuildMI(*NewKernel, NewKernel->getFirstNonPHI(), DebugLoc(),
2507 TII->get(TargetOpcode::PHI), PhiReg)
2508 .addReg(NewReg->second)
2509 .addMBB(NewKernel)
2510 .addReg(CorrespondReg)
2511 .addMBB(Prolog);
2512 LIS.InsertMachineInstrInMaps(*NewPhi);
2513 PhiVRMap[UnrollNum][OrigReg] = PhiReg;
2514 }
2515}
2516
2517static void replacePhiSrc(MachineInstr &Phi, Register OrigReg, Register NewReg,
2518 MachineBasicBlock *NewMBB) {
2519 for (unsigned Idx = 1; Idx < Phi.getNumOperands(); Idx += 2) {
2520 if (Phi.getOperand(Idx).getReg() == OrigReg) {
2521 Phi.getOperand(Idx).setReg(NewReg);
2522 Phi.getOperand(Idx + 1).setMBB(NewMBB);
2523 return;
2524 }
2525 }
2526}
2527
2528/// Generate phis that merge values from multiple routes
2529void ModuloScheduleExpanderMVE::mergeRegUsesAfterPipeline(Register OrigReg,
2530 Register NewReg) {
2531 SmallVector<MachineOperand *> UsesAfterLoop;
2534 E = MRI.use_end();
2535 I != E; ++I) {
2536 MachineOperand &O = *I;
2537 if (O.getParent()->getParent() != OrigKernel &&
2538 O.getParent()->getParent() != Prolog &&
2539 O.getParent()->getParent() != NewKernel &&
2540 O.getParent()->getParent() != Epilog)
2541 UsesAfterLoop.push_back(&O);
2542 if (O.getParent()->getParent() == OrigKernel && O.getParent()->isPHI())
2543 LoopPhis.push_back(O.getParent());
2544 }
2545
2546 // Merge the route that only execute the pipelined loop (when there are no
2547 // remaining iterations) with the route that execute the original loop.
2548 if (!UsesAfterLoop.empty()) {
2550 MachineInstr *NewPhi =
2551 BuildMI(*NewExit, NewExit->getFirstNonPHI(), DebugLoc(),
2552 TII->get(TargetOpcode::PHI), PhiReg)
2553 .addReg(OrigReg)
2554 .addMBB(OrigKernel)
2555 .addReg(NewReg)
2556 .addMBB(Epilog);
2557 LIS.InsertMachineInstrInMaps(*NewPhi);
2558
2559 for (MachineOperand *MO : UsesAfterLoop)
2560 MO->setReg(PhiReg);
2561
2562 // The interval of OrigReg is invalid and should be recalculated when
2563 // LiveInterval::getInterval() is called.
2564 if (LIS.hasInterval(OrigReg))
2565 LIS.removeInterval(OrigReg);
2566 }
2567
2568 // Merge routes from the pipelined loop and the bypassed route before the
2569 // original loop
2570 if (!LoopPhis.empty()) {
2571 for (MachineInstr *Phi : LoopPhis) {
2572 Register InitReg, LoopReg;
2573 getPhiRegs(*Phi, OrigKernel, InitReg, LoopReg);
2574 Register NewInit = MRI.createVirtualRegister(MRI.getRegClass(InitReg));
2575 MachineInstr *NewPhi =
2576 BuildMI(*NewPreheader, NewPreheader->getFirstNonPHI(),
2577 Phi->getDebugLoc(), TII->get(TargetOpcode::PHI), NewInit)
2578 .addReg(InitReg)
2579 .addMBB(Check)
2580 .addReg(NewReg)
2581 .addMBB(Epilog);
2582 LIS.InsertMachineInstrInMaps(*NewPhi);
2583 replacePhiSrc(*Phi, InitReg, NewInit, NewPreheader);
2584 }
2585 }
2586}
2587
2588void ModuloScheduleExpanderMVE::generateProlog(
2589 SmallVectorImpl<ValueMapTy> &PrologVRMap) {
2590 PrologVRMap.clear();
2591 PrologVRMap.resize(Schedule.getNumStages() - 1);
2592 DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
2593 for (int PrologNum = 0; PrologNum < Schedule.getNumStages() - 1;
2594 ++PrologNum) {
2595 for (MachineInstr *MI : Schedule.getInstructions()) {
2596 if (MI->isPHI())
2597 continue;
2598 int StageNum = Schedule.getStage(MI);
2599 if (StageNum > PrologNum)
2600 continue;
2601 MachineInstr *NewMI = cloneInstr(MI);
2602 updateInstrDef(NewMI, PrologVRMap[PrologNum], false);
2603 NewMIMap[NewMI] = {PrologNum, StageNum};
2604 Prolog->push_back(NewMI);
2605 LIS.InsertMachineInstrInMaps(*NewMI);
2606 }
2607 }
2608
2609 for (auto I : NewMIMap) {
2610 MachineInstr *MI = I.first;
2611 int PrologNum = I.second.first;
2612 int StageNum = I.second.second;
2613 updateInstrUse(MI, StageNum, PrologNum, PrologVRMap, nullptr);
2614 }
2615
2616 LLVM_DEBUG({
2617 dbgs() << "prolog:\n";
2618 Prolog->dump();
2619 });
2620}
2621
2622void ModuloScheduleExpanderMVE::generateKernel(
2623 SmallVectorImpl<ValueMapTy> &PrologVRMap,
2624 SmallVectorImpl<ValueMapTy> &KernelVRMap, InstrMapTy &LastStage0Insts) {
2625 KernelVRMap.clear();
2626 KernelVRMap.resize(NumUnroll);
2627 SmallVector<ValueMapTy> PhiVRMap;
2628 PhiVRMap.resize(NumUnroll);
2629 DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
2630 for (int UnrollNum = 0; UnrollNum < NumUnroll; ++UnrollNum) {
2631 for (MachineInstr *MI : Schedule.getInstructions()) {
2632 if (MI->isPHI())
2633 continue;
2634 int StageNum = Schedule.getStage(MI);
2635 MachineInstr *NewMI = cloneInstr(MI);
2636 if (UnrollNum == NumUnroll - 1)
2637 LastStage0Insts[MI] = NewMI;
2638 updateInstrDef(NewMI, KernelVRMap[UnrollNum],
2639 (UnrollNum == NumUnroll - 1 && StageNum == 0));
2640 generatePhi(MI, UnrollNum, PrologVRMap, KernelVRMap, PhiVRMap);
2641 NewMIMap[NewMI] = {UnrollNum, StageNum};
2642 NewKernel->push_back(NewMI);
2643 LIS.InsertMachineInstrInMaps(*NewMI);
2644 }
2645 }
2646
2647 for (auto I : NewMIMap) {
2648 MachineInstr *MI = I.first;
2649 int UnrollNum = I.second.first;
2650 int StageNum = I.second.second;
2651 updateInstrUse(MI, StageNum, UnrollNum, KernelVRMap, &PhiVRMap);
2652 }
2653
2654 // If remaining trip count is greater than NumUnroll-1, loop continues
2655 insertCondBranch(*NewKernel, NumUnroll - 1, LastStage0Insts, *NewKernel,
2656 *Epilog);
2657
2658 LLVM_DEBUG({
2659 dbgs() << "kernel:\n";
2660 NewKernel->dump();
2661 });
2662}
2663
2664void ModuloScheduleExpanderMVE::generateEpilog(
2665 SmallVectorImpl<ValueMapTy> &KernelVRMap,
2666 SmallVectorImpl<ValueMapTy> &EpilogVRMap, InstrMapTy &LastStage0Insts) {
2667 EpilogVRMap.clear();
2668 EpilogVRMap.resize(Schedule.getNumStages() - 1);
2669 DenseMap<MachineInstr *, std::pair<int, int>> NewMIMap;
2670 for (int EpilogNum = 0; EpilogNum < Schedule.getNumStages() - 1;
2671 ++EpilogNum) {
2672 for (MachineInstr *MI : Schedule.getInstructions()) {
2673 if (MI->isPHI())
2674 continue;
2675 int StageNum = Schedule.getStage(MI);
2676 if (StageNum <= EpilogNum)
2677 continue;
2678 MachineInstr *NewMI = cloneInstr(MI);
2679 updateInstrDef(NewMI, EpilogVRMap[EpilogNum], StageNum - 1 == EpilogNum);
2680 NewMIMap[NewMI] = {EpilogNum, StageNum};
2681 Epilog->push_back(NewMI);
2682 LIS.InsertMachineInstrInMaps(*NewMI);
2683 }
2684 }
2685
2686 for (auto I : NewMIMap) {
2687 MachineInstr *MI = I.first;
2688 int EpilogNum = I.second.first;
2689 int StageNum = I.second.second;
2690 updateInstrUse(MI, StageNum, EpilogNum, EpilogVRMap, &KernelVRMap);
2691 }
2692
2693 // If there are remaining iterations, they are executed in the original loop.
2694 // Instructions related to loop control, such as loop counter comparison,
2695 // are indicated by shouldIgnoreForPipelining() and are assumed to be placed
2696 // in stage 0. Thus, the map is for the last one in the kernel.
2697 insertCondBranch(*Epilog, 0, LastStage0Insts, *NewPreheader, *NewExit);
2698
2699 LLVM_DEBUG({
2700 dbgs() << "epilog:\n";
2701 Epilog->dump();
2702 });
2703}
2704
2705/// Calculate the number of unroll required and set it to NumUnroll
2706void ModuloScheduleExpanderMVE::calcNumUnroll() {
2707 DenseMap<MachineInstr *, unsigned> Inst2Idx;
2708 NumUnroll = 1;
2709 for (unsigned I = 0; I < Schedule.getInstructions().size(); ++I)
2710 Inst2Idx[Schedule.getInstructions()[I]] = I;
2711
2712 for (MachineInstr *MI : Schedule.getInstructions()) {
2713 if (MI->isPHI())
2714 continue;
2715 int StageNum = Schedule.getStage(MI);
2716 for (const MachineOperand &MO : MI->uses()) {
2717 if (!MO.isReg() || !MO.getReg().isVirtual())
2718 continue;
2719 MachineInstr *DefMI = MRI.getVRegDef(MO.getReg());
2720 if (DefMI->getParent() != OrigKernel)
2721 continue;
2722
2723 int NumUnrollLocal = 1;
2724 if (DefMI->isPHI()) {
2725 ++NumUnrollLocal;
2726 // canApply() guarantees that DefMI is not phi and is an instruction in
2727 // the loop
2728 DefMI = MRI.getVRegDef(getLoopPhiReg(*DefMI, OrigKernel));
2729 }
2730 NumUnrollLocal += StageNum - Schedule.getStage(DefMI);
2731 if (Inst2Idx[MI] <= Inst2Idx[DefMI])
2732 --NumUnrollLocal;
2733 NumUnroll = std::max(NumUnroll, NumUnrollLocal);
2734 }
2735 }
2736 LLVM_DEBUG(dbgs() << "NumUnroll: " << NumUnroll << "\n");
2737}
2738
2739/// Create new virtual registers for definitions of NewMI and update NewMI.
2740/// If the definitions are referenced after the pipelined loop, phis are
2741/// created to merge with other routes.
2742void ModuloScheduleExpanderMVE::updateInstrDef(MachineInstr *NewMI,
2743 ValueMapTy &VRMap,
2744 bool LastDef) {
2745 for (MachineOperand &MO : NewMI->all_defs()) {
2746 if (!MO.getReg().isVirtual())
2747 continue;
2748 Register Reg = MO.getReg();
2750 Register NewReg = MRI.createVirtualRegister(RC);
2751 MO.setReg(NewReg);
2752 VRMap[Reg] = NewReg;
2753 if (LastDef)
2754 mergeRegUsesAfterPipeline(Reg, NewReg);
2755 }
2756}
2757
2759 OrigKernel = Schedule.getLoop()->getTopBlock();
2760 OrigPreheader = Schedule.getLoop()->getLoopPreheader();
2761 OrigExit = Schedule.getLoop()->getExitBlock();
2762
2763 LLVM_DEBUG(Schedule.dump());
2764
2765 generatePipelinedLoop();
2766}
2767
2768/// Check if ModuloScheduleExpanderMVE can be applied to L
2770 if (!L.getExitBlock()) {
2771 LLVM_DEBUG(dbgs() << "Can not apply MVE expander: No single exit block.\n");
2772 return false;
2773 }
2774
2775 MachineBasicBlock *BB = L.getTopBlock();
2777
2778 // Put some constraints on the operands of the phis to simplify the
2779 // transformation
2780 DenseSet<Register> UsedByPhi;
2781 for (MachineInstr &MI : BB->phis()) {
2782 // Registers defined by phis must be used only inside the loop and be never
2783 // used by phis.
2784 for (MachineOperand &MO : MI.defs())
2785 if (MO.isReg())
2786 for (MachineInstr &Ref : MRI.use_instructions(MO.getReg()))
2787 if (Ref.getParent() != BB || Ref.isPHI()) {
2788 LLVM_DEBUG(dbgs() << "Can not apply MVE expander: A phi result is "
2789 "referenced outside of the loop or by phi.\n");
2790 return false;
2791 }
2792
2793 // A source register from the loop block must be defined inside the loop.
2794 // A register defined inside the loop must be referenced by only one phi at
2795 // most.
2796 Register InitVal, LoopVal;
2797 getPhiRegs(MI, MI.getParent(), InitVal, LoopVal);
2798 if (!Register(LoopVal).isVirtual() || MRI.getDefBlock(LoopVal) != BB) {
2799 LLVM_DEBUG(
2800 dbgs() << "Can not apply MVE expander: A phi source value coming "
2801 "from the loop is not defined in the loop.\n");
2802 return false;
2803 }
2804 if (UsedByPhi.count(LoopVal)) {
2805 LLVM_DEBUG(dbgs() << "Can not apply MVE expander: A value defined in the "
2806 "loop is referenced by two or more phis.\n");
2807 return false;
2808 }
2809 UsedByPhi.insert(LoopVal);
2810 }
2811
2812 return true;
2813}
2814
2815//===----------------------------------------------------------------------===//
2816// ModuloScheduleTestPass implementation
2817//===----------------------------------------------------------------------===//
2818// This pass constructs a ModuloSchedule from its module and runs
2819// ModuloScheduleExpander.
2820//
2821// The module is expected to contain a single-block analyzable loop.
2822// The total order of instructions is taken from the loop as-is.
2823// Instructions are expected to be annotated with a PostInstrSymbol.
2824// This PostInstrSymbol must have the following format:
2825// "Stage=%d Cycle=%d".
2826//===----------------------------------------------------------------------===//
2827
2828namespace {
2829class ModuloScheduleTest : public MachineFunctionPass {
2830public:
2831 static char ID;
2832
2833 ModuloScheduleTest() : MachineFunctionPass(ID) {}
2834
2835 bool runOnMachineFunction(MachineFunction &MF) override;
2836 void runOnLoop(MachineFunction &MF, MachineLoop &L);
2837
2838 void getAnalysisUsage(AnalysisUsage &AU) const override {
2842 }
2843};
2844} // namespace
2845
2846char ModuloScheduleTest::ID = 0;
2847
2848INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
2849 "Modulo Schedule test pass", false, false)
2852INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
2853 "Modulo Schedule test pass", false, false)
2854
2855bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
2856 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2857 for (auto *L : MLI) {
2858 if (L->getTopBlock() != L->getBottomBlock())
2859 continue;
2860 runOnLoop(MF, *L);
2861 return false;
2862 }
2863 return false;
2864}
2865
2866static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
2867 std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
2868 std::pair<StringRef, StringRef> StageTokenAndValue =
2869 getToken(StageAndCycle.first, "-");
2870 std::pair<StringRef, StringRef> CycleTokenAndValue =
2871 getToken(StageAndCycle.second, "-");
2872 if (StageTokenAndValue.first != "Stage" ||
2873 CycleTokenAndValue.first != "_Cycle") {
2875 "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
2876 return;
2877 }
2878
2879 StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
2880 CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
2881
2882 dbgs() << " Stage=" << Stage << ", Cycle=" << Cycle << "\n";
2883}
2884
2885void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
2886 LiveIntervals &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
2887 MachineBasicBlock *BB = L.getTopBlock();
2888 dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
2889
2890 DenseMap<MachineInstr *, int> Cycle, Stage;
2891 std::vector<MachineInstr *> Instrs;
2892 for (MachineInstr &MI : *BB) {
2893 if (MI.isTerminator())
2894 continue;
2895 Instrs.push_back(&MI);
2896 if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
2897 dbgs() << "Parsing post-instr symbol for " << MI;
2898 parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
2899 }
2900 }
2901
2902 ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
2903 std::move(Stage));
2904 ModuloScheduleExpander MSE(
2905 MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
2906 MSE.expand();
2907 MSE.cleanup();
2908}
2909
2910//===----------------------------------------------------------------------===//
2911// ModuloScheduleTestAnnotater implementation
2912//===----------------------------------------------------------------------===//
2913
2915 for (MachineInstr *MI : S.getInstructions()) {
2917 raw_svector_ostream OS(SV);
2918 OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
2919 MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
2920 MI->setPostInstrSymbol(MF, Sym);
2921 }
2922}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum, Register ReplaceReg, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertTo)
Clone an instruction from MI.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
Rewrite undef for PHI
MachineBasicBlock & MBB
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static const Function * getParent(const Value *V)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Default
#define Check(C,...)
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
static Register getLoopPhiReg(const MachineInstr &Phi, const MachineBasicBlock *LoopBB)
Return the Phi register value that comes the loop block.
static void getPhiRegs(const MachineInstr &Phi, const MachineBasicBlock *Loop, Register &InitVal, Register &LoopVal)
Return the register values for the operands of a Phi instruction.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file provides utility analysis objects describing memory locations.
static bool hasUseAfterLoop(Register Reg, MachineBasicBlock *BB, MachineRegisterInfo &MRI)
Return true if the register has a use that occurs outside the specified loop.
static void replaceRegUsesAfterLoop(Register FromReg, Register ToReg, MachineBasicBlock *MBB, MachineRegisterInfo &MRI)
Replace all uses of FromReg that appear outside the specified basic block with ToReg.
static void replacePhiSrc(MachineInstr &Phi, Register OrigReg, Register NewReg, MachineBasicBlock *NewMBB)
static MachineInstr * getLoopPhiUser(Register Reg, MachineBasicBlock *Loop)
Return a phi if Reg is referenced by the phi.
static void parseSymbolString(StringRef S, int &Cycle, int &Stage)
static Register getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB)
Return the Phi register value that comes from the incoming block.
static MachineBasicBlock * createDedicatedExit(MachineBasicBlock *Loop, MachineBasicBlock *Exit, LiveIntervals &LIS, MachineDomTreeUpdater &MDTU)
Create a dedicated exit for Loop.
static void eraseBlock(MachineBasicBlock *MBB, LiveIntervals &LIS, MachineDomTreeUpdater &MDTU)
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
Remove Loads Into Fake Uses
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void splitCriticalEdge(BasicBlockT *FromBB, BasicBlockT *ToBB, BasicBlockT *NewBB)
Apply updates that the critical edge (FromBB, ToBB) has been split with NewBB.
bool hasInterval(Register Reg) const
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
void insertMBBInMaps(MachineBasicBlock *MBB)
Adds an empty block MBB to the SlotIndexes and regmask maps.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
void removeInterval(Register Reg)
Interval removal.
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
LLVM_ABI void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
reverse_instr_iterator instr_rbegin()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
void push_back(MachineInstr *MI)
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
MachineInstrBundleIterator< MachineInstr > iterator
Instructions::reverse_iterator reverse_instr_iterator
LLVM_ABI void deleteBB(MachineBasicBlock *DelBB)
Delete DelBB.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
unsigned getNumOperands() const
Retuns the total number of operands.
bool memoperands_empty() const
Return true if we don't have any memory operands which described the memory access done by this instr...
LLVM_ABI void setMemRefs(MachineFunction &MF, ArrayRef< MachineMemOperand * > MemRefs)
Assign this MachineInstr's memory reference descriptor list.
LLVM_ABI void dropMemRefs(MachineFunction &MF)
Clear this MachineInstr's memory reference descriptor list.
mop_range operands()
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
defusechain_iterator< true, false, false, true, false > use_iterator
use_iterator/use_begin/use_end - Walk all uses of the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
use_iterator use_begin(Register RegNo) const
static use_iterator use_end()
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static LLVM_ABI bool canApply(MachineLoop &L)
Check if ModuloScheduleExpanderMVE can be applied to L.
The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place, rewriting the old loop and...
MachineBasicBlock * getRewrittenKernel()
Returns the newly rewritten kernel block, or nullptr if this was optimized away.
LLVM_ABI void cleanup()
Performs final cleanup after expansion.
LLVM_ABI void expand()
Performs the actual expansion.
DenseMap< MachineInstr *, std::pair< Register, int64_t > > InstrChangesTy
LLVM_ABI void annotate()
Performs the annotation.
Represents a schedule for a single-block loop.
int getNumStages() const
Return the number of stages contained in this schedule, which is the largest stage index + 1.
ArrayRef< MachineInstr * > getInstructions()
Return the rescheduled instructions in order.
LLVM_ABI void print(raw_ostream &OS)
int getCycle(MachineInstr *MI)
Return the cycle that MI is scheduled at, or -1.
void setStage(MachineInstr *MI, int MIStage)
Set the stage of a newly created instruction.
int getStage(MachineInstr *MI)
Return the stage that MI is scheduled in, or -1.
std::deque< MachineBasicBlock * > PeeledBack
SmallVector< MachineInstr *, 4 > IllegalPhisToDelete
Illegal phis that need to be deleted once we re-link stages.
DenseMap< MachineInstr *, MachineInstr * > CanonicalMIs
CanonicalMIs and BlockMIs form a bidirectional map between any of the loop kernel clones.
SmallVector< MachineBasicBlock *, 4 > Prologs
All prolog and epilog blocks.
LLVM_ABI MachineBasicBlock * peelKernel(LoopPeelDirection LPD)
Peels one iteration of the rewritten kernel (BB) in the specified direction.
std::deque< MachineBasicBlock * > PeeledFront
State passed from peelKernel to peelPrologAndEpilogs().
unsigned getStage(MachineInstr *MI)
Helper to get the stage of an instruction in the schedule.
LLVM_ABI void rewriteUsesOf(MachineInstr *MI)
Change all users of MI, if MI is predicated out (LiveStages[MI->getParent()] == false).
SmallVector< MachineBasicBlock *, 4 > Epilogs
DenseMap< MachineBasicBlock *, BitVector > AvailableStages
For every block, the stages that are available.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > LoopInfo
Target loop info before kernel peeling.
DenseMap< std::pair< MachineBasicBlock *, MachineInstr * >, MachineInstr * > BlockMIs
LLVM_ABI Register getEquivalentRegisterIn(Register Reg, MachineBasicBlock *BB)
All prolog and epilog blocks are clones of the kernel, so any produced register in one block has an c...
MachineBasicBlock * Preheader
The original loop preheader.
LLVM_ABI void rewriteKernel()
Converts BB from the original loop body to the rewritten, pipelined steady-state.
DenseMap< MachineInstr *, unsigned > PhiNodeLoopIteration
When peeling the epilogue keep track of the distance between the phi nodes and the kernel.
DenseMap< MachineBasicBlock *, BitVector > LiveStages
For every block, the stages that are produced.
LLVM_ABI void filterInstructions(MachineBasicBlock *MB, int MinStage)
LLVM_ABI void peelPrologAndEpilogs()
Peel the kernel forwards and backwards to produce prologs and epilogs, and stitch them together.
MachineBasicBlock * BB
The original loop block that gets rewritten in-place.
LLVM_ABI void fixupBranches()
Insert branches between prologs, kernel and epilogs.
LLVM_ABI MachineBasicBlock * CreateLCSSAExitingBlock()
Create a poor-man's LCSSA by cloning only the PHIs from the kernel block to a block dominated by all ...
LLVM_ABI void validateAgainstModuloScheduleExpander()
Runs ModuloScheduleExpander and treats it as a golden input to validate aspects of the code generated...
LLVM_ABI Register getPhiCanonicalReg(MachineInstr *CanonicalPhi, MachineInstr *Phi)
Helper function to find the right canonical register for a phi instruction coming from a peeled out p...
LLVM_ABI void moveStageBetweenBlocks(MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetInstrInfo * getInstrInfo() const
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool used(const UsedT *U, size_t I)
Definition DenseMap.h:117
constexpr double phi
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
iterator end() const
Definition BasicBlock.h:89
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MachineBasicBlock * PeelSingleBlockLoop(LoopPeelDirection Direction, MachineBasicBlock *Loop, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineDomTreeUpdater *MDTU=nullptr)
Peels a single block loop.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
@ LPD_Back
Peel the last iteration of the loop.
@ LPD_Front
Peel the first iteration of the loop.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881