xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 3197eb69812f9ff1c0ef4b2a7b894397dec3de24)
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief This pass lowers the pseudo control flow instructions to real
12 /// machine instructions.
13 ///
14 /// All control flow is handled using predicated instructions and
15 /// a predicate stack.  Each Scalar ALU controls the operations of 64 Vector
16 /// ALUs.  The Scalar ALU can update the predicate for any of the Vector ALUs
17 /// by writting to the 64-bit EXEC register (each bit corresponds to a
18 /// single vector ALU).  Typically, for predicates, a vector ALU will write
19 /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
20 /// Vector ALU) and then the ScalarALU will AND the VCC register with the
21 /// EXEC to update the predicates.
22 ///
23 /// For example:
24 /// %VCC = V_CMP_GT_F32 %VGPR1, %VGPR2
25 /// %SGPR0 = SI_IF %VCC
26 ///   %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0
27 /// %SGPR0 = SI_ELSE %SGPR0
28 ///   %VGPR0 = V_SUB_F32 %VGPR0, %VGPR0
29 /// SI_END_CF %SGPR0
30 ///
31 /// becomes:
32 ///
33 /// %SGPR0 = S_AND_SAVEEXEC_B64 %VCC  // Save and update the exec mask
34 /// %SGPR0 = S_XOR_B64 %SGPR0, %EXEC  // Clear live bits from saved exec mask
35 /// S_CBRANCH_EXECZ label0            // This instruction is an optional
36 ///                                   // optimization which allows us to
37 ///                                   // branch if all the bits of
38 ///                                   // EXEC are zero.
39 /// %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0 // Do the IF block of the branch
40 ///
41 /// label0:
42 /// %SGPR0 = S_OR_SAVEEXEC_B64 %EXEC   // Restore the exec mask for the Then block
43 /// %EXEC = S_XOR_B64 %SGPR0, %EXEC    // Clear live bits from saved exec mask
44 /// S_BRANCH_EXECZ label1              // Use our branch optimization
45 ///                                    // instruction again.
46 /// %VGPR0 = V_SUB_F32 %VGPR0, %VGPR   // Do the THEN block
47 /// label1:
48 /// %EXEC = S_OR_B64 %EXEC, %SGPR0     // Re-enable saved exec mask bits
49 //===----------------------------------------------------------------------===//
50 
51 #include "AMDGPU.h"
52 #include "AMDGPUSubtarget.h"
53 #include "SIInstrInfo.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
57 #include "llvm/CodeGen/MachineBasicBlock.h"
58 #include "llvm/CodeGen/MachineFunction.h"
59 #include "llvm/CodeGen/MachineFunctionPass.h"
60 #include "llvm/CodeGen/MachineInstr.h"
61 #include "llvm/CodeGen/MachineInstrBuilder.h"
62 #include "llvm/CodeGen/MachineOperand.h"
63 #include "llvm/CodeGen/MachineRegisterInfo.h"
64 #include "llvm/CodeGen/Passes.h"
65 #include "llvm/CodeGen/SlotIndexes.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/Pass.h"
68 #include "llvm/Target/TargetRegisterInfo.h"
69 #include <cassert>
70 #include <iterator>
71 
72 using namespace llvm;
73 
74 #define DEBUG_TYPE "si-lower-control-flow"
75 
76 namespace {
77 
78 class SILowerControlFlow : public MachineFunctionPass {
79 private:
80   const SIRegisterInfo *TRI = nullptr;
81   const SIInstrInfo *TII = nullptr;
82   LiveIntervals *LIS = nullptr;
83   MachineRegisterInfo *MRI = nullptr;
84 
85   void emitIf(MachineInstr &MI);
86   void emitElse(MachineInstr &MI);
87   void emitBreak(MachineInstr &MI);
88   void emitIfBreak(MachineInstr &MI);
89   void emitElseBreak(MachineInstr &MI);
90   void emitLoop(MachineInstr &MI);
91   void emitEndCf(MachineInstr &MI);
92 
93   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
94                         SmallVectorImpl<MachineOperand> &Src) const;
95 
96   void combineMasks(MachineInstr &MI);
97 
98 public:
99   static char ID;
100 
101   SILowerControlFlow() : MachineFunctionPass(ID) {}
102 
103   bool runOnMachineFunction(MachineFunction &MF) override;
104 
105   StringRef getPassName() const override {
106     return "SI Lower control flow pseudo instructions";
107   }
108 
109   void getAnalysisUsage(AnalysisUsage &AU) const override {
110     // Should preserve the same set that TwoAddressInstructions does.
111     AU.addPreserved<SlotIndexes>();
112     AU.addPreserved<LiveIntervals>();
113     AU.addPreservedID(LiveVariablesID);
114     AU.addPreservedID(MachineLoopInfoID);
115     AU.addPreservedID(MachineDominatorsID);
116     AU.setPreservesCFG();
117     MachineFunctionPass::getAnalysisUsage(AU);
118   }
119 };
120 
121 } // end anonymous namespace
122 
123 char SILowerControlFlow::ID = 0;
124 
125 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
126                "SI lower control flow", false, false)
127 
128 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
129   MachineOperand &ImpDefSCC = MI.getOperand(3);
130   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
131 
132   ImpDefSCC.setIsDead(IsDead);
133 }
134 
135 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
136 
137 void SILowerControlFlow::emitIf(MachineInstr &MI) {
138   MachineBasicBlock &MBB = *MI.getParent();
139   const DebugLoc &DL = MI.getDebugLoc();
140   MachineBasicBlock::iterator I(&MI);
141 
142   MachineOperand &SaveExec = MI.getOperand(0);
143   MachineOperand &Cond = MI.getOperand(1);
144   assert(SaveExec.getSubReg() == AMDGPU::NoSubRegister &&
145          Cond.getSubReg() == AMDGPU::NoSubRegister);
146 
147   unsigned SaveExecReg = SaveExec.getReg();
148 
149   MachineOperand &ImpDefSCC = MI.getOperand(4);
150   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
151 
152   // If there is only one use of save exec register and that use is SI_END_CF,
153   // we can optimize SI_IF by returning the full saved exec mask instead of
154   // just cleared bits.
155   bool SimpleIf = false;
156   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
157   SimpleIf = U != MRI->use_instr_nodbg_end() &&
158              std::next(U) == MRI->use_instr_nodbg_end() &&
159              U->getOpcode() == AMDGPU::SI_END_CF;
160 
161   // Add an implicit def of exec to discourage scheduling VALU after this which
162   // will interfere with trying to form s_and_saveexec_b64 later.
163   unsigned CopyReg = SimpleIf ? SaveExecReg
164                        : MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
165   MachineInstr *CopyExec =
166     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
167     .addReg(AMDGPU::EXEC)
168     .addReg(AMDGPU::EXEC, RegState::ImplicitDefine);
169 
170   unsigned Tmp = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
171 
172   MachineInstr *And =
173     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_AND_B64), Tmp)
174     .addReg(CopyReg)
175     //.addReg(AMDGPU::EXEC)
176     .addReg(Cond.getReg());
177   setImpSCCDefDead(*And, true);
178 
179   MachineInstr *Xor = nullptr;
180   if (!SimpleIf) {
181     Xor =
182       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_XOR_B64), SaveExecReg)
183       .addReg(Tmp)
184       .addReg(CopyReg);
185     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
186   }
187 
188   // Use a copy that is a terminator to get correct spill code placement it with
189   // fast regalloc.
190   MachineInstr *SetExec =
191     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64_term), AMDGPU::EXEC)
192     .addReg(Tmp, RegState::Kill);
193 
194   // Insert a pseudo terminator to help keep the verifier happy. This will also
195   // be used later when inserting skips.
196   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
197                             .add(MI.getOperand(2));
198 
199   if (!LIS) {
200     MI.eraseFromParent();
201     return;
202   }
203 
204   LIS->InsertMachineInstrInMaps(*CopyExec);
205 
206   // Replace with and so we don't need to fix the live interval for condition
207   // register.
208   LIS->ReplaceMachineInstrInMaps(MI, *And);
209 
210   if (!SimpleIf)
211     LIS->InsertMachineInstrInMaps(*Xor);
212   LIS->InsertMachineInstrInMaps(*SetExec);
213   LIS->InsertMachineInstrInMaps(*NewBr);
214 
215   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI));
216   MI.eraseFromParent();
217 
218   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
219   // hard to add another def here but I'm not sure how to correctly update the
220   // valno.
221   LIS->removeInterval(SaveExecReg);
222   LIS->createAndComputeVirtRegInterval(SaveExecReg);
223   LIS->createAndComputeVirtRegInterval(Tmp);
224   if (!SimpleIf)
225     LIS->createAndComputeVirtRegInterval(CopyReg);
226 }
227 
228 void SILowerControlFlow::emitElse(MachineInstr &MI) {
229   MachineBasicBlock &MBB = *MI.getParent();
230   const DebugLoc &DL = MI.getDebugLoc();
231 
232   unsigned DstReg = MI.getOperand(0).getReg();
233   assert(MI.getOperand(0).getSubReg() == AMDGPU::NoSubRegister);
234 
235   bool ExecModified = MI.getOperand(3).getImm() != 0;
236   MachineBasicBlock::iterator Start = MBB.begin();
237 
238   // We are running before TwoAddressInstructions, and si_else's operands are
239   // tied. In order to correctly tie the registers, split this into a copy of
240   // the src like it does.
241   unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
242   MachineInstr *CopyExec =
243     BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg)
244       .add(MI.getOperand(1)); // Saved EXEC
245 
246   // This must be inserted before phis and any spill code inserted before the
247   // else.
248   unsigned SaveReg = ExecModified ?
249     MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass) : DstReg;
250   MachineInstr *OrSaveExec =
251     BuildMI(MBB, Start, DL, TII->get(AMDGPU::S_OR_SAVEEXEC_B64), SaveReg)
252     .addReg(CopyReg);
253 
254   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
255 
256   MachineBasicBlock::iterator ElsePt(MI);
257 
258   if (ExecModified) {
259     MachineInstr *And =
260       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_AND_B64), DstReg)
261       .addReg(AMDGPU::EXEC)
262       .addReg(SaveReg);
263 
264     if (LIS)
265       LIS->InsertMachineInstrInMaps(*And);
266   }
267 
268   MachineInstr *Xor =
269     BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC)
270     .addReg(AMDGPU::EXEC)
271     .addReg(DstReg);
272 
273   MachineInstr *Branch =
274     BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
275     .addMBB(DestBB);
276 
277   if (!LIS) {
278     MI.eraseFromParent();
279     return;
280   }
281 
282   LIS->RemoveMachineInstrFromMaps(MI);
283   MI.eraseFromParent();
284 
285   LIS->InsertMachineInstrInMaps(*CopyExec);
286   LIS->InsertMachineInstrInMaps(*OrSaveExec);
287 
288   LIS->InsertMachineInstrInMaps(*Xor);
289   LIS->InsertMachineInstrInMaps(*Branch);
290 
291   // src reg is tied to dst reg.
292   LIS->removeInterval(DstReg);
293   LIS->createAndComputeVirtRegInterval(DstReg);
294   LIS->createAndComputeVirtRegInterval(CopyReg);
295   if (ExecModified)
296     LIS->createAndComputeVirtRegInterval(SaveReg);
297 
298   // Let this be recomputed.
299   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI));
300 }
301 
302 void SILowerControlFlow::emitBreak(MachineInstr &MI) {
303   MachineBasicBlock &MBB = *MI.getParent();
304   const DebugLoc &DL = MI.getDebugLoc();
305   unsigned Dst = MI.getOperand(0).getReg();
306 
307   MachineInstr *Or = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
308                          .addReg(AMDGPU::EXEC)
309                          .add(MI.getOperand(1));
310 
311   if (LIS)
312     LIS->ReplaceMachineInstrInMaps(MI, *Or);
313   MI.eraseFromParent();
314 }
315 
316 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
317   MI.setDesc(TII->get(AMDGPU::S_OR_B64));
318 }
319 
320 void SILowerControlFlow::emitElseBreak(MachineInstr &MI) {
321   MI.setDesc(TII->get(AMDGPU::S_OR_B64));
322 }
323 
324 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
325   MachineBasicBlock &MBB = *MI.getParent();
326   const DebugLoc &DL = MI.getDebugLoc();
327 
328   MachineInstr *AndN2 =
329       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64_term), AMDGPU::EXEC)
330           .addReg(AMDGPU::EXEC)
331           .add(MI.getOperand(0));
332 
333   MachineInstr *Branch =
334       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
335           .add(MI.getOperand(1));
336 
337   if (LIS) {
338     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
339     LIS->InsertMachineInstrInMaps(*Branch);
340   }
341 
342   MI.eraseFromParent();
343 }
344 
345 void SILowerControlFlow::emitEndCf(MachineInstr &MI) {
346   MachineBasicBlock &MBB = *MI.getParent();
347   const DebugLoc &DL = MI.getDebugLoc();
348 
349   MachineBasicBlock::iterator InsPt = MBB.begin();
350   MachineInstr *NewMI =
351       BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC)
352           .addReg(AMDGPU::EXEC)
353           .add(MI.getOperand(0));
354 
355   if (LIS)
356     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
357 
358   MI.eraseFromParent();
359 
360   if (LIS)
361     LIS->handleMove(*NewMI);
362 }
363 
364 // Returns replace operands for a logical operation, either single result
365 // for exec or two operands if source was another equivalent operation.
366 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
367        SmallVectorImpl<MachineOperand> &Src) const {
368   MachineOperand &Op = MI.getOperand(OpNo);
369   if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg())) {
370     Src.push_back(Op);
371     return;
372   }
373 
374   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
375   if (!Def || Def->getParent() != MI.getParent() ||
376       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
377     return;
378 
379   // Make sure we do not modify exec between def and use.
380   // A copy with implcitly defined exec inserted earlier is an exclusion, it
381   // does not really modify exec.
382   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
383     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
384         !(I->isCopy() && I->getOperand(0).getReg() != AMDGPU::EXEC))
385       return;
386 
387   for (const auto &SrcOp : Def->explicit_operands())
388     if (SrcOp.isUse() && (!SrcOp.isReg() ||
389         TargetRegisterInfo::isVirtualRegister(SrcOp.getReg()) ||
390         SrcOp.getReg() == AMDGPU::EXEC))
391       Src.push_back(SrcOp);
392 }
393 
394 // Search and combine pairs of equivalent instructions, like
395 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
396 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
397 // One of the operands is exec mask.
398 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
399   assert(MI.getNumExplicitOperands() == 3);
400   SmallVector<MachineOperand, 4> Ops;
401   unsigned OpToReplace = 1;
402   findMaskOperands(MI, 1, Ops);
403   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
404   findMaskOperands(MI, 2, Ops);
405   if (Ops.size() != 3) return;
406 
407   unsigned UniqueOpndIdx;
408   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
409   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
410   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
411   else return;
412 
413   unsigned Reg = MI.getOperand(OpToReplace).getReg();
414   MI.RemoveOperand(OpToReplace);
415   MI.addOperand(Ops[UniqueOpndIdx]);
416   if (MRI->use_empty(Reg))
417     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
418 }
419 
420 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
421   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
422   TII = ST.getInstrInfo();
423   TRI = &TII->getRegisterInfo();
424 
425   // This doesn't actually need LiveIntervals, but we can preserve them.
426   LIS = getAnalysisIfAvailable<LiveIntervals>();
427   MRI = &MF.getRegInfo();
428 
429   MachineFunction::iterator NextBB;
430   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
431        BI != BE; BI = NextBB) {
432     NextBB = std::next(BI);
433     MachineBasicBlock &MBB = *BI;
434 
435     MachineBasicBlock::iterator I, Next, Last;
436 
437     for (I = MBB.begin(), Last = MBB.end(); I != MBB.end(); I = Next) {
438       Next = std::next(I);
439       MachineInstr &MI = *I;
440 
441       switch (MI.getOpcode()) {
442       case AMDGPU::SI_IF:
443         emitIf(MI);
444         break;
445 
446       case AMDGPU::SI_ELSE:
447         emitElse(MI);
448         break;
449 
450       case AMDGPU::SI_BREAK:
451         emitBreak(MI);
452         break;
453 
454       case AMDGPU::SI_IF_BREAK:
455         emitIfBreak(MI);
456         break;
457 
458       case AMDGPU::SI_ELSE_BREAK:
459         emitElseBreak(MI);
460         break;
461 
462       case AMDGPU::SI_LOOP:
463         emitLoop(MI);
464         break;
465 
466       case AMDGPU::SI_END_CF:
467         emitEndCf(MI);
468         break;
469 
470       case AMDGPU::S_AND_B64:
471       case AMDGPU::S_OR_B64:
472         // Cleanup bit manipulations on exec mask
473         combineMasks(MI);
474         Last = I;
475         continue;
476 
477       default:
478         Last = I;
479         continue;
480       }
481 
482       // Replay newly inserted code to combine masks
483       Next = (Last == MBB.end()) ? MBB.begin() : Last;
484     }
485   }
486 
487   return true;
488 }
489