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