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