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