1 //===--------------------- SIOptimizeVGPRLiveRange.cpp  -------------------===//
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 tries to remove unnecessary VGPR live ranges in divergent if-else
11 /// structures and waterfall loops.
12 ///
13 /// When we do structurization, we usually transform an if-else into two
14 /// sucessive if-then (with a flow block to do predicate inversion). Consider a
15 /// simple case after structurization: A divergent value %a was defined before
16 /// if-else and used in both THEN (use in THEN is optional) and ELSE part:
17 ///    bb.if:
18 ///      %a = ...
19 ///      ...
20 ///    bb.then:
21 ///      ... = op %a
22 ///      ... // %a can be dead here
23 ///    bb.flow:
24 ///      ...
25 ///    bb.else:
26 ///      ... = %a
27 ///      ...
28 ///    bb.endif
29 ///
30 ///  As register allocator has no idea of the thread-control-flow, it will just
31 ///  assume %a would be alive in the whole range of bb.then because of a later
32 ///  use in bb.else. On AMDGPU architecture, the VGPR is accessed with respect
33 ///  to exec mask. For this if-else case, the lanes active in bb.then will be
34 ///  inactive in bb.else, and vice-versa. So we are safe to say that %a was dead
35 ///  after the last use in bb.then until the end of the block. The reason is
36 ///  the instructions in bb.then will only overwrite lanes that will never be
37 ///  accessed in bb.else.
38 ///
39 ///  This pass aims to to tell register allocator that %a is in-fact dead,
40 ///  through inserting a phi-node in bb.flow saying that %a is undef when coming
41 ///  from bb.then, and then replace the uses in the bb.else with the result of
42 ///  newly inserted phi.
43 ///
44 ///  Two key conditions must be met to ensure correctness:
45 ///  1.) The def-point should be in the same loop-level as if-else-endif to make
46 ///      sure the second loop iteration still get correct data.
47 ///  2.) There should be no further uses after the IF-ELSE region.
48 ///
49 ///
50 /// Waterfall loops get inserted around instructions that use divergent values
51 /// but can only be executed with a uniform value. For example an indirect call
52 /// to a divergent address:
53 ///    bb.start:
54 ///      %a = ...
55 ///      %fun = ...
56 ///      ...
57 ///    bb.loop:
58 ///      call %fun (%a)
59 ///      ... // %a can be dead here
60 ///      loop %bb.loop
61 ///
62 ///  The loop block is executed multiple times, but it is run exactly once for
63 ///  each active lane. Similar to the if-else case, the register allocator
64 ///  assumes that %a is live throughout the loop as it is used again in the next
65 ///  iteration. If %a is a VGPR that is unused after the loop, it does not need
66 ///  to be live after its last use in the loop block. By inserting a phi-node at
67 ///  the start of bb.loop that is undef when coming from bb.loop, the register
68 ///  allocation knows that the value of %a does not need to be preserved through
69 ///  iterations of the loop.
70 ///
71 //
72 //===----------------------------------------------------------------------===//
73 
74 #include "AMDGPU.h"
75 #include "GCNSubtarget.h"
76 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
77 #include "SIMachineFunctionInfo.h"
78 #include "llvm/CodeGen/LiveVariables.h"
79 #include "llvm/CodeGen/MachineDominators.h"
80 #include "llvm/CodeGen/MachineLoopInfo.h"
81 #include "llvm/CodeGen/TargetRegisterInfo.h"
82 #include "llvm/InitializePasses.h"
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-opt-vgpr-liverange"
87 
88 namespace {
89 
90 class SIOptimizeVGPRLiveRange : public MachineFunctionPass {
91 private:
92   const SIRegisterInfo *TRI = nullptr;
93   const SIInstrInfo *TII = nullptr;
94   LiveVariables *LV = nullptr;
95   MachineDominatorTree *MDT = nullptr;
96   const MachineLoopInfo *Loops = nullptr;
97   MachineRegisterInfo *MRI = nullptr;
98 
99 public:
100   static char ID;
101 
102   MachineBasicBlock *getElseTarget(MachineBasicBlock *MBB) const;
103 
104   void collectElseRegionBlocks(MachineBasicBlock *Flow,
105                                MachineBasicBlock *Endif,
106                                SmallSetVector<MachineBasicBlock *, 16> &) const;
107 
108   void
109   collectCandidateRegisters(MachineBasicBlock *If, MachineBasicBlock *Flow,
110                             MachineBasicBlock *Endif,
111                             SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks,
112                             SmallVectorImpl<Register> &CandidateRegs) const;
113 
114   void collectWaterfallCandidateRegisters(
115       MachineBasicBlock *Loop,
116       SmallSetVector<Register, 16> &CandidateRegs) const;
117 
118   void findNonPHIUsesInBlock(Register Reg, MachineBasicBlock *MBB,
119                              SmallVectorImpl<MachineInstr *> &Uses) const;
120 
121   void updateLiveRangeInThenRegion(Register Reg, MachineBasicBlock *If,
122                                    MachineBasicBlock *Flow) const;
123 
124   void updateLiveRangeInElseRegion(
125       Register Reg, Register NewReg, MachineBasicBlock *Flow,
126       MachineBasicBlock *Endif,
127       SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const;
128 
129   void
130   optimizeLiveRange(Register Reg, MachineBasicBlock *If,
131                     MachineBasicBlock *Flow, MachineBasicBlock *Endif,
132                     SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const;
133 
134   void optimizeWaterfallLiveRange(Register Reg, MachineBasicBlock *If) const;
135 
136   SIOptimizeVGPRLiveRange() : MachineFunctionPass(ID) {}
137 
138   bool runOnMachineFunction(MachineFunction &MF) override;
139 
140   StringRef getPassName() const override {
141     return "SI Optimize VGPR LiveRange";
142   }
143 
144   void getAnalysisUsage(AnalysisUsage &AU) const override {
145     AU.addRequired<LiveVariables>();
146     AU.addRequired<MachineDominatorTree>();
147     AU.addRequired<MachineLoopInfo>();
148     AU.addPreserved<LiveVariables>();
149     AU.addPreserved<MachineDominatorTree>();
150     AU.addPreserved<MachineLoopInfo>();
151     MachineFunctionPass::getAnalysisUsage(AU);
152   }
153 
154   MachineFunctionProperties getRequiredProperties() const override {
155     return MachineFunctionProperties().set(
156         MachineFunctionProperties::Property::IsSSA);
157   }
158 };
159 
160 } // end anonymous namespace
161 
162 // Check whether the MBB is a else flow block and get the branching target which
163 // is the Endif block
164 MachineBasicBlock *
165 SIOptimizeVGPRLiveRange::getElseTarget(MachineBasicBlock *MBB) const {
166   for (auto &BR : MBB->terminators()) {
167     if (BR.getOpcode() == AMDGPU::SI_ELSE)
168       return BR.getOperand(2).getMBB();
169   }
170   return nullptr;
171 }
172 
173 void SIOptimizeVGPRLiveRange::collectElseRegionBlocks(
174     MachineBasicBlock *Flow, MachineBasicBlock *Endif,
175     SmallSetVector<MachineBasicBlock *, 16> &Blocks) const {
176   assert(Flow != Endif);
177 
178   MachineBasicBlock *MBB = Endif;
179   unsigned Cur = 0;
180   while (MBB) {
181     for (auto *Pred : MBB->predecessors()) {
182       if (Pred != Flow && !Blocks.contains(Pred))
183         Blocks.insert(Pred);
184     }
185 
186     if (Cur < Blocks.size())
187       MBB = Blocks[Cur++];
188     else
189       MBB = nullptr;
190   }
191 
192   LLVM_DEBUG({
193     dbgs() << "Found Else blocks: ";
194     for (auto *MBB : Blocks)
195       dbgs() << printMBBReference(*MBB) << ' ';
196     dbgs() << '\n';
197   });
198 }
199 
200 /// Find the instructions(excluding phi) in \p MBB that uses the \p Reg.
201 void SIOptimizeVGPRLiveRange::findNonPHIUsesInBlock(
202     Register Reg, MachineBasicBlock *MBB,
203     SmallVectorImpl<MachineInstr *> &Uses) const {
204   for (auto &UseMI : MRI->use_nodbg_instructions(Reg)) {
205     if (UseMI.getParent() == MBB && !UseMI.isPHI())
206       Uses.push_back(&UseMI);
207   }
208 }
209 
210 /// Collect the killed registers in the ELSE region which are not alive through
211 /// the whole THEN region.
212 void SIOptimizeVGPRLiveRange::collectCandidateRegisters(
213     MachineBasicBlock *If, MachineBasicBlock *Flow, MachineBasicBlock *Endif,
214     SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks,
215     SmallVectorImpl<Register> &CandidateRegs) const {
216 
217   SmallSet<Register, 8> KillsInElse;
218 
219   for (auto *Else : ElseBlocks) {
220     for (auto &MI : Else->instrs()) {
221       if (MI.isDebugInstr())
222         continue;
223 
224       for (auto &MO : MI.operands()) {
225         if (!MO.isReg() || !MO.getReg() || MO.isDef())
226           continue;
227 
228         Register MOReg = MO.getReg();
229         // We can only optimize AGPR/VGPR virtual register
230         if (MOReg.isPhysical() || !TRI->isVectorRegister(*MRI, MOReg))
231           continue;
232 
233         if (MO.isKill() && MO.readsReg()) {
234           LiveVariables::VarInfo &VI = LV->getVarInfo(MOReg);
235           const MachineBasicBlock *DefMBB = MRI->getVRegDef(MOReg)->getParent();
236           // Make sure two conditions are met:
237           // a.) the value is defined before/in the IF block
238           // b.) should be defined in the same loop-level.
239           if ((VI.AliveBlocks.test(If->getNumber()) || DefMBB == If) &&
240               Loops->getLoopFor(DefMBB) == Loops->getLoopFor(If))
241             KillsInElse.insert(MOReg);
242         }
243       }
244     }
245   }
246 
247   // Check the phis in the Endif, looking for value coming from the ELSE
248   // region. Make sure the phi-use is the last use.
249   for (auto &MI : Endif->phis()) {
250     for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
251       auto &MO = MI.getOperand(Idx);
252       auto *Pred = MI.getOperand(Idx + 1).getMBB();
253       if (Pred == Flow)
254         continue;
255       assert(ElseBlocks.contains(Pred) && "Should be from Else region\n");
256 
257       if (!MO.isReg() || !MO.getReg() || MO.isUndef())
258         continue;
259 
260       Register Reg = MO.getReg();
261       if (Reg.isPhysical() || !TRI->isVectorRegister(*MRI, Reg))
262         continue;
263 
264       LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
265 
266       if (VI.isLiveIn(*Endif, Reg, *MRI)) {
267         LLVM_DEBUG(dbgs() << "Excluding " << printReg(Reg, TRI)
268                           << " as Live in Endif\n");
269         continue;
270       }
271       // Make sure two conditions are met:
272       // a.) the value is defined before/in the IF block
273       // b.) should be defined in the same loop-level.
274       const MachineBasicBlock *DefMBB = MRI->getVRegDef(Reg)->getParent();
275       if ((VI.AliveBlocks.test(If->getNumber()) || DefMBB == If) &&
276           Loops->getLoopFor(DefMBB) == Loops->getLoopFor(If))
277         KillsInElse.insert(Reg);
278     }
279   }
280 
281   auto IsLiveThroughThen = [&](Register Reg) {
282     for (auto I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end(); I != E;
283          ++I) {
284       if (!I->readsReg())
285         continue;
286       auto *UseMI = I->getParent();
287       auto *UseMBB = UseMI->getParent();
288       if (UseMBB == Flow || UseMBB == Endif) {
289         if (!UseMI->isPHI())
290           return true;
291 
292         auto *IncomingMBB = UseMI->getOperand(I.getOperandNo() + 1).getMBB();
293         // The register is live through the path If->Flow or Flow->Endif.
294         // we should not optimize for such cases.
295         if ((UseMBB == Flow && IncomingMBB != If) ||
296             (UseMBB == Endif && IncomingMBB == Flow))
297           return true;
298       }
299     }
300     return false;
301   };
302 
303   for (auto Reg : KillsInElse) {
304     if (!IsLiveThroughThen(Reg))
305       CandidateRegs.push_back(Reg);
306   }
307 }
308 
309 /// Collect the registers used in the waterfall loop block that are defined
310 /// before.
311 void SIOptimizeVGPRLiveRange::collectWaterfallCandidateRegisters(
312     MachineBasicBlock *Loop,
313     SmallSetVector<Register, 16> &CandidateRegs) const {
314 
315   for (auto &MI : Loop->instrs()) {
316     if (MI.isDebugInstr())
317       continue;
318 
319     for (auto &MO : MI.operands()) {
320       if (!MO.isReg() || !MO.getReg() || MO.isDef())
321         continue;
322 
323       Register MOReg = MO.getReg();
324       // We can only optimize AGPR/VGPR virtual register
325       if (MOReg.isPhysical() || !TRI->isVectorRegister(*MRI, MOReg))
326         continue;
327 
328       if (MO.readsReg()) {
329         const MachineBasicBlock *DefMBB = MRI->getVRegDef(MOReg)->getParent();
330         // Make sure the value is defined before the LOOP block
331         if (DefMBB != Loop && !CandidateRegs.contains(MOReg)) {
332           // If the variable is used after the loop, the register coalescer will
333           // merge the newly created register and remove the phi node again.
334           // Just do nothing in that case.
335           LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(MOReg);
336           bool IsUsed = false;
337           for (auto *Succ : Loop->successors()) {
338             if (Succ != Loop && OldVarInfo.isLiveIn(*Succ, MOReg, *MRI)) {
339               IsUsed = true;
340               break;
341             }
342           }
343           if (!IsUsed) {
344             LLVM_DEBUG(dbgs() << "Found candidate reg: "
345                               << printReg(MOReg, TRI, 0, MRI) << '\n');
346             CandidateRegs.insert(MOReg);
347           } else {
348             LLVM_DEBUG(dbgs() << "Reg is used after loop, ignoring: "
349                               << printReg(MOReg, TRI, 0, MRI) << '\n');
350           }
351         }
352       }
353     }
354   }
355 }
356 
357 // Re-calculate the liveness of \p Reg in the THEN-region
358 void SIOptimizeVGPRLiveRange::updateLiveRangeInThenRegion(
359     Register Reg, MachineBasicBlock *If, MachineBasicBlock *Flow) const {
360 
361   SmallPtrSet<MachineBasicBlock *, 16> PHIIncoming;
362 
363   MachineBasicBlock *ThenEntry = nullptr;
364   for (auto *Succ : If->successors()) {
365     if (Succ != Flow) {
366       ThenEntry = Succ;
367       break;
368     }
369   }
370   assert(ThenEntry && "No successor in Then region?");
371 
372   LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg);
373   df_iterator_default_set<MachineBasicBlock *, 16> Visited;
374 
375   for (MachineBasicBlock *MBB : depth_first_ext(ThenEntry, Visited)) {
376     if (MBB == Flow)
377       break;
378 
379     // Clear Live bit, as we will recalculate afterwards
380     LLVM_DEBUG(dbgs() << "Clear AliveBlock " << printMBBReference(*MBB)
381                       << '\n');
382     OldVarInfo.AliveBlocks.reset(MBB->getNumber());
383   }
384 
385   // Get the blocks the Reg should be alive through
386   for (auto I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end(); I != E;
387        ++I) {
388     auto *UseMI = I->getParent();
389     if (UseMI->isPHI() && I->readsReg()) {
390       if (Visited.contains(UseMI->getParent()))
391         PHIIncoming.insert(UseMI->getOperand(I.getOperandNo() + 1).getMBB());
392     }
393   }
394 
395   Visited.clear();
396 
397   for (MachineBasicBlock *MBB : depth_first_ext(ThenEntry, Visited)) {
398     if (MBB == Flow)
399       break;
400 
401     SmallVector<MachineInstr *> Uses;
402     // PHI instructions has been processed before.
403     findNonPHIUsesInBlock(Reg, MBB, Uses);
404 
405     if (Uses.size() == 1) {
406       LLVM_DEBUG(dbgs() << "Found one Non-PHI use in "
407                         << printMBBReference(*MBB) << '\n');
408       LV->HandleVirtRegUse(Reg, MBB, *(*Uses.begin()));
409     } else if (Uses.size() > 1) {
410       // Process the instructions in-order
411       LLVM_DEBUG(dbgs() << "Found " << Uses.size() << " Non-PHI uses in "
412                         << printMBBReference(*MBB) << '\n');
413       for (MachineInstr &MI : *MBB) {
414         if (llvm::is_contained(Uses, &MI))
415           LV->HandleVirtRegUse(Reg, MBB, MI);
416       }
417     }
418 
419     // Mark Reg alive through the block if this is a PHI incoming block
420     if (PHIIncoming.contains(MBB))
421       LV->MarkVirtRegAliveInBlock(OldVarInfo, MRI->getVRegDef(Reg)->getParent(),
422                                   MBB);
423   }
424 
425   // Set the isKilled flag if we get new Kills in the THEN region.
426   for (auto *MI : OldVarInfo.Kills) {
427     if (Visited.contains(MI->getParent()))
428       MI->addRegisterKilled(Reg, TRI);
429   }
430 }
431 
432 void SIOptimizeVGPRLiveRange::updateLiveRangeInElseRegion(
433     Register Reg, Register NewReg, MachineBasicBlock *Flow,
434     MachineBasicBlock *Endif,
435     SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const {
436   LiveVariables::VarInfo &NewVarInfo = LV->getVarInfo(NewReg);
437   LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg);
438 
439   // Transfer aliveBlocks from Reg to NewReg
440   for (auto *MBB : ElseBlocks) {
441     unsigned BBNum = MBB->getNumber();
442     if (OldVarInfo.AliveBlocks.test(BBNum)) {
443       NewVarInfo.AliveBlocks.set(BBNum);
444       LLVM_DEBUG(dbgs() << "Removing AliveBlock " << printMBBReference(*MBB)
445                         << '\n');
446       OldVarInfo.AliveBlocks.reset(BBNum);
447     }
448   }
449 
450   // Transfer the possible Kills in ElseBlocks from Reg to NewReg
451   auto I = OldVarInfo.Kills.begin();
452   while (I != OldVarInfo.Kills.end()) {
453     if (ElseBlocks.contains((*I)->getParent())) {
454       NewVarInfo.Kills.push_back(*I);
455       I = OldVarInfo.Kills.erase(I);
456     } else {
457       ++I;
458     }
459   }
460 }
461 
462 void SIOptimizeVGPRLiveRange::optimizeLiveRange(
463     Register Reg, MachineBasicBlock *If, MachineBasicBlock *Flow,
464     MachineBasicBlock *Endif,
465     SmallSetVector<MachineBasicBlock *, 16> &ElseBlocks) const {
466   // Insert a new PHI, marking the value from the THEN region being
467   // undef.
468   LLVM_DEBUG(dbgs() << "Optimizing " << printReg(Reg, TRI) << '\n');
469   const auto *RC = MRI->getRegClass(Reg);
470   Register NewReg = MRI->createVirtualRegister(RC);
471   Register UndefReg = MRI->createVirtualRegister(RC);
472   MachineInstrBuilder PHI = BuildMI(*Flow, Flow->getFirstNonPHI(), DebugLoc(),
473                                     TII->get(TargetOpcode::PHI), NewReg);
474   for (auto *Pred : Flow->predecessors()) {
475     if (Pred == If)
476       PHI.addReg(Reg).addMBB(Pred);
477     else
478       PHI.addReg(UndefReg, RegState::Undef).addMBB(Pred);
479   }
480 
481   // Replace all uses in the ELSE region or the PHIs in ENDIF block
482   // Use early increment range because setReg() will update the linked list.
483   for (auto &O : make_early_inc_range(MRI->use_operands(Reg))) {
484     auto *UseMI = O.getParent();
485     auto *UseBlock = UseMI->getParent();
486     // Replace uses in Endif block
487     if (UseBlock == Endif) {
488       assert(UseMI->isPHI() && "Uses should be PHI in Endif block");
489       O.setReg(NewReg);
490       continue;
491     }
492 
493     // Replace uses in Else region
494     if (ElseBlocks.contains(UseBlock))
495       O.setReg(NewReg);
496   }
497 
498   // The optimized Reg is not alive through Flow blocks anymore.
499   LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg);
500   OldVarInfo.AliveBlocks.reset(Flow->getNumber());
501 
502   updateLiveRangeInElseRegion(Reg, NewReg, Flow, Endif, ElseBlocks);
503   updateLiveRangeInThenRegion(Reg, If, Flow);
504 }
505 
506 void SIOptimizeVGPRLiveRange::optimizeWaterfallLiveRange(
507     Register Reg, MachineBasicBlock *Loop) const {
508   // Insert a new PHI, marking the value from the last loop iteration undef.
509   LLVM_DEBUG(dbgs() << "Optimizing " << printReg(Reg, TRI) << '\n');
510   const auto *RC = MRI->getRegClass(Reg);
511   Register NewReg = MRI->createVirtualRegister(RC);
512   Register UndefReg = MRI->createVirtualRegister(RC);
513 
514   // Replace all uses in the LOOP region
515   // Use early increment range because setReg() will update the linked list.
516   for (auto &O : make_early_inc_range(MRI->use_operands(Reg))) {
517     auto *UseMI = O.getParent();
518     auto *UseBlock = UseMI->getParent();
519     // Replace uses in Loop block
520     if (UseBlock == Loop)
521       O.setReg(NewReg);
522   }
523 
524   MachineInstrBuilder PHI = BuildMI(*Loop, Loop->getFirstNonPHI(), DebugLoc(),
525                                     TII->get(TargetOpcode::PHI), NewReg);
526   for (auto *Pred : Loop->predecessors()) {
527     if (Pred == Loop)
528       PHI.addReg(UndefReg, RegState::Undef).addMBB(Pred);
529     else
530       PHI.addReg(Reg).addMBB(Pred);
531   }
532 
533   LiveVariables::VarInfo &NewVarInfo = LV->getVarInfo(NewReg);
534   LiveVariables::VarInfo &OldVarInfo = LV->getVarInfo(Reg);
535 
536   // collectWaterfallCandidateRegisters only collects registers that are dead
537   // after the loop. So we know that the old reg is not live throughout the
538   // whole block anymore.
539   OldVarInfo.AliveBlocks.reset(Loop->getNumber());
540 
541   // Mark the last use as kill
542   for (auto &MI : reverse(Loop->instrs())) {
543     if (MI.readsRegister(NewReg, TRI)) {
544       MI.addRegisterKilled(NewReg, TRI);
545       NewVarInfo.Kills.push_back(&MI);
546       break;
547     }
548   }
549   assert(!NewVarInfo.Kills.empty() &&
550          "Failed to find last usage of register in loop");
551 }
552 
553 char SIOptimizeVGPRLiveRange::ID = 0;
554 
555 INITIALIZE_PASS_BEGIN(SIOptimizeVGPRLiveRange, DEBUG_TYPE,
556                       "SI Optimize VGPR LiveRange", false, false)
557 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
558 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
559 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
560 INITIALIZE_PASS_END(SIOptimizeVGPRLiveRange, DEBUG_TYPE,
561                     "SI Optimize VGPR LiveRange", false, false)
562 
563 char &llvm::SIOptimizeVGPRLiveRangeID = SIOptimizeVGPRLiveRange::ID;
564 
565 FunctionPass *llvm::createSIOptimizeVGPRLiveRangePass() {
566   return new SIOptimizeVGPRLiveRange();
567 }
568 
569 bool SIOptimizeVGPRLiveRange::runOnMachineFunction(MachineFunction &MF) {
570 
571   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
572   TII = ST.getInstrInfo();
573   TRI = &TII->getRegisterInfo();
574   MDT = &getAnalysis<MachineDominatorTree>();
575   Loops = &getAnalysis<MachineLoopInfo>();
576   LV = &getAnalysis<LiveVariables>();
577   MRI = &MF.getRegInfo();
578 
579   if (skipFunction(MF.getFunction()))
580     return false;
581 
582   bool MadeChange = false;
583 
584   // TODO: we need to think about the order of visiting the blocks to get
585   // optimal result for nesting if-else cases.
586   for (MachineBasicBlock &MBB : MF) {
587     for (auto &MI : MBB.terminators()) {
588       // Detect the if-else blocks
589       if (MI.getOpcode() == AMDGPU::SI_IF) {
590         MachineBasicBlock *IfTarget = MI.getOperand(2).getMBB();
591         auto *Endif = getElseTarget(IfTarget);
592         if (!Endif)
593           continue;
594 
595         SmallSetVector<MachineBasicBlock *, 16> ElseBlocks;
596         SmallVector<Register> CandidateRegs;
597 
598         LLVM_DEBUG(dbgs() << "Checking IF-ELSE-ENDIF: "
599                           << printMBBReference(MBB) << ' '
600                           << printMBBReference(*IfTarget) << ' '
601                           << printMBBReference(*Endif) << '\n');
602 
603         // Collect all the blocks in the ELSE region
604         collectElseRegionBlocks(IfTarget, Endif, ElseBlocks);
605 
606         // Collect the registers can be optimized
607         collectCandidateRegisters(&MBB, IfTarget, Endif, ElseBlocks,
608                                   CandidateRegs);
609         MadeChange |= !CandidateRegs.empty();
610         // Now we are safe to optimize.
611         for (auto Reg : CandidateRegs)
612           optimizeLiveRange(Reg, &MBB, IfTarget, Endif, ElseBlocks);
613       } else if (MI.getOpcode() == AMDGPU::SI_WATERFALL_LOOP) {
614         LLVM_DEBUG(dbgs() << "Checking Waterfall loop: "
615                           << printMBBReference(MBB) << '\n');
616 
617         SmallSetVector<Register, 16> CandidateRegs;
618         collectWaterfallCandidateRegisters(&MBB, CandidateRegs);
619         MadeChange |= !CandidateRegs.empty();
620         // Now we are safe to optimize.
621         for (auto Reg : CandidateRegs)
622           optimizeWaterfallLiveRange(Reg, &MBB);
623       }
624     }
625   }
626 
627   return MadeChange;
628 }
629