xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 2bd72abef0f24d9f7da13af3a43a25409159a87e)
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   // We are running before TwoAddressInstructions, and si_else's operands are
339   // tied. In order to correctly tie the registers, split this into a copy of
340   // the src like it does.
341   Register CopyReg = MRI->createVirtualRegister(BoolRC);
342   MachineInstr *CopyExec =
343     BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg)
344       .add(MI.getOperand(1)); // Saved EXEC
345 
346   // This must be inserted before phis and any spill code inserted before the
347   // else.
348   Register SaveReg = ExecModified ?
349     MRI->createVirtualRegister(BoolRC) : DstReg;
350   MachineInstr *OrSaveExec =
351     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
352     .addReg(CopyReg);
353 
354   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
355 
356   MachineBasicBlock::iterator ElsePt(MI);
357 
358   if (ExecModified) {
359     MachineInstr *And =
360       BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
361       .addReg(Exec)
362       .addReg(SaveReg);
363 
364     if (LIS)
365       LIS->InsertMachineInstrInMaps(*And);
366   }
367 
368   MachineInstr *Xor =
369     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
370     .addReg(Exec)
371     .addReg(DstReg);
372 
373   // Skip ahead to the unconditional branch in case there are other terminators
374   // present.
375   ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
376 
377   MachineInstr *Branch =
378       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
379           .addMBB(DestBB);
380 
381   if (!LIS) {
382     MI.eraseFromParent();
383     return;
384   }
385 
386   LIS->RemoveMachineInstrFromMaps(MI);
387   MI.eraseFromParent();
388 
389   LIS->InsertMachineInstrInMaps(*CopyExec);
390   LIS->InsertMachineInstrInMaps(*OrSaveExec);
391 
392   LIS->InsertMachineInstrInMaps(*Xor);
393   LIS->InsertMachineInstrInMaps(*Branch);
394 
395   // src reg is tied to dst reg.
396   LIS->removeInterval(DstReg);
397   LIS->createAndComputeVirtRegInterval(DstReg);
398   LIS->createAndComputeVirtRegInterval(CopyReg);
399   if (ExecModified)
400     LIS->createAndComputeVirtRegInterval(SaveReg);
401 
402   // Let this be recomputed.
403   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
404 }
405 
406 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
407   MachineBasicBlock &MBB = *MI.getParent();
408   const DebugLoc &DL = MI.getDebugLoc();
409   auto Dst = MI.getOperand(0).getReg();
410 
411   // Skip ANDing with exec if the break condition is already masked by exec
412   // because it is a V_CMP in the same basic block. (We know the break
413   // condition operand was an i1 in IR, so if it is a VALU instruction it must
414   // be one with a carry-out.)
415   bool SkipAnding = false;
416   if (MI.getOperand(1).isReg()) {
417     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
418       SkipAnding = Def->getParent() == MI.getParent()
419           && SIInstrInfo::isVALU(*Def);
420     }
421   }
422 
423   // AND the break condition operand with exec, then OR that into the "loop
424   // exit" mask.
425   MachineInstr *And = nullptr, *Or = nullptr;
426   if (!SkipAnding) {
427     Register AndReg = MRI->createVirtualRegister(BoolRC);
428     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
429              .addReg(Exec)
430              .add(MI.getOperand(1));
431     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
432              .addReg(AndReg)
433              .add(MI.getOperand(2));
434     if (LIS)
435       LIS->createAndComputeVirtRegInterval(AndReg);
436   } else
437     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
438              .add(MI.getOperand(1))
439              .add(MI.getOperand(2));
440 
441   if (LIS) {
442     if (And)
443       LIS->InsertMachineInstrInMaps(*And);
444     LIS->ReplaceMachineInstrInMaps(MI, *Or);
445   }
446 
447   MI.eraseFromParent();
448 }
449 
450 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
451   MachineBasicBlock &MBB = *MI.getParent();
452   const DebugLoc &DL = MI.getDebugLoc();
453 
454   MachineInstr *AndN2 =
455       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
456           .addReg(Exec)
457           .add(MI.getOperand(0));
458 
459   auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
460   MachineInstr *Branch =
461       BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
462           .add(MI.getOperand(1));
463 
464   if (LIS) {
465     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
466     LIS->InsertMachineInstrInMaps(*Branch);
467   }
468 
469   MI.eraseFromParent();
470 }
471 
472 MachineBasicBlock::iterator
473 SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
474   MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
475 
476   SmallSet<const MachineBasicBlock *, 4> Visited;
477   MachineBasicBlock *B = &MBB;
478   do {
479     if (!Visited.insert(B).second)
480       return MBB.end();
481 
482     auto E = B->end();
483     for ( ; It != E; ++It) {
484       if (It->getOpcode() == AMDGPU::SI_KILL_CLEANUP)
485         continue;
486       if (TII->mayReadEXEC(*MRI, *It))
487         break;
488     }
489 
490     if (It != E)
491       return It;
492 
493     if (B->succ_size() != 1)
494       return MBB.end();
495 
496     // If there is one trivial successor, advance to the next block.
497     MachineBasicBlock *Succ = *B->succ_begin();
498 
499     It = Succ->begin();
500     B = Succ;
501   } while (true);
502 }
503 
504 void SILowerControlFlow::emitEndCf(MachineInstr &MI) {
505   MachineBasicBlock &MBB = *MI.getParent();
506   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
507   unsigned CFMask = MI.getOperand(0).getReg();
508   MachineInstr *Def = MRI.getUniqueVRegDef(CFMask);
509   const DebugLoc &DL = MI.getDebugLoc();
510 
511   MachineBasicBlock::iterator InsPt =
512       Def && Def->getParent() == &MBB ? std::next(MachineBasicBlock::iterator(Def))
513                                : MBB.begin();
514   MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(OrOpc), Exec)
515                             .addReg(Exec)
516                             .add(MI.getOperand(0));
517 
518   LoweredEndCf.insert(NewMI);
519 
520   // If this ends control flow which contains kills (as flagged in emitIf)
521   // then insert an SI_KILL_CLEANUP immediately following the exec mask
522   // manipulation.  This can be lowered to early termination if appropriate.
523   MachineInstr *CleanUpMI = nullptr;
524   if (NeedsKillCleanup.count(&MI))
525     CleanUpMI = BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::SI_KILL_CLEANUP));
526 
527   if (LIS) {
528     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
529     if (CleanUpMI)
530       LIS->InsertMachineInstrInMaps(*CleanUpMI);
531   }
532 
533   MI.eraseFromParent();
534 
535   if (LIS)
536     LIS->handleMove(*NewMI);
537 }
538 
539 // Returns replace operands for a logical operation, either single result
540 // for exec or two operands if source was another equivalent operation.
541 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
542        SmallVectorImpl<MachineOperand> &Src) const {
543   MachineOperand &Op = MI.getOperand(OpNo);
544   if (!Op.isReg() || !Register::isVirtualRegister(Op.getReg())) {
545     Src.push_back(Op);
546     return;
547   }
548 
549   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
550   if (!Def || Def->getParent() != MI.getParent() ||
551       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
552     return;
553 
554   // Make sure we do not modify exec between def and use.
555   // A copy with implcitly defined exec inserted earlier is an exclusion, it
556   // does not really modify exec.
557   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
558     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
559         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
560       return;
561 
562   for (const auto &SrcOp : Def->explicit_operands())
563     if (SrcOp.isReg() && SrcOp.isUse() &&
564         (Register::isVirtualRegister(SrcOp.getReg()) || SrcOp.getReg() == Exec))
565       Src.push_back(SrcOp);
566 }
567 
568 // Search and combine pairs of equivalent instructions, like
569 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
570 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
571 // One of the operands is exec mask.
572 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
573   assert(MI.getNumExplicitOperands() == 3);
574   SmallVector<MachineOperand, 4> Ops;
575   unsigned OpToReplace = 1;
576   findMaskOperands(MI, 1, Ops);
577   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
578   findMaskOperands(MI, 2, Ops);
579   if (Ops.size() != 3) return;
580 
581   unsigned UniqueOpndIdx;
582   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
583   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
584   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
585   else return;
586 
587   Register Reg = MI.getOperand(OpToReplace).getReg();
588   MI.RemoveOperand(OpToReplace);
589   MI.addOperand(Ops[UniqueOpndIdx]);
590   if (MRI->use_empty(Reg))
591     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
592 }
593 
594 void SILowerControlFlow::optimizeEndCf() {
595   // If the only instruction immediately following this END_CF is an another
596   // END_CF in the only successor we can avoid emitting exec mask restore here.
597   if (!RemoveRedundantEndcf)
598     return;
599 
600   for (MachineInstr *MI : LoweredEndCf) {
601     MachineBasicBlock &MBB = *MI->getParent();
602     auto Next =
603       skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
604     if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
605       continue;
606     // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
607     // If that belongs to SI_ELSE then saved mask has an inverted value.
608     Register SavedExec
609       = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
610     assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
611 
612     const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
613     if (Def && LoweredIf.count(SavedExec)) {
614       LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
615       if (LIS)
616         LIS->RemoveMachineInstrFromMaps(*MI);
617       MI->eraseFromParent();
618     }
619   }
620 }
621 
622 void SILowerControlFlow::process(MachineInstr &MI) {
623   MachineBasicBlock &MBB = *MI.getParent();
624   MachineBasicBlock::iterator I(MI);
625   MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
626 
627   switch (MI.getOpcode()) {
628   case AMDGPU::SI_IF:
629     emitIf(MI);
630     break;
631 
632   case AMDGPU::SI_ELSE:
633     emitElse(MI);
634     break;
635 
636   case AMDGPU::SI_IF_BREAK:
637     emitIfBreak(MI);
638     break;
639 
640   case AMDGPU::SI_LOOP:
641     emitLoop(MI);
642     break;
643 
644   case AMDGPU::SI_END_CF:
645     emitEndCf(MI);
646     break;
647 
648   default:
649     assert(false && "Attempt to process unsupported instruction");
650     break;
651   }
652 
653   MachineBasicBlock::iterator Next;
654   for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
655     Next = std::next(I);
656     MachineInstr &MaskMI = *I;
657     switch (MaskMI.getOpcode()) {
658     case AMDGPU::S_AND_B64:
659     case AMDGPU::S_OR_B64:
660     case AMDGPU::S_AND_B32:
661     case AMDGPU::S_OR_B32:
662       // Cleanup bit manipulations on exec mask
663       combineMasks(MaskMI);
664       break;
665     default:
666       I = MBB.end();
667       break;
668     }
669   }
670 }
671 
672 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
673   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
674   TII = ST.getInstrInfo();
675   TRI = &TII->getRegisterInfo();
676 
677   // This doesn't actually need LiveIntervals, but we can preserve them.
678   LIS = getAnalysisIfAvailable<LiveIntervals>();
679   MRI = &MF.getRegInfo();
680   BoolRC = TRI->getBoolRC();
681   InsertKillCleanups =
682       MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
683 
684   if (ST.isWave32()) {
685     AndOpc = AMDGPU::S_AND_B32;
686     OrOpc = AMDGPU::S_OR_B32;
687     XorOpc = AMDGPU::S_XOR_B32;
688     MovTermOpc = AMDGPU::S_MOV_B32_term;
689     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
690     XorTermrOpc = AMDGPU::S_XOR_B32_term;
691     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
692     Exec = AMDGPU::EXEC_LO;
693   } else {
694     AndOpc = AMDGPU::S_AND_B64;
695     OrOpc = AMDGPU::S_OR_B64;
696     XorOpc = AMDGPU::S_XOR_B64;
697     MovTermOpc = AMDGPU::S_MOV_B64_term;
698     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
699     XorTermrOpc = AMDGPU::S_XOR_B64_term;
700     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
701     Exec = AMDGPU::EXEC;
702   }
703 
704   SmallVector<MachineInstr *, 32> Worklist;
705 
706   MachineFunction::iterator NextBB;
707   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
708        BI != BE; BI = NextBB) {
709     NextBB = std::next(BI);
710     MachineBasicBlock &MBB = *BI;
711 
712     MachineBasicBlock::iterator I, Next;
713     for (I = MBB.begin(); I != MBB.end(); I = Next) {
714       Next = std::next(I);
715       MachineInstr &MI = *I;
716 
717       switch (MI.getOpcode()) {
718       case AMDGPU::SI_IF:
719         process(MI);
720         break;
721 
722       case AMDGPU::SI_ELSE:
723       case AMDGPU::SI_IF_BREAK:
724       case AMDGPU::SI_LOOP:
725       case AMDGPU::SI_END_CF:
726         // Only build worklist if SI_IF instructions must be processed first.
727         if (InsertKillCleanups)
728           Worklist.push_back(&MI);
729         else
730           process(MI);
731         break;
732 
733       default:
734         break;
735       }
736     }
737   }
738 
739   for (MachineInstr *MI : Worklist)
740     process(*MI);
741 
742   optimizeEndCf();
743 
744   LoweredEndCf.clear();
745   LoweredIf.clear();
746   NeedsKillCleanup.clear();
747 
748   return true;
749 }
750