AMDGPU: Improve debug printing in SIFixSGPRLiveRanges
[oota-llvm.git] / lib / Target / AMDGPU / SIFixSGPRLiveRanges.cpp
1 //===-- SIFixSGPRLiveRanges.cpp - Fix SGPR live ranges ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file SALU instructions ignore the execution mask, so we need to modify the
11 /// live ranges of the registers they define in some cases.
12 ///
13 /// The main case we need to handle is when a def is used in one side of a
14 /// branch and not another.  For example:
15 ///
16 /// %def
17 /// IF
18 ///   ...
19 ///   ...
20 /// ELSE
21 ///   %use
22 ///   ...
23 /// ENDIF
24 ///
25 /// Here we need the register allocator to avoid assigning any of the defs
26 /// inside of the IF to the same register as %def.  In traditional live
27 /// interval analysis %def is not live inside the IF branch, however, since
28 /// SALU instructions inside of IF will be executed even if the branch is not
29 /// taken, there is the chance that one of the instructions will overwrite the
30 /// value of %def, so the use in ELSE will see the wrong value.
31 ///
32 /// The strategy we use for solving this is to add an extra use after the ENDIF:
33 ///
34 /// %def
35 /// IF
36 ///   ...
37 ///   ...
38 /// ELSE
39 ///   %use
40 ///   ...
41 /// ENDIF
42 /// %use
43 ///
44 /// Adding this use will make the def live throughout the IF branch, which is
45 /// what we want.
46
47 #include "AMDGPU.h"
48 #include "SIInstrInfo.h"
49 #include "SIRegisterInfo.h"
50 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
51 #include "llvm/CodeGen/LiveVariables.h"
52 #include "llvm/CodeGen/MachineFunctionPass.h"
53 #include "llvm/CodeGen/MachineInstrBuilder.h"
54 #include "llvm/CodeGen/MachinePostDominators.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
59
60 using namespace llvm;
61
62 #define DEBUG_TYPE "si-fix-sgpr-live-ranges"
63
64 namespace {
65
66 class SIFixSGPRLiveRanges : public MachineFunctionPass {
67 public:
68   static char ID;
69
70 public:
71   SIFixSGPRLiveRanges() : MachineFunctionPass(ID) {
72     initializeSIFixSGPRLiveRangesPass(*PassRegistry::getPassRegistry());
73   }
74
75   bool runOnMachineFunction(MachineFunction &MF) override;
76
77   const char *getPassName() const override {
78     return "SI Fix SGPR live ranges";
79   }
80
81   void getAnalysisUsage(AnalysisUsage &AU) const override {
82     AU.addRequired<LiveIntervals>();
83     AU.addRequired<MachinePostDominatorTree>();
84     AU.setPreservesCFG();
85
86     //AU.addPreserved<SlotIndexes>(); // XXX - This might be OK
87     AU.addPreserved<LiveIntervals>();
88
89     MachineFunctionPass::getAnalysisUsage(AU);
90   }
91 };
92
93 } // End anonymous namespace.
94
95 INITIALIZE_PASS_BEGIN(SIFixSGPRLiveRanges, DEBUG_TYPE,
96                       "SI Fix SGPR Live Ranges", false, false)
97 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
98 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
99 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
100 INITIALIZE_PASS_END(SIFixSGPRLiveRanges, DEBUG_TYPE,
101                     "SI Fix SGPR Live Ranges", false, false)
102
103 char SIFixSGPRLiveRanges::ID = 0;
104
105 char &llvm::SIFixSGPRLiveRangesID = SIFixSGPRLiveRanges::ID;
106
107 FunctionPass *llvm::createSIFixSGPRLiveRangesPass() {
108   return new SIFixSGPRLiveRanges();
109 }
110
111 bool SIFixSGPRLiveRanges::runOnMachineFunction(MachineFunction &MF) {
112   MachineRegisterInfo &MRI = MF.getRegInfo();
113   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
114   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(
115       MF.getSubtarget().getRegisterInfo());
116
117   MachinePostDominatorTree *PDT = &getAnalysis<MachinePostDominatorTree>();
118   std::vector<std::pair<unsigned, LiveRange *>> SGPRLiveRanges;
119
120   LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
121   LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
122
123   // First pass, collect all live intervals for SGPRs
124   for (const MachineBasicBlock &MBB : MF) {
125     for (const MachineInstr &MI : MBB) {
126       for (const MachineOperand &MO : MI.defs()) {
127         if (MO.isImplicit())
128           continue;
129         unsigned Def = MO.getReg();
130         if (TargetRegisterInfo::isVirtualRegister(Def)) {
131           if (TRI->isSGPRClass(MRI.getRegClass(Def))) {
132             // Only consider defs that are live outs. We don't care about def /
133             // use within the same block.
134             LiveRange &LR = LIS->getInterval(Def);
135             if (LIS->isLiveOutOfMBB(LR, &MBB))
136               SGPRLiveRanges.push_back(std::make_pair(Def, &LR));
137           }
138         } else if (TRI->isSGPRClass(TRI->getPhysRegClass(Def))) {
139             SGPRLiveRanges.push_back(
140                 std::make_pair(Def, &LIS->getRegUnit(Def)));
141         }
142       }
143     }
144   }
145
146   // Second pass fix the intervals
147   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
148                                                   BI != BE; ++BI) {
149     MachineBasicBlock &MBB = *BI;
150     if (MBB.succ_size() < 2)
151       continue;
152
153     // We have structured control flow, so the number of successors should be
154     // two.
155     assert(MBB.succ_size() == 2);
156     MachineBasicBlock *SuccA = *MBB.succ_begin();
157     MachineBasicBlock *SuccB = *(++MBB.succ_begin());
158     MachineBasicBlock *NCD = PDT->findNearestCommonDominator(SuccA, SuccB);
159
160     if (!NCD)
161       continue;
162
163     MachineBasicBlock::iterator NCDTerm = NCD->getFirstTerminator();
164
165     if (NCDTerm != NCD->end() && NCDTerm->getOpcode() == AMDGPU::SI_ELSE) {
166       assert(NCD->succ_size() == 2);
167       // We want to make sure we insert the Use after the ENDIF, not after
168       // the ELSE.
169       NCD = PDT->findNearestCommonDominator(*NCD->succ_begin(),
170                                             *(++NCD->succ_begin()));
171     }
172
173     for (std::pair<unsigned, LiveRange*> RegLR : SGPRLiveRanges) {
174       unsigned Reg = RegLR.first;
175       LiveRange *LR = RegLR.second;
176
177       // FIXME: We could be smarter here. If the register is Live-In to one
178       // block, but the other doesn't have any SGPR defs, then there won't be a
179       // conflict. Also, if the branch condition is uniform then there will be
180       // no conflict.
181       bool LiveInToA = LIS->isLiveInToMBB(*LR, SuccA);
182       bool LiveInToB = LIS->isLiveInToMBB(*LR, SuccB);
183
184       if (!LiveInToA && !LiveInToB) {
185         DEBUG(dbgs() << PrintReg(Reg, TRI, 0)
186               << " is live into neither successor\n");
187         continue;
188       }
189
190       if (LiveInToA && LiveInToB) {
191         DEBUG(dbgs() << PrintReg(Reg, TRI, 0)
192               << " is live into both successors\n");
193         continue;
194       }
195
196       // This interval is live in to one successor, but not the other, so
197       // we need to update its range so it is live in to both.
198       DEBUG(dbgs() << "Possible SGPR conflict detected for "
199             << PrintReg(Reg, TRI, 0) <<  " in " << *LR
200             << " BB#" << SuccA->getNumber() << ", BB#"
201             << SuccB->getNumber()
202             << " with NCD = BB#" << NCD->getNumber() << '\n');
203
204       assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
205              "Not expecting to extend live range of physreg");
206
207       // FIXME: Need to figure out how to update LiveRange here so this pass
208       // will be able to preserve LiveInterval analysis.
209       MachineInstr *NCDSGPRUse =
210         BuildMI(*NCD, NCD->getFirstNonPHI(), DebugLoc(),
211                 TII->get(AMDGPU::SGPR_USE))
212         .addReg(Reg, RegState::Implicit);
213
214       SlotIndex SI = LIS->InsertMachineInstrInMaps(NCDSGPRUse);
215       LIS->extendToIndices(*LR, SI.getRegSlot());
216
217       if (LV) {
218         // TODO: This won't work post-SSA
219         LV->HandleVirtRegUse(Reg, NCD, NCDSGPRUse);
220       }
221
222       DEBUG(NCDSGPRUse->dump());
223     }
224   }
225
226   return false;
227 }