xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 46cb48c74ae4220bbb56b88ca2432a98ce8fe9c8)
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 "SIMachineFunctionInfo.h"
55 #include "llvm/CodeGen/LivePhysRegs.h"
56 #include "llvm/CodeGen/MachineFrameInfo.h"
57 #include "llvm/CodeGen/MachineFunction.h"
58 #include "llvm/CodeGen/MachineFunctionPass.h"
59 #include "llvm/CodeGen/MachineInstrBuilder.h"
60 #include "llvm/CodeGen/MachineRegisterInfo.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/MC/MCAsmInfo.h"
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "si-lower-control-flow"
67 
68 namespace {
69 
70 static cl::opt<unsigned> SkipThresholdFlag(
71   "amdgpu-skip-threshold",
72   cl::desc("Number of instructions before jumping over divergent control flow"),
73   cl::init(12), cl::Hidden);
74 
75 class SILowerControlFlow : public MachineFunctionPass {
76 private:
77   const SIRegisterInfo *TRI;
78   const SIInstrInfo *TII;
79   unsigned SkipThreshold;
80 
81   bool shouldSkip(MachineBasicBlock *From, MachineBasicBlock *To);
82 
83   void Skip(MachineInstr &From, MachineOperand &To);
84   bool skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB);
85 
86   void If(MachineInstr &MI);
87   void Else(MachineInstr &MI, bool ExecModified);
88   void Break(MachineInstr &MI);
89   void IfBreak(MachineInstr &MI);
90   void ElseBreak(MachineInstr &MI);
91   void Loop(MachineInstr &MI);
92   void EndCf(MachineInstr &MI);
93 
94   void Kill(MachineInstr &MI);
95   void Branch(MachineInstr &MI);
96 
97   MachineBasicBlock *insertSkipBlock(MachineBasicBlock &MBB,
98                                      MachineBasicBlock::iterator I) const;
99 public:
100   static char ID;
101 
102   SILowerControlFlow() :
103     MachineFunctionPass(ID), TRI(nullptr), TII(nullptr), SkipThreshold(0) { }
104 
105   bool runOnMachineFunction(MachineFunction &MF) override;
106 
107   const char *getPassName() const override {
108     return "SI Lower control flow pseudo instructions";
109   }
110 };
111 
112 } // End anonymous namespace
113 
114 char SILowerControlFlow::ID = 0;
115 
116 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
117                 "SI lower control flow", false, false)
118 
119 char &llvm::SILowerControlFlowPassID = SILowerControlFlow::ID;
120 
121 
122 FunctionPass *llvm::createSILowerControlFlowPass() {
123   return new SILowerControlFlow();
124 }
125 
126 static bool opcodeEmitsNoInsts(unsigned Opc) {
127   switch (Opc) {
128   case TargetOpcode::IMPLICIT_DEF:
129   case TargetOpcode::KILL:
130   case TargetOpcode::BUNDLE:
131   case TargetOpcode::CFI_INSTRUCTION:
132   case TargetOpcode::EH_LABEL:
133   case TargetOpcode::GC_LABEL:
134   case TargetOpcode::DBG_VALUE:
135     return true;
136   default:
137     return false;
138   }
139 }
140 
141 bool SILowerControlFlow::shouldSkip(MachineBasicBlock *From,
142                                     MachineBasicBlock *To) {
143   if (From->succ_empty())
144     return false;
145 
146   unsigned NumInstr = 0;
147   MachineFunction *MF = From->getParent();
148 
149   for (MachineFunction::iterator MBBI(From), ToI(To), End = MF->end();
150        MBBI != End && MBBI != ToI; ++MBBI) {
151     MachineBasicBlock &MBB = *MBBI;
152 
153     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
154          NumInstr < SkipThreshold && I != E; ++I) {
155       if (opcodeEmitsNoInsts(I->getOpcode()))
156         continue;
157 
158       // When a uniform loop is inside non-uniform control flow, the branch
159       // leaving the loop might be an S_CBRANCH_VCCNZ, which is never taken
160       // when EXEC = 0. We should skip the loop lest it becomes infinite.
161       if (I->getOpcode() == AMDGPU::S_CBRANCH_VCCNZ ||
162           I->getOpcode() == AMDGPU::S_CBRANCH_VCCZ)
163         return true;
164 
165       if (I->isInlineAsm()) {
166         const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
167         const char *AsmStr = I->getOperand(0).getSymbolName();
168 
169         // inlineasm length estimate is number of bytes assuming the longest
170         // instruction.
171         uint64_t MaxAsmSize = TII->getInlineAsmLength(AsmStr, *MAI);
172         NumInstr += MaxAsmSize / MAI->getMaxInstLength();
173       } else {
174         ++NumInstr;
175       }
176 
177       if (NumInstr >= SkipThreshold)
178         return true;
179     }
180   }
181 
182   return false;
183 }
184 
185 void SILowerControlFlow::Skip(MachineInstr &From, MachineOperand &To) {
186 
187   if (!shouldSkip(*From.getParent()->succ_begin(), To.getMBB()))
188     return;
189 
190   DebugLoc DL = From.getDebugLoc();
191   BuildMI(*From.getParent(), &From, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
192     .addOperand(To);
193 }
194 
195 bool SILowerControlFlow::skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB) {
196   MachineBasicBlock &MBB = *MI.getParent();
197   MachineFunction *MF = MBB.getParent();
198 
199   if (MF->getFunction()->getCallingConv() != CallingConv::AMDGPU_PS ||
200       !shouldSkip(&MBB, &MBB.getParent()->back()))
201     return false;
202 
203   MachineBasicBlock *SkipBB = insertSkipBlock(MBB, MI.getIterator());
204   MBB.addSuccessor(SkipBB);
205 
206   const DebugLoc &DL = MI.getDebugLoc();
207 
208   // If the exec mask is non-zero, skip the next two instructions
209   BuildMI(&MBB, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
210     .addMBB(&NextBB);
211 
212   MachineBasicBlock::iterator Insert = SkipBB->begin();
213 
214   // Exec mask is zero: Export to NULL target...
215   BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::EXP))
216     .addImm(0)
217     .addImm(0x09) // V_008DFC_SQ_EXP_NULL
218     .addImm(0)
219     .addImm(1)
220     .addImm(1)
221     .addReg(AMDGPU::VGPR0, RegState::Undef)
222     .addReg(AMDGPU::VGPR0, RegState::Undef)
223     .addReg(AMDGPU::VGPR0, RegState::Undef)
224     .addReg(AMDGPU::VGPR0, RegState::Undef);
225 
226   // ... and terminate wavefront.
227   BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::S_ENDPGM));
228 
229   return true;
230 }
231 
232 void SILowerControlFlow::If(MachineInstr &MI) {
233   MachineBasicBlock &MBB = *MI.getParent();
234   DebugLoc DL = MI.getDebugLoc();
235   unsigned Reg = MI.getOperand(0).getReg();
236   unsigned Vcc = MI.getOperand(1).getReg();
237 
238   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), Reg)
239           .addReg(Vcc);
240 
241   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_XOR_B64), Reg)
242           .addReg(AMDGPU::EXEC)
243           .addReg(Reg);
244 
245   Skip(MI, MI.getOperand(2));
246 
247   // Insert a pseudo terminator to help keep the verifier happy.
248   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
249     .addOperand(MI.getOperand(2))
250     .addReg(Reg);
251 
252   MI.eraseFromParent();
253 }
254 
255 void SILowerControlFlow::Else(MachineInstr &MI, bool ExecModified) {
256   MachineBasicBlock &MBB = *MI.getParent();
257   DebugLoc DL = MI.getDebugLoc();
258   unsigned Dst = MI.getOperand(0).getReg();
259   unsigned Src = MI.getOperand(1).getReg();
260 
261   BuildMI(MBB, MBB.getFirstNonPHI(), DL,
262           TII->get(AMDGPU::S_OR_SAVEEXEC_B64), Dst)
263           .addReg(Src); // Saved EXEC
264 
265   if (ExecModified) {
266     // Adjust the saved exec to account for the modifications during the flow
267     // block that contains the ELSE. This can happen when WQM mode is switched
268     // off.
269     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_AND_B64), Dst)
270             .addReg(AMDGPU::EXEC)
271             .addReg(Dst);
272   }
273 
274   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
275           .addReg(AMDGPU::EXEC)
276           .addReg(Dst);
277 
278   Skip(MI, MI.getOperand(2));
279 
280   // Insert a pseudo terminator to help keep the verifier happy.
281   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
282     .addOperand(MI.getOperand(2))
283     .addReg(Dst);
284 
285   MI.eraseFromParent();
286 }
287 
288 void SILowerControlFlow::Break(MachineInstr &MI) {
289   MachineBasicBlock &MBB = *MI.getParent();
290   DebugLoc DL = MI.getDebugLoc();
291 
292   unsigned Dst = MI.getOperand(0).getReg();
293   unsigned Src = MI.getOperand(1).getReg();
294 
295   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
296           .addReg(AMDGPU::EXEC)
297           .addReg(Src);
298 
299   MI.eraseFromParent();
300 }
301 
302 void SILowerControlFlow::IfBreak(MachineInstr &MI) {
303   MachineBasicBlock &MBB = *MI.getParent();
304   DebugLoc DL = MI.getDebugLoc();
305 
306   unsigned Dst = MI.getOperand(0).getReg();
307   unsigned Vcc = MI.getOperand(1).getReg();
308   unsigned Src = MI.getOperand(2).getReg();
309 
310   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
311           .addReg(Vcc)
312           .addReg(Src);
313 
314   MI.eraseFromParent();
315 }
316 
317 void SILowerControlFlow::ElseBreak(MachineInstr &MI) {
318   MachineBasicBlock &MBB = *MI.getParent();
319   DebugLoc DL = MI.getDebugLoc();
320 
321   unsigned Dst = MI.getOperand(0).getReg();
322   unsigned Saved = MI.getOperand(1).getReg();
323   unsigned Src = MI.getOperand(2).getReg();
324 
325   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
326           .addReg(Saved)
327           .addReg(Src);
328 
329   MI.eraseFromParent();
330 }
331 
332 void SILowerControlFlow::Loop(MachineInstr &MI) {
333   MachineBasicBlock &MBB = *MI.getParent();
334   DebugLoc DL = MI.getDebugLoc();
335   unsigned Src = MI.getOperand(0).getReg();
336 
337   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64), AMDGPU::EXEC)
338           .addReg(AMDGPU::EXEC)
339           .addReg(Src);
340 
341   BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
342     .addOperand(MI.getOperand(1));
343 
344   MI.eraseFromParent();
345 }
346 
347 void SILowerControlFlow::EndCf(MachineInstr &MI) {
348   MachineBasicBlock &MBB = *MI.getParent();
349   DebugLoc DL = MI.getDebugLoc();
350   unsigned Reg = MI.getOperand(0).getReg();
351 
352   BuildMI(MBB, MBB.getFirstNonPHI(), DL,
353           TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC)
354           .addReg(AMDGPU::EXEC)
355           .addReg(Reg);
356 
357   MI.eraseFromParent();
358 }
359 
360 void SILowerControlFlow::Branch(MachineInstr &MI) {
361   MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
362   if (MBB == MI.getParent()->getNextNode())
363     MI.eraseFromParent();
364 
365   // If these aren't equal, this is probably an infinite loop.
366 }
367 
368 void SILowerControlFlow::Kill(MachineInstr &MI) {
369   MachineBasicBlock &MBB = *MI.getParent();
370   DebugLoc DL = MI.getDebugLoc();
371   const MachineOperand &Op = MI.getOperand(0);
372 
373 #ifndef NDEBUG
374   CallingConv::ID CallConv = MBB.getParent()->getFunction()->getCallingConv();
375   // Kill is only allowed in pixel / geometry shaders.
376   assert(CallConv == CallingConv::AMDGPU_PS ||
377          CallConv == CallingConv::AMDGPU_GS);
378 #endif
379 
380   // Clear this thread from the exec mask if the operand is negative
381   if ((Op.isImm())) {
382     // Constant operand: Set exec mask to 0 or do nothing
383     if (Op.getImm() & 0x80000000) {
384       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
385               .addImm(0);
386     }
387   } else {
388     BuildMI(MBB, &MI, DL, TII->get(AMDGPU::V_CMPX_LE_F32_e32))
389            .addImm(0)
390            .addOperand(Op);
391   }
392 
393   MI.eraseFromParent();
394 }
395 
396 MachineBasicBlock *SILowerControlFlow::insertSkipBlock(
397   MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
398   MachineFunction *MF = MBB.getParent();
399 
400   MachineBasicBlock *SkipBB = MF->CreateMachineBasicBlock();
401   MachineFunction::iterator MBBI(MBB);
402   ++MBBI;
403 
404   MF->insert(MBBI, SkipBB);
405 
406   return SkipBB;
407 }
408 
409 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
410   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
411   TII = ST.getInstrInfo();
412   TRI = &TII->getRegisterInfo();
413   SkipThreshold = SkipThresholdFlag;
414 
415   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
416 
417   bool HaveKill = false;
418   bool NeedFlat = false;
419   unsigned Depth = 0;
420 
421   MachineFunction::iterator NextBB;
422 
423   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
424        BI != BE; BI = NextBB) {
425     NextBB = std::next(BI);
426     MachineBasicBlock &MBB = *BI;
427 
428     MachineBasicBlock *EmptyMBBAtEnd = nullptr;
429     MachineBasicBlock::iterator I, Next;
430     bool ExecModified = false;
431 
432     for (I = MBB.begin(); I != MBB.end(); I = Next) {
433       Next = std::next(I);
434 
435       MachineInstr &MI = *I;
436 
437       // Flat uses m0 in case it needs to access LDS.
438       if (TII->isFLAT(MI))
439         NeedFlat = true;
440 
441       if (I->modifiesRegister(AMDGPU::EXEC, TRI))
442         ExecModified = true;
443 
444       switch (MI.getOpcode()) {
445         default: break;
446         case AMDGPU::SI_IF:
447           ++Depth;
448           If(MI);
449           break;
450 
451         case AMDGPU::SI_ELSE:
452           Else(MI, ExecModified);
453           break;
454 
455         case AMDGPU::SI_BREAK:
456           Break(MI);
457           break;
458 
459         case AMDGPU::SI_IF_BREAK:
460           IfBreak(MI);
461           break;
462 
463         case AMDGPU::SI_ELSE_BREAK:
464           ElseBreak(MI);
465           break;
466 
467         case AMDGPU::SI_LOOP:
468           ++Depth;
469           Loop(MI);
470           break;
471 
472         case AMDGPU::SI_END_CF:
473           if (--Depth == 0 && HaveKill) {
474             HaveKill = false;
475             // TODO: Insert skip if exec is 0?
476           }
477 
478           EndCf(MI);
479           break;
480 
481         case AMDGPU::SI_KILL_TERMINATOR:
482           if (Depth == 0) {
483             if (skipIfDead(MI, *NextBB)) {
484               NextBB = std::next(BI);
485               BE = MF.end();
486             }
487           } else
488             HaveKill = true;
489           Kill(MI);
490           break;
491 
492         case AMDGPU::S_BRANCH:
493           Branch(MI);
494           break;
495 
496         case AMDGPU::SI_RETURN: {
497           assert(!MF.getInfo<SIMachineFunctionInfo>()->returnsVoid());
498 
499           // Graphics shaders returning non-void shouldn't contain S_ENDPGM,
500           // because external bytecode will be appended at the end.
501           if (BI != --MF.end() || I != MBB.getFirstTerminator()) {
502             // SI_RETURN is not the last instruction. Add an empty block at
503             // the end and jump there.
504             if (!EmptyMBBAtEnd) {
505               EmptyMBBAtEnd = MF.CreateMachineBasicBlock();
506               MF.insert(MF.end(), EmptyMBBAtEnd);
507             }
508 
509             MBB.addSuccessor(EmptyMBBAtEnd);
510             BuildMI(*BI, I, MI.getDebugLoc(), TII->get(AMDGPU::S_BRANCH))
511                     .addMBB(EmptyMBBAtEnd);
512             I->eraseFromParent();
513           }
514           break;
515         }
516       }
517     }
518   }
519 
520   if (NeedFlat && MFI->isKernel()) {
521     // TODO: What to use with function calls?
522     // We will need to Initialize the flat scratch register pair.
523     if (NeedFlat)
524       MFI->setHasFlatInstructions(true);
525   }
526 
527   return true;
528 }
529