1 //===--- LivePhysRegs.cpp - Live Physical Register Set --------------------===//
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 // This file implements the LivePhysRegs utility for tracking liveness of
11 // physical registers across machine instructions in forward or backward order.
12 // A more detailed description can be found in the corresponding header file.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/LivePhysRegs.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBundle.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25 
26 
27 /// \brief Remove all registers from the set that get clobbered by the register
28 /// mask.
29 /// The clobbers set will be the list of live registers clobbered
30 /// by the regmask.
31 void LivePhysRegs::removeRegsInMask(const MachineOperand &MO,
32         SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> *Clobbers) {
33   SparseSet<unsigned>::iterator LRI = LiveRegs.begin();
34   while (LRI != LiveRegs.end()) {
35     if (MO.clobbersPhysReg(*LRI)) {
36       if (Clobbers)
37         Clobbers->push_back(std::make_pair(*LRI, &MO));
38       LRI = LiveRegs.erase(LRI);
39     } else
40       ++LRI;
41   }
42 }
43 
44 /// Remove defined registers and regmask kills from the set.
45 void LivePhysRegs::removeDefs(const MachineInstr &MI) {
46   for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
47     if (O->isReg()) {
48       if (!O->isDef() || O->isDebug())
49         continue;
50       unsigned Reg = O->getReg();
51       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
52         continue;
53       removeReg(Reg);
54     } else if (O->isRegMask())
55       removeRegsInMask(*O);
56   }
57 }
58 
59 /// Add uses to the set.
60 void LivePhysRegs::addUses(const MachineInstr &MI) {
61   for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
62     if (!O->isReg() || !O->readsReg() || O->isDebug())
63       continue;
64     unsigned Reg = O->getReg();
65     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
66       continue;
67     addReg(Reg);
68   }
69 }
70 
71 /// Simulates liveness when stepping backwards over an instruction(bundle):
72 /// Remove Defs, add uses. This is the recommended way of calculating liveness.
73 void LivePhysRegs::stepBackward(const MachineInstr &MI) {
74   // Remove defined registers and regmask kills from the set.
75   removeDefs(MI);
76 
77   // Add uses to the set.
78   addUses(MI);
79 }
80 
81 /// Simulates liveness when stepping forward over an instruction(bundle): Remove
82 /// killed-uses, add defs. This is the not recommended way, because it depends
83 /// on accurate kill flags. If possible use stepBackward() instead of this
84 /// function.
85 void LivePhysRegs::stepForward(const MachineInstr &MI,
86         SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> &Clobbers) {
87   // Remove killed registers from the set.
88   for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
89     if (O->isReg() && !O->isDebug()) {
90       unsigned Reg = O->getReg();
91       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
92         continue;
93       if (O->isDef()) {
94         // Note, dead defs are still recorded.  The caller should decide how to
95         // handle them.
96         Clobbers.push_back(std::make_pair(Reg, &*O));
97       } else {
98         if (!O->isKill())
99           continue;
100         assert(O->isUse());
101         removeReg(Reg);
102       }
103     } else if (O->isRegMask())
104       removeRegsInMask(*O, &Clobbers);
105   }
106 
107   // Add defs to the set.
108   for (auto Reg : Clobbers) {
109     // Skip dead defs.  They shouldn't be added to the set.
110     if (Reg.second->isReg() && Reg.second->isDead())
111       continue;
112     addReg(Reg.first);
113   }
114 }
115 
116 /// Prin the currently live registers to OS.
117 void LivePhysRegs::print(raw_ostream &OS) const {
118   OS << "Live Registers:";
119   if (!TRI) {
120     OS << " (uninitialized)\n";
121     return;
122   }
123 
124   if (empty()) {
125     OS << " (empty)\n";
126     return;
127   }
128 
129   for (const_iterator I = begin(), E = end(); I != E; ++I)
130     OS << " " << printReg(*I, TRI);
131   OS << "\n";
132 }
133 
134 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
135 LLVM_DUMP_METHOD void LivePhysRegs::dump() const {
136   dbgs() << "  " << *this;
137 }
138 #endif
139 
140 bool LivePhysRegs::available(const MachineRegisterInfo &MRI,
141                              unsigned Reg) const {
142   if (LiveRegs.count(Reg))
143     return false;
144   if (MRI.isReserved(Reg))
145     return false;
146   for (MCRegAliasIterator R(Reg, TRI, false); R.isValid(); ++R) {
147     if (LiveRegs.count(*R))
148       return false;
149   }
150   return true;
151 }
152 
153 /// Add live-in registers of basic block \p MBB to \p LiveRegs.
154 void LivePhysRegs::addBlockLiveIns(const MachineBasicBlock &MBB) {
155   for (const auto &LI : MBB.liveins()) {
156     unsigned Reg = LI.PhysReg;
157     LaneBitmask Mask = LI.LaneMask;
158     MCSubRegIndexIterator S(Reg, TRI);
159     assert(Mask.any() && "Invalid livein mask");
160     if (Mask.all() || !S.isValid()) {
161       addReg(Reg);
162       continue;
163     }
164     for (; S.isValid(); ++S) {
165       unsigned SI = S.getSubRegIndex();
166       if ((Mask & TRI->getSubRegIndexLaneMask(SI)).any())
167         addReg(S.getSubReg());
168     }
169   }
170 }
171 
172 /// Adds all callee saved registers to \p LiveRegs.
173 static void addCalleeSavedRegs(LivePhysRegs &LiveRegs,
174                                const MachineFunction &MF) {
175   const MachineRegisterInfo &MRI = MF.getRegInfo();
176   for (const MCPhysReg *CSR = MRI.getCalleeSavedRegs(); CSR && *CSR; ++CSR)
177     LiveRegs.addReg(*CSR);
178 }
179 
180 void LivePhysRegs::addPristines(const MachineFunction &MF) {
181   const MachineFrameInfo &MFI = MF.getFrameInfo();
182   if (!MFI.isCalleeSavedInfoValid())
183     return;
184   /// This function will usually be called on an empty object, handle this
185   /// as a special case.
186   if (empty()) {
187     /// Add all callee saved regs, then remove the ones that are saved and
188     /// restored.
189     addCalleeSavedRegs(*this, MF);
190     /// Remove the ones that are not saved/restored; they are pristine.
191     for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo())
192       removeReg(Info.getReg());
193     return;
194   }
195   /// If a callee-saved register that is not pristine is already present
196   /// in the set, we should make sure that it stays in it. Precompute the
197   /// set of pristine registers in a separate object.
198   /// Add all callee saved regs, then remove the ones that are saved+restored.
199   LivePhysRegs Pristine(*TRI);
200   addCalleeSavedRegs(Pristine, MF);
201   /// Remove the ones that are not saved/restored; they are pristine.
202   for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo())
203     Pristine.removeReg(Info.getReg());
204   for (MCPhysReg R : Pristine)
205     addReg(R);
206 }
207 
208 void LivePhysRegs::addLiveOutsNoPristines(const MachineBasicBlock &MBB) {
209   // To get the live-outs we simply merge the live-ins of all successors.
210   for (const MachineBasicBlock *Succ : MBB.successors())
211     addBlockLiveIns(*Succ);
212   if (MBB.isReturnBlock()) {
213     // Return blocks are a special case because we currently don't mark up
214     // return instructions completely: specifically, there is no explicit
215     // use for callee-saved registers. So we add all callee saved registers
216     // that are saved and restored (somewhere). This does not include
217     // callee saved registers that are unused and hence not saved and
218     // restored; they are called pristine.
219     // FIXME: PEI should add explicit markings to return instructions
220     // instead of implicitly handling them here.
221     const MachineFunction &MF = *MBB.getParent();
222     const MachineFrameInfo &MFI = MF.getFrameInfo();
223     if (MFI.isCalleeSavedInfoValid()) {
224       for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo())
225         if (Info.isRestored())
226           addReg(Info.getReg());
227     }
228   }
229 }
230 
231 void LivePhysRegs::addLiveOuts(const MachineBasicBlock &MBB) {
232   const MachineFunction &MF = *MBB.getParent();
233   addPristines(MF);
234   addLiveOutsNoPristines(MBB);
235 }
236 
237 void LivePhysRegs::addLiveIns(const MachineBasicBlock &MBB) {
238   const MachineFunction &MF = *MBB.getParent();
239   addPristines(MF);
240   addBlockLiveIns(MBB);
241 }
242 
243 void llvm::computeLiveIns(LivePhysRegs &LiveRegs,
244                           const MachineBasicBlock &MBB) {
245   const MachineFunction &MF = *MBB.getParent();
246   const MachineRegisterInfo &MRI = MF.getRegInfo();
247   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
248   LiveRegs.init(TRI);
249   LiveRegs.addLiveOutsNoPristines(MBB);
250   for (const MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend()))
251     LiveRegs.stepBackward(MI);
252 }
253 
254 void llvm::addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs) {
255   assert(MBB.livein_empty() && "Expected empty live-in list");
256   const MachineFunction &MF = *MBB.getParent();
257   const MachineRegisterInfo &MRI = MF.getRegInfo();
258   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
259   for (MCPhysReg Reg : LiveRegs) {
260     if (MRI.isReserved(Reg))
261       continue;
262     // Skip the register if we are about to add one of its super registers.
263     bool ContainsSuperReg = false;
264     for (MCSuperRegIterator SReg(Reg, &TRI); SReg.isValid(); ++SReg) {
265       if (LiveRegs.contains(*SReg) && !MRI.isReserved(*SReg)) {
266         ContainsSuperReg = true;
267         break;
268       }
269     }
270     if (ContainsSuperReg)
271       continue;
272     MBB.addLiveIn(Reg);
273   }
274 }
275 
276 void llvm::recomputeLivenessFlags(MachineBasicBlock &MBB) {
277   const MachineFunction &MF = *MBB.getParent();
278   const MachineRegisterInfo &MRI = MF.getRegInfo();
279   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
280 
281   // We walk through the block backwards and start with the live outs.
282   LivePhysRegs LiveRegs;
283   LiveRegs.init(TRI);
284   LiveRegs.addLiveOutsNoPristines(MBB);
285 
286   for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
287     // Recompute dead flags.
288     for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
289       if (!MO->isReg() || !MO->isDef() || MO->isDebug())
290         continue;
291 
292       unsigned Reg = MO->getReg();
293       if (Reg == 0)
294         continue;
295       assert(TargetRegisterInfo::isPhysicalRegister(Reg));
296 
297       bool IsNotLive = LiveRegs.available(MRI, Reg);
298       MO->setIsDead(IsNotLive);
299     }
300 
301     // Step backward over defs.
302     LiveRegs.removeDefs(MI);
303 
304     // Recompute kill flags.
305     for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
306       if (!MO->isReg() || !MO->readsReg() || MO->isDebug())
307         continue;
308 
309       unsigned Reg = MO->getReg();
310       if (Reg == 0)
311         continue;
312       assert(TargetRegisterInfo::isPhysicalRegister(Reg));
313 
314       bool IsNotLive = LiveRegs.available(MRI, Reg);
315       MO->setIsKill(IsNotLive);
316     }
317 
318     // Complete the stepbackward.
319     LiveRegs.addUses(MI);
320   }
321 }
322 
323 void llvm::computeAndAddLiveIns(LivePhysRegs &LiveRegs,
324                                 MachineBasicBlock &MBB) {
325   computeLiveIns(LiveRegs, MBB);
326   addLiveIns(MBB, LiveRegs);
327 }
328