xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 36deb9a670d06fc254df2f357ae595fb8f817d07)
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
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 //
9 /// \file
10 /// This pass lowers the pseudo control flow instructions to real
11 /// machine instructions.
12 ///
13 /// All control flow is handled using predicated instructions and
14 /// a predicate stack.  Each Scalar ALU controls the operations of 64 Vector
15 /// ALUs.  The Scalar ALU can update the predicate for any of the Vector ALUs
16 /// by writting to the 64-bit EXEC register (each bit corresponds to a
17 /// single vector ALU).  Typically, for predicates, a vector ALU will write
18 /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
19 /// Vector ALU) and then the ScalarALU will AND the VCC register with the
20 /// EXEC to update the predicates.
21 ///
22 /// For example:
23 /// %vcc = V_CMP_GT_F32 %vgpr1, %vgpr2
24 /// %sgpr0 = SI_IF %vcc
25 ///   %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0
26 /// %sgpr0 = SI_ELSE %sgpr0
27 ///   %vgpr0 = V_SUB_F32 %vgpr0, %vgpr0
28 /// SI_END_CF %sgpr0
29 ///
30 /// becomes:
31 ///
32 /// %sgpr0 = S_AND_SAVEEXEC_B64 %vcc  // Save and update the exec mask
33 /// %sgpr0 = S_XOR_B64 %sgpr0, %exec  // Clear live bits from saved exec mask
34 /// S_CBRANCH_EXECZ label0            // This instruction is an optional
35 ///                                   // optimization which allows us to
36 ///                                   // branch if all the bits of
37 ///                                   // EXEC are zero.
38 /// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0 // Do the IF block of the branch
39 ///
40 /// label0:
41 /// %sgpr0 = S_OR_SAVEEXEC_B64 %sgpr0  // Restore the exec mask for the Then block
42 /// %exec = S_XOR_B64 %sgpr0, %exec    // Update the exec mask
43 /// S_BRANCH_EXECZ label1              // Use our branch optimization
44 ///                                    // instruction again.
45 /// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr   // Do the THEN block
46 /// label1:
47 /// %exec = S_OR_B64 %exec, %sgpr0     // Re-enable saved exec mask bits
48 //===----------------------------------------------------------------------===//
49 
50 #include "AMDGPU.h"
51 #include "GCNSubtarget.h"
52 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
53 #include "llvm/ADT/SmallSet.h"
54 #include "llvm/CodeGen/LiveIntervals.h"
55 #include "llvm/CodeGen/MachineDominators.h"
56 #include "llvm/CodeGen/MachineFunctionPass.h"
57 
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "si-lower-control-flow"
61 
62 static cl::opt<bool>
63 RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
64     cl::init(true), cl::ReallyHidden);
65 
66 namespace {
67 
68 class SILowerControlFlow : public MachineFunctionPass {
69 private:
70   const SIRegisterInfo *TRI = nullptr;
71   const SIInstrInfo *TII = nullptr;
72   LiveIntervals *LIS = nullptr;
73   MachineDominatorTree *MDT = nullptr;
74   MachineRegisterInfo *MRI = nullptr;
75   SetVector<MachineInstr*> LoweredEndCf;
76   DenseSet<Register> LoweredIf;
77   SmallSet<MachineBasicBlock *, 4> KillBlocks;
78 
79   const TargetRegisterClass *BoolRC = nullptr;
80   unsigned AndOpc;
81   unsigned OrOpc;
82   unsigned XorOpc;
83   unsigned MovTermOpc;
84   unsigned Andn2TermOpc;
85   unsigned XorTermrOpc;
86   unsigned OrTermrOpc;
87   unsigned OrSaveExecOpc;
88   unsigned Exec;
89 
90   bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
91 
92   void emitIf(MachineInstr &MI);
93   void emitElse(MachineInstr &MI);
94   void emitIfBreak(MachineInstr &MI);
95   void emitLoop(MachineInstr &MI);
96 
97   MachineBasicBlock *emitEndCf(MachineInstr &MI);
98 
99   void lowerInitExec(MachineBasicBlock *MBB, MachineInstr &MI);
100 
101   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
102                         SmallVectorImpl<MachineOperand> &Src) const;
103 
104   void combineMasks(MachineInstr &MI);
105 
106   bool removeMBBifRedundant(MachineBasicBlock &MBB);
107 
108   MachineBasicBlock *process(MachineInstr &MI);
109 
110   // Skip to the next instruction, ignoring debug instructions, and trivial
111   // block boundaries (blocks that have one (typically fallthrough) successor,
112   // and the successor has one predecessor.
113   MachineBasicBlock::iterator
114   skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
115                                  MachineBasicBlock::iterator It) const;
116 
117   /// Find the insertion point for a new conditional branch.
118   MachineBasicBlock::iterator
119   skipToUncondBrOrEnd(MachineBasicBlock &MBB,
120                       MachineBasicBlock::iterator I) const {
121     assert(I->isTerminator());
122 
123     // FIXME: What if we had multiple pre-existing conditional branches?
124     MachineBasicBlock::iterator End = MBB.end();
125     while (I != End && !I->isUnconditionalBranch())
126       ++I;
127     return I;
128   }
129 
130   // Remove redundant SI_END_CF instructions.
131   void optimizeEndCf();
132 
133 public:
134   static char ID;
135 
136   SILowerControlFlow() : MachineFunctionPass(ID) {}
137 
138   bool runOnMachineFunction(MachineFunction &MF) override;
139 
140   StringRef getPassName() const override {
141     return "SI Lower control flow pseudo instructions";
142   }
143 
144   void getAnalysisUsage(AnalysisUsage &AU) const override {
145     // Should preserve the same set that TwoAddressInstructions does.
146     AU.addPreserved<MachineDominatorTree>();
147     AU.addPreserved<SlotIndexes>();
148     AU.addPreserved<LiveIntervals>();
149     AU.addPreservedID(LiveVariablesID);
150     MachineFunctionPass::getAnalysisUsage(AU);
151   }
152 };
153 
154 } // end anonymous namespace
155 
156 char SILowerControlFlow::ID = 0;
157 
158 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
159                "SI lower control flow", false, false)
160 
161 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
162   MachineOperand &ImpDefSCC = MI.getOperand(3);
163   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
164 
165   ImpDefSCC.setIsDead(IsDead);
166 }
167 
168 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
169 
170 bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
171                                  const MachineBasicBlock *End) {
172   DenseSet<const MachineBasicBlock*> Visited;
173   SmallVector<MachineBasicBlock *, 4> Worklist(Begin->successors());
174 
175   while (!Worklist.empty()) {
176     MachineBasicBlock *MBB = Worklist.pop_back_val();
177 
178     if (MBB == End || !Visited.insert(MBB).second)
179       continue;
180     if (KillBlocks.contains(MBB))
181       return true;
182 
183     Worklist.append(MBB->succ_begin(), MBB->succ_end());
184   }
185 
186   return false;
187 }
188 
189 static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
190   Register SaveExecReg = MI.getOperand(0).getReg();
191   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
192 
193   if (U == MRI->use_instr_nodbg_end() ||
194       std::next(U) != MRI->use_instr_nodbg_end() ||
195       U->getOpcode() != AMDGPU::SI_END_CF)
196     return false;
197 
198   return true;
199 }
200 
201 void SILowerControlFlow::emitIf(MachineInstr &MI) {
202   MachineBasicBlock &MBB = *MI.getParent();
203   const DebugLoc &DL = MI.getDebugLoc();
204   MachineBasicBlock::iterator I(&MI);
205   Register SaveExecReg = MI.getOperand(0).getReg();
206   MachineOperand& Cond = MI.getOperand(1);
207   assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
208 
209   MachineOperand &ImpDefSCC = MI.getOperand(4);
210   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
211 
212   // If there is only one use of save exec register and that use is SI_END_CF,
213   // we can optimize SI_IF by returning the full saved exec mask instead of
214   // just cleared bits.
215   bool SimpleIf = isSimpleIf(MI, MRI);
216 
217   if (SimpleIf) {
218     // Check for SI_KILL_*_TERMINATOR on path from if to endif.
219     // if there is any such terminator simplifications are not safe.
220     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
221     SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
222   }
223 
224   // Add an implicit def of exec to discourage scheduling VALU after this which
225   // will interfere with trying to form s_and_saveexec_b64 later.
226   Register CopyReg = SimpleIf ? SaveExecReg
227                        : MRI->createVirtualRegister(BoolRC);
228   MachineInstr *CopyExec =
229     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
230     .addReg(Exec)
231     .addReg(Exec, RegState::ImplicitDefine);
232   LoweredIf.insert(CopyReg);
233 
234   Register Tmp = MRI->createVirtualRegister(BoolRC);
235 
236   MachineInstr *And =
237     BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
238     .addReg(CopyReg)
239     .add(Cond);
240 
241   setImpSCCDefDead(*And, true);
242 
243   MachineInstr *Xor = nullptr;
244   if (!SimpleIf) {
245     Xor =
246       BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
247       .addReg(Tmp)
248       .addReg(CopyReg);
249     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
250   }
251 
252   // Use a copy that is a terminator to get correct spill code placement it with
253   // fast regalloc.
254   MachineInstr *SetExec =
255     BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
256     .addReg(Tmp, RegState::Kill);
257 
258   // Skip ahead to the unconditional branch in case there are other terminators
259   // present.
260   I = skipToUncondBrOrEnd(MBB, I);
261 
262   // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
263   // during SIRemoveShortExecBranches.
264   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
265                             .add(MI.getOperand(2));
266 
267   if (!LIS) {
268     MI.eraseFromParent();
269     return;
270   }
271 
272   LIS->InsertMachineInstrInMaps(*CopyExec);
273 
274   // Replace with and so we don't need to fix the live interval for condition
275   // register.
276   LIS->ReplaceMachineInstrInMaps(MI, *And);
277 
278   if (!SimpleIf)
279     LIS->InsertMachineInstrInMaps(*Xor);
280   LIS->InsertMachineInstrInMaps(*SetExec);
281   LIS->InsertMachineInstrInMaps(*NewBr);
282 
283   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
284   MI.eraseFromParent();
285 
286   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
287   // hard to add another def here but I'm not sure how to correctly update the
288   // valno.
289   LIS->removeInterval(SaveExecReg);
290   LIS->createAndComputeVirtRegInterval(SaveExecReg);
291   LIS->createAndComputeVirtRegInterval(Tmp);
292   if (!SimpleIf)
293     LIS->createAndComputeVirtRegInterval(CopyReg);
294 }
295 
296 void SILowerControlFlow::emitElse(MachineInstr &MI) {
297   MachineBasicBlock &MBB = *MI.getParent();
298   const DebugLoc &DL = MI.getDebugLoc();
299 
300   Register DstReg = MI.getOperand(0).getReg();
301 
302   MachineBasicBlock::iterator Start = MBB.begin();
303 
304   // This must be inserted before phis and any spill code inserted before the
305   // else.
306   Register SaveReg = MRI->createVirtualRegister(BoolRC);
307   MachineInstr *OrSaveExec =
308     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
309     .add(MI.getOperand(1)); // Saved EXEC
310 
311   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
312 
313   MachineBasicBlock::iterator ElsePt(MI);
314 
315   // This accounts for any modification of the EXEC mask within the block and
316   // can be optimized out pre-RA when not required.
317   MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
318                           .addReg(Exec)
319                           .addReg(SaveReg);
320 
321   if (LIS)
322     LIS->InsertMachineInstrInMaps(*And);
323 
324   MachineInstr *Xor =
325     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
326     .addReg(Exec)
327     .addReg(DstReg);
328 
329   // Skip ahead to the unconditional branch in case there are other terminators
330   // present.
331   ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
332 
333   MachineInstr *Branch =
334       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
335           .addMBB(DestBB);
336 
337   if (!LIS) {
338     MI.eraseFromParent();
339     return;
340   }
341 
342   LIS->RemoveMachineInstrFromMaps(MI);
343   MI.eraseFromParent();
344 
345   LIS->InsertMachineInstrInMaps(*OrSaveExec);
346 
347   LIS->InsertMachineInstrInMaps(*Xor);
348   LIS->InsertMachineInstrInMaps(*Branch);
349 
350   LIS->removeInterval(DstReg);
351   LIS->createAndComputeVirtRegInterval(DstReg);
352   LIS->createAndComputeVirtRegInterval(SaveReg);
353 
354   // Let this be recomputed.
355   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
356 }
357 
358 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
359   MachineBasicBlock &MBB = *MI.getParent();
360   const DebugLoc &DL = MI.getDebugLoc();
361   auto Dst = MI.getOperand(0).getReg();
362 
363   // Skip ANDing with exec if the break condition is already masked by exec
364   // because it is a V_CMP in the same basic block. (We know the break
365   // condition operand was an i1 in IR, so if it is a VALU instruction it must
366   // be one with a carry-out.)
367   bool SkipAnding = false;
368   if (MI.getOperand(1).isReg()) {
369     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
370       SkipAnding = Def->getParent() == MI.getParent()
371           && SIInstrInfo::isVALU(*Def);
372     }
373   }
374 
375   // AND the break condition operand with exec, then OR that into the "loop
376   // exit" mask.
377   MachineInstr *And = nullptr, *Or = nullptr;
378   if (!SkipAnding) {
379     Register AndReg = MRI->createVirtualRegister(BoolRC);
380     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
381              .addReg(Exec)
382              .add(MI.getOperand(1));
383     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
384              .addReg(AndReg)
385              .add(MI.getOperand(2));
386     if (LIS)
387       LIS->createAndComputeVirtRegInterval(AndReg);
388   } else
389     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
390              .add(MI.getOperand(1))
391              .add(MI.getOperand(2));
392 
393   if (LIS) {
394     if (And)
395       LIS->InsertMachineInstrInMaps(*And);
396     LIS->ReplaceMachineInstrInMaps(MI, *Or);
397   }
398 
399   MI.eraseFromParent();
400 }
401 
402 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
403   MachineBasicBlock &MBB = *MI.getParent();
404   const DebugLoc &DL = MI.getDebugLoc();
405 
406   MachineInstr *AndN2 =
407       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
408           .addReg(Exec)
409           .add(MI.getOperand(0));
410 
411   auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
412   MachineInstr *Branch =
413       BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
414           .add(MI.getOperand(1));
415 
416   if (LIS) {
417     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
418     LIS->InsertMachineInstrInMaps(*Branch);
419   }
420 
421   MI.eraseFromParent();
422 }
423 
424 MachineBasicBlock::iterator
425 SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
426   MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
427 
428   SmallSet<const MachineBasicBlock *, 4> Visited;
429   MachineBasicBlock *B = &MBB;
430   do {
431     if (!Visited.insert(B).second)
432       return MBB.end();
433 
434     auto E = B->end();
435     for ( ; It != E; ++It) {
436       if (TII->mayReadEXEC(*MRI, *It))
437         break;
438     }
439 
440     if (It != E)
441       return It;
442 
443     if (B->succ_size() != 1)
444       return MBB.end();
445 
446     // If there is one trivial successor, advance to the next block.
447     MachineBasicBlock *Succ = *B->succ_begin();
448 
449     It = Succ->begin();
450     B = Succ;
451   } while (true);
452 }
453 
454 MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
455   MachineBasicBlock &MBB = *MI.getParent();
456   const DebugLoc &DL = MI.getDebugLoc();
457 
458   MachineBasicBlock::iterator InsPt = MBB.begin();
459 
460   // If we have instructions that aren't prolog instructions, split the block
461   // and emit a terminator instruction. This ensures correct spill placement.
462   // FIXME: We should unconditionally split the block here.
463   bool NeedBlockSplit = false;
464   Register DataReg = MI.getOperand(0).getReg();
465   for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
466        I != E; ++I) {
467     if (I->modifiesRegister(DataReg, TRI)) {
468       NeedBlockSplit = true;
469       break;
470     }
471   }
472 
473   unsigned Opcode = OrOpc;
474   MachineBasicBlock *SplitBB = &MBB;
475   if (NeedBlockSplit) {
476     SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
477     if (MDT && SplitBB != &MBB) {
478       MachineDomTreeNode *MBBNode = (*MDT)[&MBB];
479       SmallVector<MachineDomTreeNode *> Children(MBBNode->begin(),
480                                                  MBBNode->end());
481       MachineDomTreeNode *SplitBBNode = MDT->addNewBlock(SplitBB, &MBB);
482       for (MachineDomTreeNode *Child : Children)
483         MDT->changeImmediateDominator(Child, SplitBBNode);
484     }
485     Opcode = OrTermrOpc;
486     InsPt = MI;
487   }
488 
489   MachineInstr *NewMI =
490     BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
491     .addReg(Exec)
492     .add(MI.getOperand(0));
493 
494   LoweredEndCf.insert(NewMI);
495 
496   if (LIS)
497     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
498 
499   MI.eraseFromParent();
500 
501   if (LIS)
502     LIS->handleMove(*NewMI);
503   return SplitBB;
504 }
505 
506 // Returns replace operands for a logical operation, either single result
507 // for exec or two operands if source was another equivalent operation.
508 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
509        SmallVectorImpl<MachineOperand> &Src) const {
510   MachineOperand &Op = MI.getOperand(OpNo);
511   if (!Op.isReg() || !Op.getReg().isVirtual()) {
512     Src.push_back(Op);
513     return;
514   }
515 
516   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
517   if (!Def || Def->getParent() != MI.getParent() ||
518       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
519     return;
520 
521   // Make sure we do not modify exec between def and use.
522   // A copy with implcitly defined exec inserted earlier is an exclusion, it
523   // does not really modify exec.
524   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
525     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
526         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
527       return;
528 
529   for (const auto &SrcOp : Def->explicit_operands())
530     if (SrcOp.isReg() && SrcOp.isUse() &&
531         (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
532       Src.push_back(SrcOp);
533 }
534 
535 // Search and combine pairs of equivalent instructions, like
536 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
537 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
538 // One of the operands is exec mask.
539 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
540   assert(MI.getNumExplicitOperands() == 3);
541   SmallVector<MachineOperand, 4> Ops;
542   unsigned OpToReplace = 1;
543   findMaskOperands(MI, 1, Ops);
544   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
545   findMaskOperands(MI, 2, Ops);
546   if (Ops.size() != 3) return;
547 
548   unsigned UniqueOpndIdx;
549   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
550   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
551   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
552   else return;
553 
554   Register Reg = MI.getOperand(OpToReplace).getReg();
555   MI.RemoveOperand(OpToReplace);
556   MI.addOperand(Ops[UniqueOpndIdx]);
557   if (MRI->use_empty(Reg))
558     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
559 }
560 
561 void SILowerControlFlow::optimizeEndCf() {
562   // If the only instruction immediately following this END_CF is an another
563   // END_CF in the only successor we can avoid emitting exec mask restore here.
564   if (!RemoveRedundantEndcf)
565     return;
566 
567   for (MachineInstr *MI : LoweredEndCf) {
568     MachineBasicBlock &MBB = *MI->getParent();
569     auto Next =
570       skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
571     if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
572       continue;
573     // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
574     // If that belongs to SI_ELSE then saved mask has an inverted value.
575     Register SavedExec
576       = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
577     assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
578 
579     const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
580     if (Def && LoweredIf.count(SavedExec)) {
581       LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
582       if (LIS)
583         LIS->RemoveMachineInstrFromMaps(*MI);
584       MI->eraseFromParent();
585       removeMBBifRedundant(MBB);
586     }
587   }
588 }
589 
590 MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
591   MachineBasicBlock &MBB = *MI.getParent();
592   MachineBasicBlock::iterator I(MI);
593   MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
594 
595   MachineBasicBlock *SplitBB = &MBB;
596 
597   switch (MI.getOpcode()) {
598   case AMDGPU::SI_IF:
599     emitIf(MI);
600     break;
601 
602   case AMDGPU::SI_ELSE:
603     emitElse(MI);
604     break;
605 
606   case AMDGPU::SI_IF_BREAK:
607     emitIfBreak(MI);
608     break;
609 
610   case AMDGPU::SI_LOOP:
611     emitLoop(MI);
612     break;
613 
614   case AMDGPU::SI_WATERFALL_LOOP:
615     MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
616     break;
617 
618   case AMDGPU::SI_END_CF:
619     SplitBB = emitEndCf(MI);
620     break;
621 
622   default:
623     assert(false && "Attempt to process unsupported instruction");
624     break;
625   }
626 
627   MachineBasicBlock::iterator Next;
628   for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
629     Next = std::next(I);
630     MachineInstr &MaskMI = *I;
631     switch (MaskMI.getOpcode()) {
632     case AMDGPU::S_AND_B64:
633     case AMDGPU::S_OR_B64:
634     case AMDGPU::S_AND_B32:
635     case AMDGPU::S_OR_B32:
636       // Cleanup bit manipulations on exec mask
637       combineMasks(MaskMI);
638       break;
639     default:
640       I = MBB.end();
641       break;
642     }
643   }
644 
645   return SplitBB;
646 }
647 
648 void SILowerControlFlow::lowerInitExec(MachineBasicBlock *MBB,
649                                        MachineInstr &MI) {
650   MachineFunction &MF = *MBB->getParent();
651   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
652   bool IsWave32 = ST.isWave32();
653 
654   if (MI.getOpcode() == AMDGPU::SI_INIT_EXEC) {
655     // This should be before all vector instructions.
656     BuildMI(*MBB, MBB->begin(), MI.getDebugLoc(),
657             TII->get(IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64), Exec)
658         .addImm(MI.getOperand(0).getImm());
659     if (LIS)
660       LIS->RemoveMachineInstrFromMaps(MI);
661     MI.eraseFromParent();
662     return;
663   }
664 
665   // Extract the thread count from an SGPR input and set EXEC accordingly.
666   // Since BFM can't shift by 64, handle that case with CMP + CMOV.
667   //
668   // S_BFE_U32 count, input, {shift, 7}
669   // S_BFM_B64 exec, count, 0
670   // S_CMP_EQ_U32 count, 64
671   // S_CMOV_B64 exec, -1
672   Register InputReg = MI.getOperand(0).getReg();
673   MachineInstr *FirstMI = &*MBB->begin();
674   if (InputReg.isVirtual()) {
675     MachineInstr *DefInstr = MRI->getVRegDef(InputReg);
676     assert(DefInstr && DefInstr->isCopy());
677     if (DefInstr->getParent() == MBB) {
678       if (DefInstr != FirstMI) {
679         // If the `InputReg` is defined in current block, we also need to
680         // move that instruction to the beginning of the block.
681         DefInstr->removeFromParent();
682         MBB->insert(FirstMI, DefInstr);
683         if (LIS)
684           LIS->handleMove(*DefInstr);
685       } else {
686         // If first instruction is definition then move pointer after it.
687         FirstMI = &*std::next(FirstMI->getIterator());
688       }
689     }
690   }
691 
692   // Insert instruction sequence at block beginning (before vector operations).
693   const DebugLoc DL = MI.getDebugLoc();
694   const unsigned WavefrontSize = ST.getWavefrontSize();
695   const unsigned Mask = (WavefrontSize << 1) - 1;
696   Register CountReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
697   auto BfeMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_BFE_U32), CountReg)
698                    .addReg(InputReg)
699                    .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
700   auto BfmMI =
701       BuildMI(*MBB, FirstMI, DL,
702               TII->get(IsWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), Exec)
703           .addReg(CountReg)
704           .addImm(0);
705   auto CmpMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
706                    .addReg(CountReg, RegState::Kill)
707                    .addImm(WavefrontSize);
708   auto CmovMI =
709       BuildMI(*MBB, FirstMI, DL,
710               TII->get(IsWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
711               Exec)
712           .addImm(-1);
713 
714   if (!LIS) {
715     MI.eraseFromParent();
716     return;
717   }
718 
719   LIS->RemoveMachineInstrFromMaps(MI);
720   MI.eraseFromParent();
721 
722   LIS->InsertMachineInstrInMaps(*BfeMI);
723   LIS->InsertMachineInstrInMaps(*BfmMI);
724   LIS->InsertMachineInstrInMaps(*CmpMI);
725   LIS->InsertMachineInstrInMaps(*CmovMI);
726 
727   LIS->removeInterval(InputReg);
728   LIS->createAndComputeVirtRegInterval(InputReg);
729   LIS->createAndComputeVirtRegInterval(CountReg);
730 }
731 
732 bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
733   auto GetFallThroughSucc = [=](MachineBasicBlock *B) -> MachineBasicBlock * {
734     auto *S = B->getNextNode();
735     if (!S)
736       return nullptr;
737     if (B->isSuccessor(S)) {
738       // The only fallthrough candidate
739       MachineBasicBlock::iterator I(B->getFirstInstrTerminator());
740       MachineBasicBlock::iterator E = B->end();
741       for (; I != E; I++) {
742         if (I->isBranch() && TII->getBranchDestBlock(*I) == S)
743           // We have unoptimized branch to layout successor
744           return nullptr;
745       }
746     }
747     return S;
748   };
749 
750   for (auto &I : MBB.instrs()) {
751     if (!I.isDebugInstr() && !I.isUnconditionalBranch())
752       return false;
753   }
754 
755   assert(MBB.succ_size() == 1 && "MBB has more than one successor");
756 
757   MachineBasicBlock *Succ = *MBB.succ_begin();
758   MachineBasicBlock *FallThrough = nullptr;
759 
760   while (!MBB.predecessors().empty()) {
761     MachineBasicBlock *P = *MBB.pred_begin();
762     if (GetFallThroughSucc(P) == &MBB)
763       FallThrough = P;
764     P->ReplaceUsesOfBlockWith(&MBB, Succ);
765   }
766   MBB.removeSuccessor(Succ);
767   if (LIS) {
768     for (auto &I : MBB.instrs())
769       LIS->RemoveMachineInstrFromMaps(I);
770   }
771   if (MDT) {
772     // If Succ, the single successor of MBB, is dominated by MBB, MDT needs
773     // updating by changing Succ's idom to the one of MBB; otherwise, MBB must
774     // be a leaf node in MDT and could be erased directly.
775     if (MDT->dominates(&MBB, Succ))
776       MDT->changeImmediateDominator(MDT->getNode(Succ),
777                                     MDT->getNode(&MBB)->getIDom());
778     MDT->eraseNode(&MBB);
779   }
780   MBB.clear();
781   MBB.eraseFromParent();
782   if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
783     if (!GetFallThroughSucc(Succ)) {
784       MachineFunction *MF = FallThrough->getParent();
785       MachineFunction::iterator FallThroughPos(FallThrough);
786       MF->splice(std::next(FallThroughPos), Succ);
787     } else
788       BuildMI(*FallThrough, FallThrough->end(),
789               FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
790           .addMBB(Succ);
791   }
792 
793   return true;
794 }
795 
796 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
797   // FIXME: This pass causes verification failures.
798   MF.getProperties().set(
799       MachineFunctionProperties::Property::FailsVerification);
800 
801   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
802   TII = ST.getInstrInfo();
803   TRI = &TII->getRegisterInfo();
804 
805   // This doesn't actually need LiveIntervals, but we can preserve them.
806   LIS = getAnalysisIfAvailable<LiveIntervals>();
807   MDT = getAnalysisIfAvailable<MachineDominatorTree>();
808   MRI = &MF.getRegInfo();
809   BoolRC = TRI->getBoolRC();
810 
811   if (ST.isWave32()) {
812     AndOpc = AMDGPU::S_AND_B32;
813     OrOpc = AMDGPU::S_OR_B32;
814     XorOpc = AMDGPU::S_XOR_B32;
815     MovTermOpc = AMDGPU::S_MOV_B32_term;
816     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
817     XorTermrOpc = AMDGPU::S_XOR_B32_term;
818     OrTermrOpc = AMDGPU::S_OR_B32_term;
819     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
820     Exec = AMDGPU::EXEC_LO;
821   } else {
822     AndOpc = AMDGPU::S_AND_B64;
823     OrOpc = AMDGPU::S_OR_B64;
824     XorOpc = AMDGPU::S_XOR_B64;
825     MovTermOpc = AMDGPU::S_MOV_B64_term;
826     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
827     XorTermrOpc = AMDGPU::S_XOR_B64_term;
828     OrTermrOpc = AMDGPU::S_OR_B64_term;
829     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
830     Exec = AMDGPU::EXEC;
831   }
832 
833   // Compute set of blocks with kills
834   const bool CanDemote =
835       MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
836   for (auto &MBB : MF) {
837     bool IsKillBlock = false;
838     for (auto &Term : MBB.terminators()) {
839       if (TII->isKillTerminator(Term.getOpcode())) {
840         KillBlocks.insert(&MBB);
841         IsKillBlock = true;
842         break;
843       }
844     }
845     if (CanDemote && !IsKillBlock) {
846       for (auto &MI : MBB) {
847         if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
848           KillBlocks.insert(&MBB);
849           break;
850         }
851       }
852     }
853   }
854 
855   MachineFunction::iterator NextBB;
856   for (MachineFunction::iterator BI = MF.begin();
857        BI != MF.end(); BI = NextBB) {
858     NextBB = std::next(BI);
859     MachineBasicBlock *MBB = &*BI;
860 
861     MachineBasicBlock::iterator I, E, Next;
862     E = MBB->end();
863     for (I = MBB->begin(); I != E; I = Next) {
864       Next = std::next(I);
865       MachineInstr &MI = *I;
866       MachineBasicBlock *SplitMBB = MBB;
867 
868       switch (MI.getOpcode()) {
869       case AMDGPU::SI_IF:
870       case AMDGPU::SI_ELSE:
871       case AMDGPU::SI_IF_BREAK:
872       case AMDGPU::SI_WATERFALL_LOOP:
873       case AMDGPU::SI_LOOP:
874       case AMDGPU::SI_END_CF:
875         SplitMBB = process(MI);
876         break;
877 
878       // FIXME: find a better place for this
879       case AMDGPU::SI_INIT_EXEC:
880       case AMDGPU::SI_INIT_EXEC_FROM_INPUT:
881         lowerInitExec(MBB, MI);
882         if (LIS)
883           LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
884         break;
885 
886       default:
887         break;
888       }
889 
890       if (SplitMBB != MBB) {
891         MBB = Next->getParent();
892         E = MBB->end();
893       }
894     }
895   }
896 
897   optimizeEndCf();
898 
899   LoweredEndCf.clear();
900   LoweredIf.clear();
901   KillBlocks.clear();
902 
903   return true;
904 }
905