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