1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveVariable analysis pass. For each machine
11 // instruction in the function, this pass calculates the set of registers that
12 // are immediately dead after the instruction (i.e., the instruction calculates
13 // the value, but it is never used) and the set of registers that are used by
14 // the instruction, but are never used after the instruction (i.e., they are
17 // This class computes live variables using are sparse implementation based on
18 // the machine code SSA form. This class computes live variable information for
19 // each virtual and _register allocatable_ physical register in a function. It
20 // uses the dominance properties of SSA form to efficiently compute live
21 // variables for virtual registers, and assumes that physical registers are only
22 // live within a single basic block (allowing it to do a single local analysis
23 // to resolve physical register lifetimes in each basic block). If a physical
24 // register is not register allocatable, it is not tracked. This is useful for
25 // things like the stack pointer and condition codes.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/CodeGen/LiveVariables.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Config/alloca.h"
39 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
41 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
42 assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
43 "getVarInfo: not a virtual register!");
44 RegIdx -= MRegisterInfo::FirstVirtualRegister;
45 if (RegIdx >= VirtRegInfo.size()) {
46 if (RegIdx >= 2*VirtRegInfo.size())
47 VirtRegInfo.resize(RegIdx*2);
49 VirtRegInfo.resize(2*VirtRegInfo.size());
51 return VirtRegInfo[RegIdx];
56 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
57 MachineBasicBlock *MBB) {
58 unsigned BBNum = MBB->getNumber();
60 // Check to see if this basic block is one of the killing blocks. If so,
62 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
63 if (VRInfo.Kills[i]->getParent() == MBB) {
64 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
68 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
70 if (VRInfo.AliveBlocks.size() <= BBNum)
71 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
73 if (VRInfo.AliveBlocks[BBNum])
74 return; // We already know the block is live
76 // Mark the variable known alive in this bb
77 VRInfo.AliveBlocks[BBNum] = true;
79 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
80 E = MBB->pred_end(); PI != E; ++PI)
81 MarkVirtRegAliveInBlock(VRInfo, *PI);
84 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
86 assert(VRInfo.DefInst && "Register use before def!");
88 // Check to see if this basic block is already a kill block...
89 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
90 // Yes, this register is killed in this basic block already. Increase the
91 // live range by updating the kill instruction.
92 VRInfo.Kills.back() = MI;
97 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
98 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
101 assert(MBB != VRInfo.DefInst->getParent() &&
102 "Should have kill for defblock!");
104 // Add a new kill entry for this basic block.
105 VRInfo.Kills.push_back(MI);
107 // Update all dominating blocks to mark them known live.
108 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
109 E = MBB->pred_end(); PI != E; ++PI)
110 MarkVirtRegAliveInBlock(VRInfo, *PI);
113 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
114 PhysRegInfo[Reg] = MI;
115 PhysRegUsed[Reg] = true;
117 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
118 unsigned Alias = *AliasSet; ++AliasSet) {
119 PhysRegInfo[Alias] = MI;
120 PhysRegUsed[Alias] = true;
124 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
125 // Does this kill a previous version of this register?
126 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
127 if (PhysRegUsed[Reg])
128 RegistersKilled.insert(std::make_pair(LastUse, Reg));
130 RegistersDead.insert(std::make_pair(LastUse, Reg));
132 PhysRegInfo[Reg] = MI;
133 PhysRegUsed[Reg] = false;
135 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
136 unsigned Alias = *AliasSet; ++AliasSet) {
137 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
138 if (PhysRegUsed[Alias])
139 RegistersKilled.insert(std::make_pair(LastUse, Alias));
141 RegistersDead.insert(std::make_pair(LastUse, Alias));
143 PhysRegInfo[Alias] = MI;
144 PhysRegUsed[Alias] = false;
148 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
149 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
150 RegInfo = MF.getTarget().getRegisterInfo();
151 assert(RegInfo && "Target doesn't have register information?");
153 AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
155 // PhysRegInfo - Keep track of which instruction was the last use of a
156 // physical register. This is a purely local property, because all physical
157 // register references as presumed dead across basic blocks.
159 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
160 RegInfo->getNumRegs());
161 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
162 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
164 /// Get some space for a respectable number of registers...
165 VirtRegInfo.resize(64);
167 // Calculate live variable information in depth first order on the CFG of the
168 // function. This guarantees that we will see the definition of a virtual
169 // register before its uses due to dominance properties of SSA (except for PHI
170 // nodes, which are treated as a special case).
172 MachineBasicBlock *Entry = MF.begin();
173 std::set<MachineBasicBlock*> Visited;
174 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
175 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
176 MachineBasicBlock *MBB = *DFI;
177 unsigned BBNum = MBB->getNumber();
179 // Loop over all of the instructions, processing them.
180 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
182 MachineInstr *MI = I;
183 const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
185 // Process all of the operands of the instruction...
186 unsigned NumOperandsToProcess = MI->getNumOperands();
188 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
189 // of the uses. They will be handled in other basic blocks.
190 if (MI->getOpcode() == TargetInstrInfo::PHI)
191 NumOperandsToProcess = 1;
193 // Loop over implicit uses, using them.
194 for (const unsigned *ImplicitUses = MID.ImplicitUses;
195 *ImplicitUses; ++ImplicitUses)
196 HandlePhysRegUse(*ImplicitUses, MI);
198 // Process all explicit uses...
199 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
200 MachineOperand &MO = MI->getOperand(i);
201 if (MO.isUse() && MO.isRegister() && MO.getReg()) {
202 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
203 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
204 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
205 AllocatablePhysicalRegisters[MO.getReg()]) {
206 HandlePhysRegUse(MO.getReg(), MI);
211 // Loop over implicit defs, defining them.
212 for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
213 *ImplicitDefs; ++ImplicitDefs)
214 HandlePhysRegDef(*ImplicitDefs, MI);
216 // Process all explicit defs...
217 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
218 MachineOperand &MO = MI->getOperand(i);
219 if (MO.isDef() && MO.isRegister() && MO.getReg()) {
220 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
221 VarInfo &VRInfo = getVarInfo(MO.getReg());
223 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
226 VRInfo.Kills.push_back(MI);
227 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
228 AllocatablePhysicalRegisters[MO.getReg()]) {
229 HandlePhysRegDef(MO.getReg(), MI);
235 // Handle any virtual assignments from PHI nodes which might be at the
236 // bottom of this basic block. We check all of our successor blocks to see
237 // if they have PHI nodes, and if so, we simulate an assignment at the end
238 // of the current block.
239 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
240 E = MBB->succ_end(); SI != E; ++SI) {
241 MachineBasicBlock *Succ = *SI;
243 // PHI nodes are guaranteed to be at the top of the block...
244 for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
245 MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
246 for (unsigned i = 1; ; i += 2) {
247 assert(MI->getNumOperands() > i+1 &&
248 "Didn't find an entry for our predecessor??");
249 if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
250 MachineOperand &MO = MI->getOperand(i);
251 if (!MO.getVRegValueOrNull()) {
252 VarInfo &VRInfo = getVarInfo(MO.getReg());
254 // Only mark it alive only in the block we are representing...
255 MarkVirtRegAliveInBlock(VRInfo, MBB);
256 break; // Found the PHI entry for this block...
263 // Loop over PhysRegInfo, killing any registers that are available at the
264 // end of the basic block. This also resets the PhysRegInfo map.
265 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
267 HandlePhysRegDef(i, 0);
270 // Convert the information we have gathered into VirtRegInfo and transform it
271 // into a form usable by RegistersKilled.
273 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
274 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
275 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
276 RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j],
277 i + MRegisterInfo::FirstVirtualRegister));
280 RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j],
281 i + MRegisterInfo::FirstVirtualRegister));
284 // Check to make sure there are no unreachable blocks in the MC CFG for the
285 // function. If so, it is due to a bug in the instruction selector or some
286 // other part of the code generator if this happens.
288 for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
289 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
295 /// instructionChanged - When the address of an instruction changes, this
296 /// method should be called so that live variables can update its internal
297 /// data structures. This removes the records for OldMI, transfering them to
298 /// the records for NewMI.
299 void LiveVariables::instructionChanged(MachineInstr *OldMI,
300 MachineInstr *NewMI) {
301 // If the instruction defines any virtual registers, update the VarInfo for
303 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
304 MachineOperand &MO = OldMI->getOperand(i);
305 if (MO.isRegister() && MO.getReg() &&
306 MRegisterInfo::isVirtualRegister(MO.getReg())) {
307 unsigned Reg = MO.getReg();
308 VarInfo &VI = getVarInfo(Reg);
310 // Update the defining instruction.
311 if (VI.DefInst == OldMI)
313 } else if (MO.isUse()) {
314 // If this is a kill of the value, update the VI kills list.
315 if (VI.removeKill(OldMI))
316 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
321 // Move the killed information over...
322 killed_iterator I, E;
323 tie(I, E) = killed_range(OldMI);
324 std::vector<unsigned> Regs;
325 for (killed_iterator A = I; A != E; ++A)
326 Regs.push_back(A->second);
327 RegistersKilled.erase(I, E);
329 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
330 RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
333 // Move the dead information over...
334 tie(I, E) = dead_range(OldMI);
335 for (killed_iterator A = I; A != E; ++A)
336 Regs.push_back(A->second);
337 RegistersDead.erase(I, E);
339 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
340 RegistersDead.insert(std::make_pair(NewMI, Regs[i]));