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 
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "si-lower-control-flow"
65 
66 namespace {
67 
68 class SILowerControlFlow : public MachineFunctionPass {
69 private:
70   const SIRegisterInfo *TRI;
71   const SIInstrInfo *TII;
72   LiveIntervals *LIS;
73   MachineRegisterInfo *MRI;
74 
75   void emitIf(MachineInstr &MI);
76   void emitElse(MachineInstr &MI);
77   void emitBreak(MachineInstr &MI);
78   void emitIfBreak(MachineInstr &MI);
79   void emitElseBreak(MachineInstr &MI);
80   void emitLoop(MachineInstr &MI);
81   void emitEndCf(MachineInstr &MI);
82 
83   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
84                         SmallVectorImpl<MachineOperand> &Src) const;
85 
86   void combineMasks(MachineInstr &MI);
87 
88 public:
89   static char ID;
90 
91   SILowerControlFlow() :
92     MachineFunctionPass(ID),
93     TRI(nullptr),
94     TII(nullptr),
95     LIS(nullptr),
96     MRI(nullptr) {}
97 
98   bool runOnMachineFunction(MachineFunction &MF) override;
99 
100   StringRef getPassName() const override {
101     return "SI Lower control flow pseudo instructions";
102   }
103 
104   void getAnalysisUsage(AnalysisUsage &AU) const override {
105     // Should preserve the same set that TwoAddressInstructions does.
106     AU.addPreserved<SlotIndexes>();
107     AU.addPreserved<LiveIntervals>();
108     AU.addPreservedID(LiveVariablesID);
109     AU.addPreservedID(MachineLoopInfoID);
110     AU.addPreservedID(MachineDominatorsID);
111     AU.setPreservesCFG();
112     MachineFunctionPass::getAnalysisUsage(AU);
113   }
114 };
115 
116 } // End anonymous namespace
117 
118 char SILowerControlFlow::ID = 0;
119 
120 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
121                "SI lower control flow", false, false)
122 
123 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
124   MachineOperand &ImpDefSCC = MI.getOperand(3);
125   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
126 
127   ImpDefSCC.setIsDead(IsDead);
128 }
129 
130 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
131 
132 void SILowerControlFlow::emitIf(MachineInstr &MI) {
133   MachineBasicBlock &MBB = *MI.getParent();
134   const DebugLoc &DL = MI.getDebugLoc();
135   MachineBasicBlock::iterator I(&MI);
136 
137   MachineOperand &SaveExec = MI.getOperand(0);
138   MachineOperand &Cond = MI.getOperand(1);
139   assert(SaveExec.getSubReg() == AMDGPU::NoSubRegister &&
140          Cond.getSubReg() == AMDGPU::NoSubRegister);
141 
142   unsigned SaveExecReg = SaveExec.getReg();
143 
144   MachineOperand &ImpDefSCC = MI.getOperand(4);
145   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
146 
147   // Add an implicit def of exec to discourage scheduling VALU after this which
148   // will interfere with trying to form s_and_saveexec_b64 later.
149   unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
150   MachineInstr *CopyExec =
151     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
152     .addReg(AMDGPU::EXEC)
153     .addReg(AMDGPU::EXEC, RegState::ImplicitDefine);
154 
155   unsigned Tmp = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
156 
157   MachineInstr *And =
158     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_AND_B64), Tmp)
159     .addReg(CopyReg)
160     //.addReg(AMDGPU::EXEC)
161     .addReg(Cond.getReg());
162   setImpSCCDefDead(*And, true);
163 
164   MachineInstr *Xor =
165     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_XOR_B64), SaveExecReg)
166     .addReg(Tmp)
167     .addReg(CopyReg);
168   setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
169 
170   // Use a copy that is a terminator to get correct spill code placement it with
171   // fast regalloc.
172   MachineInstr *SetExec =
173     BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64_term), AMDGPU::EXEC)
174     .addReg(Tmp, RegState::Kill);
175 
176   // Insert a pseudo terminator to help keep the verifier happy. This will also
177   // be used later when inserting skips.
178   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
179                             .add(MI.getOperand(2));
180 
181   if (!LIS) {
182     MI.eraseFromParent();
183     return;
184   }
185 
186   LIS->InsertMachineInstrInMaps(*CopyExec);
187 
188   // Replace with and so we don't need to fix the live interval for condition
189   // register.
190   LIS->ReplaceMachineInstrInMaps(MI, *And);
191 
192   LIS->InsertMachineInstrInMaps(*Xor);
193   LIS->InsertMachineInstrInMaps(*SetExec);
194   LIS->InsertMachineInstrInMaps(*NewBr);
195 
196   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI));
197   MI.eraseFromParent();
198 
199   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
200   // hard to add another def here but I'm not sure how to correctly update the
201   // valno.
202   LIS->removeInterval(SaveExecReg);
203   LIS->createAndComputeVirtRegInterval(SaveExecReg);
204   LIS->createAndComputeVirtRegInterval(Tmp);
205   LIS->createAndComputeVirtRegInterval(CopyReg);
206 }
207 
208 void SILowerControlFlow::emitElse(MachineInstr &MI) {
209   MachineBasicBlock &MBB = *MI.getParent();
210   const DebugLoc &DL = MI.getDebugLoc();
211 
212   unsigned DstReg = MI.getOperand(0).getReg();
213   assert(MI.getOperand(0).getSubReg() == AMDGPU::NoSubRegister);
214 
215   bool ExecModified = MI.getOperand(3).getImm() != 0;
216   MachineBasicBlock::iterator Start = MBB.begin();
217 
218   // We are running before TwoAddressInstructions, and si_else's operands are
219   // tied. In order to correctly tie the registers, split this into a copy of
220   // the src like it does.
221   unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
222   BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg)
223       .add(MI.getOperand(1)); // Saved EXEC
224 
225   // This must be inserted before phis and any spill code inserted before the
226   // else.
227   unsigned SaveReg = ExecModified ?
228     MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass) : DstReg;
229   MachineInstr *OrSaveExec =
230     BuildMI(MBB, Start, DL, TII->get(AMDGPU::S_OR_SAVEEXEC_B64), SaveReg)
231     .addReg(CopyReg);
232 
233   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
234 
235   MachineBasicBlock::iterator ElsePt(MI);
236 
237   if (ExecModified) {
238     MachineInstr *And =
239       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_AND_B64), DstReg)
240       .addReg(AMDGPU::EXEC)
241       .addReg(SaveReg);
242 
243     if (LIS)
244       LIS->InsertMachineInstrInMaps(*And);
245   }
246 
247   MachineInstr *Xor =
248     BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC)
249     .addReg(AMDGPU::EXEC)
250     .addReg(DstReg);
251 
252   MachineInstr *Branch =
253     BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::SI_MASK_BRANCH))
254     .addMBB(DestBB);
255 
256   if (!LIS) {
257     MI.eraseFromParent();
258     return;
259   }
260 
261   LIS->RemoveMachineInstrFromMaps(MI);
262   MI.eraseFromParent();
263 
264   LIS->InsertMachineInstrInMaps(*OrSaveExec);
265 
266   LIS->InsertMachineInstrInMaps(*Xor);
267   LIS->InsertMachineInstrInMaps(*Branch);
268 
269   // src reg is tied to dst reg.
270   LIS->removeInterval(DstReg);
271   LIS->createAndComputeVirtRegInterval(DstReg);
272   LIS->createAndComputeVirtRegInterval(CopyReg);
273   if (ExecModified)
274     LIS->createAndComputeVirtRegInterval(SaveReg);
275 
276   // Let this be recomputed.
277   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI));
278 }
279 
280 void SILowerControlFlow::emitBreak(MachineInstr &MI) {
281   MachineBasicBlock &MBB = *MI.getParent();
282   const DebugLoc &DL = MI.getDebugLoc();
283   unsigned Dst = MI.getOperand(0).getReg();
284 
285   MachineInstr *Or = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst)
286                          .addReg(AMDGPU::EXEC)
287                          .add(MI.getOperand(1));
288 
289   if (LIS)
290     LIS->ReplaceMachineInstrInMaps(MI, *Or);
291   MI.eraseFromParent();
292 }
293 
294 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
295   MI.setDesc(TII->get(AMDGPU::S_OR_B64));
296 }
297 
298 void SILowerControlFlow::emitElseBreak(MachineInstr &MI) {
299   MI.setDesc(TII->get(AMDGPU::S_OR_B64));
300 }
301 
302 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
303   MachineBasicBlock &MBB = *MI.getParent();
304   const DebugLoc &DL = MI.getDebugLoc();
305 
306   MachineInstr *AndN2 =
307       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64_term), AMDGPU::EXEC)
308           .addReg(AMDGPU::EXEC)
309           .add(MI.getOperand(0));
310 
311   MachineInstr *Branch =
312       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
313           .add(MI.getOperand(1));
314 
315   if (LIS) {
316     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
317     LIS->InsertMachineInstrInMaps(*Branch);
318   }
319 
320   MI.eraseFromParent();
321 }
322 
323 void SILowerControlFlow::emitEndCf(MachineInstr &MI) {
324   MachineBasicBlock &MBB = *MI.getParent();
325   const DebugLoc &DL = MI.getDebugLoc();
326 
327   MachineBasicBlock::iterator InsPt = MBB.begin();
328   MachineInstr *NewMI =
329       BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC)
330           .addReg(AMDGPU::EXEC)
331           .add(MI.getOperand(0));
332 
333   if (LIS)
334     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
335 
336   MI.eraseFromParent();
337 
338   if (LIS)
339     LIS->handleMove(*NewMI);
340 }
341 
342 // Returns replace operands for a logical operation, either single result
343 // for exec or two operands if source was another equivalent operation.
344 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
345        SmallVectorImpl<MachineOperand> &Src) const {
346   MachineOperand &Op = MI.getOperand(OpNo);
347   if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg())) {
348     Src.push_back(Op);
349     return;
350   }
351 
352   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
353   if (!Def || Def->getParent() != MI.getParent() ||
354       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
355     return;
356 
357   // Make sure we do not modify exec between def and use.
358   // A copy with implcitly defined exec inserted earlier is an exclusion, it
359   // does not really modify exec.
360   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
361     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
362         !(I->isCopy() && I->getOperand(0).getReg() != AMDGPU::EXEC))
363       return;
364 
365   for (const auto &SrcOp : Def->explicit_operands())
366     if (SrcOp.isUse() && (!SrcOp.isReg() ||
367         TargetRegisterInfo::isVirtualRegister(SrcOp.getReg()) ||
368         SrcOp.getReg() == AMDGPU::EXEC))
369       Src.push_back(SrcOp);
370 }
371 
372 // Search and combine pairs of equivalent instructions, like
373 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
374 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
375 // One of the operands is exec mask.
376 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
377   assert(MI.getNumExplicitOperands() == 3);
378   SmallVector<MachineOperand, 4> Ops;
379   unsigned OpToReplace = 1;
380   findMaskOperands(MI, 1, Ops);
381   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
382   findMaskOperands(MI, 2, Ops);
383   if (Ops.size() != 3) return;
384 
385   unsigned UniqueOpndIdx;
386   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
387   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
388   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
389   else return;
390 
391   unsigned Reg = MI.getOperand(OpToReplace).getReg();
392   MI.RemoveOperand(OpToReplace);
393   MI.addOperand(Ops[UniqueOpndIdx]);
394   if (MRI->use_empty(Reg))
395     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
396 }
397 
398 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
399   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
400   TII = ST.getInstrInfo();
401   TRI = &TII->getRegisterInfo();
402 
403   // This doesn't actually need LiveIntervals, but we can preserve them.
404   LIS = getAnalysisIfAvailable<LiveIntervals>();
405   MRI = &MF.getRegInfo();
406 
407   MachineFunction::iterator NextBB;
408   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
409        BI != BE; BI = NextBB) {
410     NextBB = std::next(BI);
411     MachineBasicBlock &MBB = *BI;
412 
413     MachineBasicBlock::iterator I, Next, Last;
414 
415     for (I = MBB.begin(), Last = MBB.end(); I != MBB.end(); I = Next) {
416       Next = std::next(I);
417       MachineInstr &MI = *I;
418 
419       switch (MI.getOpcode()) {
420       case AMDGPU::SI_IF:
421         emitIf(MI);
422         break;
423 
424       case AMDGPU::SI_ELSE:
425         emitElse(MI);
426         break;
427 
428       case AMDGPU::SI_BREAK:
429         emitBreak(MI);
430         break;
431 
432       case AMDGPU::SI_IF_BREAK:
433         emitIfBreak(MI);
434         break;
435 
436       case AMDGPU::SI_ELSE_BREAK:
437         emitElseBreak(MI);
438         break;
439 
440       case AMDGPU::SI_LOOP:
441         emitLoop(MI);
442         break;
443 
444       case AMDGPU::SI_END_CF:
445         emitEndCf(MI);
446         break;
447 
448       case AMDGPU::S_AND_B64:
449       case AMDGPU::S_OR_B64:
450         // Cleanup bit manipulations on exec mask
451         combineMasks(MI);
452         Last = I;
453         continue;
454 
455       default:
456         Last = I;
457         continue;
458       }
459 
460       // Replay newly inserted code to combine masks
461       Next = (Last == MBB.end()) ? MBB.begin() : Last;
462     }
463   }
464 
465   return true;
466 }
467