xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 3c2a7bd2867eda29da8ddf5f2db2e006d504e611)
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 "AMDGPUSubtarget.h"
52 #include "SIInstrInfo.h"
53 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/CodeGen/LiveIntervals.h"
59 #include "llvm/CodeGen/MachineBasicBlock.h"
60 #include "llvm/CodeGen/MachineFunction.h"
61 #include "llvm/CodeGen/MachineFunctionPass.h"
62 #include "llvm/CodeGen/MachineInstr.h"
63 #include "llvm/CodeGen/MachineInstrBuilder.h"
64 #include "llvm/CodeGen/MachineOperand.h"
65 #include "llvm/CodeGen/MachineRegisterInfo.h"
66 #include "llvm/CodeGen/Passes.h"
67 #include "llvm/CodeGen/SlotIndexes.h"
68 #include "llvm/CodeGen/TargetRegisterInfo.h"
69 #include "llvm/MC/MCRegisterInfo.h"
70 #include "llvm/Pass.h"
71 #include <cassert>
72 #include <iterator>
73 
74 using namespace llvm;
75 
76 #define DEBUG_TYPE "si-lower-control-flow"
77 
78 static cl::opt<bool>
79 RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
80     cl::init(true), cl::ReallyHidden);
81 
82 namespace {
83 
84 class SILowerControlFlow : public MachineFunctionPass {
85 private:
86   const SIRegisterInfo *TRI = nullptr;
87   const SIInstrInfo *TII = nullptr;
88   LiveIntervals *LIS = nullptr;
89   MachineRegisterInfo *MRI = nullptr;
90   SetVector<MachineInstr*> LoweredEndCf;
91   DenseSet<Register> LoweredIf;
92   SmallSet<MachineInstr *, 16> NeedsKillCleanup;
93 
94   const TargetRegisterClass *BoolRC = nullptr;
95   bool InsertKillCleanups;
96   unsigned AndOpc;
97   unsigned OrOpc;
98   unsigned XorOpc;
99   unsigned MovTermOpc;
100   unsigned Andn2TermOpc;
101   unsigned XorTermrOpc;
102   unsigned OrSaveExecOpc;
103   unsigned Exec;
104 
105   void emitIf(MachineInstr &MI);
106   void emitElse(MachineInstr &MI);
107   void emitIfBreak(MachineInstr &MI);
108   void emitLoop(MachineInstr &MI);
109   void emitEndCf(MachineInstr &MI);
110 
111   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
112                         SmallVectorImpl<MachineOperand> &Src) const;
113 
114   void combineMasks(MachineInstr &MI);
115 
116   void process(MachineInstr &MI);
117 
118   // Skip to the next instruction, ignoring debug instructions, and trivial
119   // block boundaries (blocks that have one (typically fallthrough) successor,
120   // and the successor has one predecessor.
121   MachineBasicBlock::iterator
122   skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
123                                  MachineBasicBlock::iterator It) const;
124 
125   /// Find the insertion point for a new conditional branch.
126   MachineBasicBlock::iterator
127   skipToUncondBrOrEnd(MachineBasicBlock &MBB,
128                       MachineBasicBlock::iterator I) const {
129     assert(I->isTerminator());
130 
131     // FIXME: What if we had multiple pre-existing conditional branches?
132     MachineBasicBlock::iterator End = MBB.end();
133     while (I != End && !I->isUnconditionalBranch())
134       ++I;
135     return I;
136   }
137 
138   // Remove redundant SI_END_CF instructions.
139   void optimizeEndCf();
140 
141 public:
142   static char ID;
143 
144   SILowerControlFlow() : MachineFunctionPass(ID) {}
145 
146   bool runOnMachineFunction(MachineFunction &MF) override;
147 
148   StringRef getPassName() const override {
149     return "SI Lower control flow pseudo instructions";
150   }
151 
152   void getAnalysisUsage(AnalysisUsage &AU) const override {
153     // Should preserve the same set that TwoAddressInstructions does.
154     AU.addPreserved<SlotIndexes>();
155     AU.addPreserved<LiveIntervals>();
156     AU.addPreservedID(LiveVariablesID);
157     AU.addPreservedID(MachineLoopInfoID);
158     AU.addPreservedID(MachineDominatorsID);
159     AU.setPreservesCFG();
160     MachineFunctionPass::getAnalysisUsage(AU);
161   }
162 };
163 
164 } // end anonymous namespace
165 
166 char SILowerControlFlow::ID = 0;
167 
168 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
169                "SI lower control flow", false, false)
170 
171 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
172   MachineOperand &ImpDefSCC = MI.getOperand(3);
173   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
174 
175   ImpDefSCC.setIsDead(IsDead);
176 }
177 
178 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
179 
180 static bool hasKill(const MachineBasicBlock *Begin,
181                     const MachineBasicBlock *End, const SIInstrInfo *TII) {
182   DenseSet<const MachineBasicBlock*> Visited;
183   SmallVector<MachineBasicBlock *, 4> Worklist(Begin->succ_begin(),
184                                                Begin->succ_end());
185 
186   while (!Worklist.empty()) {
187     MachineBasicBlock *MBB = Worklist.pop_back_val();
188 
189     if (MBB == End || !Visited.insert(MBB).second)
190       continue;
191     for (auto &Term : MBB->terminators())
192       if (TII->isKillTerminator(Term.getOpcode()))
193         return true;
194 
195     Worklist.append(MBB->succ_begin(), MBB->succ_end());
196   }
197 
198   return false;
199 }
200 
201 static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
202   Register SaveExecReg = MI.getOperand(0).getReg();
203   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
204 
205   if (U == MRI->use_instr_nodbg_end() ||
206       std::next(U) != MRI->use_instr_nodbg_end() ||
207       U->getOpcode() != AMDGPU::SI_END_CF)
208     return false;
209 
210   return true;
211 }
212 
213 void SILowerControlFlow::emitIf(MachineInstr &MI) {
214   MachineBasicBlock &MBB = *MI.getParent();
215   const DebugLoc &DL = MI.getDebugLoc();
216   MachineBasicBlock::iterator I(&MI);
217   Register SaveExecReg = MI.getOperand(0).getReg();
218   MachineOperand& Cond = MI.getOperand(1);
219   assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
220 
221   MachineOperand &ImpDefSCC = MI.getOperand(4);
222   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
223 
224   // If there is only one use of save exec register and that use is SI_END_CF,
225   // we can optimize SI_IF by returning the full saved exec mask instead of
226   // just cleared bits.
227   bool SimpleIf = isSimpleIf(MI, MRI);
228 
229   if (InsertKillCleanups) {
230     // Check for SI_KILL_*_TERMINATOR on full path of control flow and
231     // flag the associated SI_END_CF for insertion of a kill cleanup.
232     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
233     while (UseMI->getOpcode() != AMDGPU::SI_END_CF) {
234       assert(std::next(UseMI) == MRI->use_instr_nodbg_end());
235       assert(UseMI->getOpcode() == AMDGPU::SI_ELSE);
236       MachineOperand &NextExec = UseMI->getOperand(0);
237       Register NextExecReg = NextExec.getReg();
238       if (NextExec.isDead()) {
239         assert(!SimpleIf);
240         break;
241       }
242       UseMI = MRI->use_instr_nodbg_begin(NextExecReg);
243     }
244     if (UseMI->getOpcode() == AMDGPU::SI_END_CF) {
245       if (hasKill(MI.getParent(), UseMI->getParent(), TII)) {
246         NeedsKillCleanup.insert(&*UseMI);
247         SimpleIf = false;
248       }
249     }
250   } else if (SimpleIf) {
251     // Check for SI_KILL_*_TERMINATOR on path from if to endif.
252     // if there is any such terminator simplifications are not safe.
253     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
254     SimpleIf = !hasKill(MI.getParent(), UseMI->getParent(), TII);
255   }
256 
257   // Add an implicit def of exec to discourage scheduling VALU after this which
258   // will interfere with trying to form s_and_saveexec_b64 later.
259   Register CopyReg = SimpleIf ? SaveExecReg
260                        : MRI->createVirtualRegister(BoolRC);
261   MachineInstr *CopyExec =
262     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
263     .addReg(Exec)
264     .addReg(Exec, RegState::ImplicitDefine);
265   LoweredIf.insert(CopyReg);
266 
267   Register Tmp = MRI->createVirtualRegister(BoolRC);
268 
269   MachineInstr *And =
270     BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
271     .addReg(CopyReg)
272     .add(Cond);
273 
274   setImpSCCDefDead(*And, true);
275 
276   MachineInstr *Xor = nullptr;
277   if (!SimpleIf) {
278     Xor =
279       BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
280       .addReg(Tmp)
281       .addReg(CopyReg);
282     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
283   }
284 
285   // Use a copy that is a terminator to get correct spill code placement it with
286   // fast regalloc.
287   MachineInstr *SetExec =
288     BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
289     .addReg(Tmp, RegState::Kill);
290 
291   // Skip ahead to the unconditional branch in case there are other terminators
292   // present.
293   I = skipToUncondBrOrEnd(MBB, I);
294 
295   // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
296   // during SIRemoveShortExecBranches.
297   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
298                             .add(MI.getOperand(2));
299 
300   if (!LIS) {
301     MI.eraseFromParent();
302     return;
303   }
304 
305   LIS->InsertMachineInstrInMaps(*CopyExec);
306 
307   // Replace with and so we don't need to fix the live interval for condition
308   // register.
309   LIS->ReplaceMachineInstrInMaps(MI, *And);
310 
311   if (!SimpleIf)
312     LIS->InsertMachineInstrInMaps(*Xor);
313   LIS->InsertMachineInstrInMaps(*SetExec);
314   LIS->InsertMachineInstrInMaps(*NewBr);
315 
316   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
317   MI.eraseFromParent();
318 
319   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
320   // hard to add another def here but I'm not sure how to correctly update the
321   // valno.
322   LIS->removeInterval(SaveExecReg);
323   LIS->createAndComputeVirtRegInterval(SaveExecReg);
324   LIS->createAndComputeVirtRegInterval(Tmp);
325   if (!SimpleIf)
326     LIS->createAndComputeVirtRegInterval(CopyReg);
327 }
328 
329 void SILowerControlFlow::emitElse(MachineInstr &MI) {
330   MachineBasicBlock &MBB = *MI.getParent();
331   const DebugLoc &DL = MI.getDebugLoc();
332 
333   Register DstReg = MI.getOperand(0).getReg();
334 
335   bool ExecModified = MI.getOperand(3).getImm() != 0;
336   MachineBasicBlock::iterator Start = MBB.begin();
337 
338   // This must be inserted before phis and any spill code inserted before the
339   // else.
340   Register SaveReg = ExecModified ?
341     MRI->createVirtualRegister(BoolRC) : DstReg;
342   MachineInstr *OrSaveExec =
343     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
344     .add(MI.getOperand(1)); // Saved EXEC
345 
346   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
347 
348   MachineBasicBlock::iterator ElsePt(MI);
349 
350   if (ExecModified) {
351     MachineInstr *And =
352       BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
353       .addReg(Exec)
354       .addReg(SaveReg);
355 
356     if (LIS)
357       LIS->InsertMachineInstrInMaps(*And);
358   }
359 
360   MachineInstr *Xor =
361     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
362     .addReg(Exec)
363     .addReg(DstReg);
364 
365   // Skip ahead to the unconditional branch in case there are other terminators
366   // present.
367   ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
368 
369   MachineInstr *Branch =
370       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
371           .addMBB(DestBB);
372 
373   if (!LIS) {
374     MI.eraseFromParent();
375     return;
376   }
377 
378   LIS->RemoveMachineInstrFromMaps(MI);
379   MI.eraseFromParent();
380 
381   LIS->InsertMachineInstrInMaps(*OrSaveExec);
382 
383   LIS->InsertMachineInstrInMaps(*Xor);
384   LIS->InsertMachineInstrInMaps(*Branch);
385 
386   LIS->removeInterval(DstReg);
387   LIS->createAndComputeVirtRegInterval(DstReg);
388   if (ExecModified)
389     LIS->createAndComputeVirtRegInterval(SaveReg);
390 
391   // Let this be recomputed.
392   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
393 }
394 
395 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
396   MachineBasicBlock &MBB = *MI.getParent();
397   const DebugLoc &DL = MI.getDebugLoc();
398   auto Dst = MI.getOperand(0).getReg();
399 
400   // Skip ANDing with exec if the break condition is already masked by exec
401   // because it is a V_CMP in the same basic block. (We know the break
402   // condition operand was an i1 in IR, so if it is a VALU instruction it must
403   // be one with a carry-out.)
404   bool SkipAnding = false;
405   if (MI.getOperand(1).isReg()) {
406     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
407       SkipAnding = Def->getParent() == MI.getParent()
408           && SIInstrInfo::isVALU(*Def);
409     }
410   }
411 
412   // AND the break condition operand with exec, then OR that into the "loop
413   // exit" mask.
414   MachineInstr *And = nullptr, *Or = nullptr;
415   if (!SkipAnding) {
416     Register AndReg = MRI->createVirtualRegister(BoolRC);
417     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
418              .addReg(Exec)
419              .add(MI.getOperand(1));
420     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
421              .addReg(AndReg)
422              .add(MI.getOperand(2));
423     if (LIS)
424       LIS->createAndComputeVirtRegInterval(AndReg);
425   } else
426     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
427              .add(MI.getOperand(1))
428              .add(MI.getOperand(2));
429 
430   if (LIS) {
431     if (And)
432       LIS->InsertMachineInstrInMaps(*And);
433     LIS->ReplaceMachineInstrInMaps(MI, *Or);
434   }
435 
436   MI.eraseFromParent();
437 }
438 
439 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
440   MachineBasicBlock &MBB = *MI.getParent();
441   const DebugLoc &DL = MI.getDebugLoc();
442 
443   MachineInstr *AndN2 =
444       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
445           .addReg(Exec)
446           .add(MI.getOperand(0));
447 
448   auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
449   MachineInstr *Branch =
450       BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
451           .add(MI.getOperand(1));
452 
453   if (LIS) {
454     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
455     LIS->InsertMachineInstrInMaps(*Branch);
456   }
457 
458   MI.eraseFromParent();
459 }
460 
461 MachineBasicBlock::iterator
462 SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
463   MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
464 
465   SmallSet<const MachineBasicBlock *, 4> Visited;
466   MachineBasicBlock *B = &MBB;
467   do {
468     if (!Visited.insert(B).second)
469       return MBB.end();
470 
471     auto E = B->end();
472     for ( ; It != E; ++It) {
473       if (It->getOpcode() == AMDGPU::SI_KILL_CLEANUP)
474         continue;
475       if (TII->mayReadEXEC(*MRI, *It))
476         break;
477     }
478 
479     if (It != E)
480       return It;
481 
482     if (B->succ_size() != 1)
483       return MBB.end();
484 
485     // If there is one trivial successor, advance to the next block.
486     MachineBasicBlock *Succ = *B->succ_begin();
487 
488     It = Succ->begin();
489     B = Succ;
490   } while (true);
491 }
492 
493 void SILowerControlFlow::emitEndCf(MachineInstr &MI) {
494   MachineBasicBlock &MBB = *MI.getParent();
495   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
496   Register CFMask = MI.getOperand(0).getReg();
497   MachineInstr *Def = MRI.getUniqueVRegDef(CFMask);
498   const DebugLoc &DL = MI.getDebugLoc();
499 
500   MachineBasicBlock::iterator InsPt =
501       Def && Def->getParent() == &MBB ? std::next(MachineBasicBlock::iterator(Def))
502                                : MBB.begin();
503   MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(OrOpc), Exec)
504                             .addReg(Exec)
505                             .add(MI.getOperand(0));
506 
507   LoweredEndCf.insert(NewMI);
508 
509   // If this ends control flow which contains kills (as flagged in emitIf)
510   // then insert an SI_KILL_CLEANUP immediately following the exec mask
511   // manipulation.  This can be lowered to early termination if appropriate.
512   MachineInstr *CleanUpMI = nullptr;
513   if (NeedsKillCleanup.count(&MI))
514     CleanUpMI = BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::SI_KILL_CLEANUP));
515 
516   if (LIS) {
517     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
518     if (CleanUpMI)
519       LIS->InsertMachineInstrInMaps(*CleanUpMI);
520   }
521 
522   MI.eraseFromParent();
523 
524   if (LIS)
525     LIS->handleMove(*NewMI);
526 }
527 
528 // Returns replace operands for a logical operation, either single result
529 // for exec or two operands if source was another equivalent operation.
530 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
531        SmallVectorImpl<MachineOperand> &Src) const {
532   MachineOperand &Op = MI.getOperand(OpNo);
533   if (!Op.isReg() || !Op.getReg().isVirtual()) {
534     Src.push_back(Op);
535     return;
536   }
537 
538   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
539   if (!Def || Def->getParent() != MI.getParent() ||
540       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
541     return;
542 
543   // Make sure we do not modify exec between def and use.
544   // A copy with implcitly defined exec inserted earlier is an exclusion, it
545   // does not really modify exec.
546   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
547     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
548         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
549       return;
550 
551   for (const auto &SrcOp : Def->explicit_operands())
552     if (SrcOp.isReg() && SrcOp.isUse() &&
553         (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
554       Src.push_back(SrcOp);
555 }
556 
557 // Search and combine pairs of equivalent instructions, like
558 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
559 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
560 // One of the operands is exec mask.
561 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
562   assert(MI.getNumExplicitOperands() == 3);
563   SmallVector<MachineOperand, 4> Ops;
564   unsigned OpToReplace = 1;
565   findMaskOperands(MI, 1, Ops);
566   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
567   findMaskOperands(MI, 2, Ops);
568   if (Ops.size() != 3) return;
569 
570   unsigned UniqueOpndIdx;
571   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
572   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
573   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
574   else return;
575 
576   Register Reg = MI.getOperand(OpToReplace).getReg();
577   MI.RemoveOperand(OpToReplace);
578   MI.addOperand(Ops[UniqueOpndIdx]);
579   if (MRI->use_empty(Reg))
580     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
581 }
582 
583 void SILowerControlFlow::optimizeEndCf() {
584   // If the only instruction immediately following this END_CF is an another
585   // END_CF in the only successor we can avoid emitting exec mask restore here.
586   if (!RemoveRedundantEndcf)
587     return;
588 
589   for (MachineInstr *MI : LoweredEndCf) {
590     MachineBasicBlock &MBB = *MI->getParent();
591     auto Next =
592       skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
593     if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
594       continue;
595     // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
596     // If that belongs to SI_ELSE then saved mask has an inverted value.
597     Register SavedExec
598       = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
599     assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
600 
601     const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
602     if (Def && LoweredIf.count(SavedExec)) {
603       LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
604       if (LIS)
605         LIS->RemoveMachineInstrFromMaps(*MI);
606       MI->eraseFromParent();
607     }
608   }
609 }
610 
611 void SILowerControlFlow::process(MachineInstr &MI) {
612   MachineBasicBlock &MBB = *MI.getParent();
613   MachineBasicBlock::iterator I(MI);
614   MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
615 
616   switch (MI.getOpcode()) {
617   case AMDGPU::SI_IF:
618     emitIf(MI);
619     break;
620 
621   case AMDGPU::SI_ELSE:
622     emitElse(MI);
623     break;
624 
625   case AMDGPU::SI_IF_BREAK:
626     emitIfBreak(MI);
627     break;
628 
629   case AMDGPU::SI_LOOP:
630     emitLoop(MI);
631     break;
632 
633   case AMDGPU::SI_END_CF:
634     emitEndCf(MI);
635     break;
636 
637   default:
638     assert(false && "Attempt to process unsupported instruction");
639     break;
640   }
641 
642   MachineBasicBlock::iterator Next;
643   for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
644     Next = std::next(I);
645     MachineInstr &MaskMI = *I;
646     switch (MaskMI.getOpcode()) {
647     case AMDGPU::S_AND_B64:
648     case AMDGPU::S_OR_B64:
649     case AMDGPU::S_AND_B32:
650     case AMDGPU::S_OR_B32:
651       // Cleanup bit manipulations on exec mask
652       combineMasks(MaskMI);
653       break;
654     default:
655       I = MBB.end();
656       break;
657     }
658   }
659 }
660 
661 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
662   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
663   TII = ST.getInstrInfo();
664   TRI = &TII->getRegisterInfo();
665 
666   // This doesn't actually need LiveIntervals, but we can preserve them.
667   LIS = getAnalysisIfAvailable<LiveIntervals>();
668   MRI = &MF.getRegInfo();
669   BoolRC = TRI->getBoolRC();
670   InsertKillCleanups =
671       MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
672 
673   if (ST.isWave32()) {
674     AndOpc = AMDGPU::S_AND_B32;
675     OrOpc = AMDGPU::S_OR_B32;
676     XorOpc = AMDGPU::S_XOR_B32;
677     MovTermOpc = AMDGPU::S_MOV_B32_term;
678     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
679     XorTermrOpc = AMDGPU::S_XOR_B32_term;
680     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
681     Exec = AMDGPU::EXEC_LO;
682   } else {
683     AndOpc = AMDGPU::S_AND_B64;
684     OrOpc = AMDGPU::S_OR_B64;
685     XorOpc = AMDGPU::S_XOR_B64;
686     MovTermOpc = AMDGPU::S_MOV_B64_term;
687     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
688     XorTermrOpc = AMDGPU::S_XOR_B64_term;
689     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
690     Exec = AMDGPU::EXEC;
691   }
692 
693   SmallVector<MachineInstr *, 32> Worklist;
694 
695   MachineFunction::iterator NextBB;
696   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
697        BI != BE; BI = NextBB) {
698     NextBB = std::next(BI);
699     MachineBasicBlock &MBB = *BI;
700 
701     MachineBasicBlock::iterator I, Next;
702     for (I = MBB.begin(); I != MBB.end(); I = Next) {
703       Next = std::next(I);
704       MachineInstr &MI = *I;
705 
706       switch (MI.getOpcode()) {
707       case AMDGPU::SI_IF:
708         process(MI);
709         break;
710 
711       case AMDGPU::SI_ELSE:
712       case AMDGPU::SI_IF_BREAK:
713       case AMDGPU::SI_LOOP:
714       case AMDGPU::SI_END_CF:
715         // Only build worklist if SI_IF instructions must be processed first.
716         if (InsertKillCleanups)
717           Worklist.push_back(&MI);
718         else
719           process(MI);
720         break;
721 
722       default:
723         break;
724       }
725     }
726   }
727 
728   for (MachineInstr *MI : Worklist)
729     process(*MI);
730 
731   optimizeEndCf();
732 
733   LoweredEndCf.clear();
734   LoweredIf.clear();
735   NeedsKillCleanup.clear();
736 
737   return true;
738 }
739