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