LiveVariables.cpp revision 472405e0dc05f6fb8c09af00713ff893fff25b94
1//===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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
15// killed).
16//
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.
26//
27//===----------------------------------------------------------------------===//
28
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 "Support/DepthFirstIterator.h"
35#include "Support/STLExtras.h"
36using namespace llvm;
37
38static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
39
40LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
41  assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
42         "getVarInfo: not a virtual register!");
43  RegIdx -= MRegisterInfo::FirstVirtualRegister;
44  if (RegIdx >= VirtRegInfo.size()) {
45    if (RegIdx >= 2*VirtRegInfo.size())
46      VirtRegInfo.resize(RegIdx*2);
47    else
48      VirtRegInfo.resize(2*VirtRegInfo.size());
49  }
50  return VirtRegInfo[RegIdx];
51}
52
53
54
55void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
56                                            MachineBasicBlock *MBB) {
57  unsigned BBNum = MBB->getNumber();
58
59  // Check to see if this basic block is one of the killing blocks.  If so,
60  // remove it...
61  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
62    if (VRInfo.Kills[i].first == MBB) {
63      VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
64      break;
65    }
66
67  if (MBB == VRInfo.DefInst->getParent()) return;  // Terminate recursion
68
69  if (VRInfo.AliveBlocks.size() <= BBNum)
70    VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
71
72  if (VRInfo.AliveBlocks[BBNum])
73    return;  // We already know the block is live
74
75  // Mark the variable known alive in this bb
76  VRInfo.AliveBlocks[BBNum] = true;
77
78  for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
79         E = MBB->pred_end(); PI != E; ++PI)
80    MarkVirtRegAliveInBlock(VRInfo, *PI);
81}
82
83void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
84                                     MachineInstr *MI) {
85  // Check to see if this basic block is already a kill block...
86  if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
87    // Yes, this register is killed in this basic block already.  Increase the
88    // live range by updating the kill instruction.
89    VRInfo.Kills.back().second = MI;
90    return;
91  }
92
93#ifndef NDEBUG
94  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
95    assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
96#endif
97
98  assert(MBB != VRInfo.DefInst->getParent() &&
99         "Should have kill for defblock!");
100
101  // Add a new kill entry for this basic block.
102  VRInfo.Kills.push_back(std::make_pair(MI->getParent(), MI));
103
104  // Update all dominating blocks to mark them known live.
105  const BasicBlock *BB = MBB->getBasicBlock();
106  for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
107         E = MBB->pred_end(); PI != E; ++PI)
108    MarkVirtRegAliveInBlock(VRInfo, *PI);
109}
110
111void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
112  PhysRegInfo[Reg] = MI;
113  PhysRegUsed[Reg] = true;
114
115  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
116       unsigned Alias = *AliasSet; ++AliasSet) {
117    PhysRegInfo[Alias] = MI;
118    PhysRegUsed[Alias] = true;
119  }
120}
121
122void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
123  // Does this kill a previous version of this register?
124  if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
125    if (PhysRegUsed[Reg])
126      RegistersKilled.insert(std::make_pair(LastUse, Reg));
127    else
128      RegistersDead.insert(std::make_pair(LastUse, Reg));
129  }
130  PhysRegInfo[Reg] = MI;
131  PhysRegUsed[Reg] = false;
132
133  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
134       unsigned Alias = *AliasSet; ++AliasSet) {
135    if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
136      if (PhysRegUsed[Alias])
137        RegistersKilled.insert(std::make_pair(LastUse, Alias));
138      else
139        RegistersDead.insert(std::make_pair(LastUse, Alias));
140    }
141    PhysRegInfo[Alias] = MI;
142    PhysRegUsed[Alias] = false;
143  }
144}
145
146bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
147  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
148  RegInfo = MF.getTarget().getRegisterInfo();
149  assert(RegInfo && "Target doesn't have register information?");
150
151  // First time though, initialize AllocatablePhysicalRegisters for the target
152  if (AllocatablePhysicalRegisters.empty()) {
153    // Make space, initializing to false...
154    AllocatablePhysicalRegisters.resize(RegInfo->getNumRegs());
155
156    // Loop over all of the register classes...
157    for (MRegisterInfo::regclass_iterator RCI = RegInfo->regclass_begin(),
158           E = RegInfo->regclass_end(); RCI != E; ++RCI)
159      // Loop over all of the allocatable registers in the function...
160      for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
161             E = (*RCI)->allocation_order_end(MF); I != E; ++I)
162        AllocatablePhysicalRegisters[*I] = true;  // The reg is allocatable!
163  }
164
165  // PhysRegInfo - Keep track of which instruction was the last use of a
166  // physical register.  This is a purely local property, because all physical
167  // register references as presumed dead across basic blocks.
168  //
169  MachineInstr *PhysRegInfoA[RegInfo->getNumRegs()];
170  bool          PhysRegUsedA[RegInfo->getNumRegs()];
171  std::fill(PhysRegInfoA, PhysRegInfoA+RegInfo->getNumRegs(), (MachineInstr*)0);
172  PhysRegInfo = PhysRegInfoA;
173  PhysRegUsed = PhysRegUsedA;
174
175  /// Get some space for a respectable number of registers...
176  VirtRegInfo.resize(64);
177
178  // Calculate live variable information in depth first order on the CFG of the
179  // function.  This guarantees that we will see the definition of a virtual
180  // register before its uses due to dominance properties of SSA (except for PHI
181  // nodes, which are treated as a special case).
182  //
183  MachineBasicBlock *Entry = MF.begin();
184  std::set<MachineBasicBlock*> Visited;
185  for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
186         E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
187    MachineBasicBlock *MBB = *DFI;
188    unsigned BBNum = MBB->getNumber();
189
190    // Loop over all of the instructions, processing them.
191    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
192         I != E; ++I) {
193      MachineInstr *MI = I;
194      const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
195
196      // Process all of the operands of the instruction...
197      unsigned NumOperandsToProcess = MI->getNumOperands();
198
199      // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
200      // of the uses.  They will be handled in other basic blocks.
201      if (MI->getOpcode() == TargetInstrInfo::PHI)
202        NumOperandsToProcess = 1;
203
204      // Loop over implicit uses, using them.
205      for (const unsigned *ImplicitUses = MID.ImplicitUses;
206           *ImplicitUses; ++ImplicitUses)
207        HandlePhysRegUse(*ImplicitUses, MI);
208
209      // Process all explicit uses...
210      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
211        MachineOperand &MO = MI->getOperand(i);
212        if (MO.isUse() && MO.isRegister() && MO.getReg()) {
213          if (MRegisterInfo::isVirtualRegister(MO.getReg())){
214            HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
215          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
216                     AllocatablePhysicalRegisters[MO.getReg()]) {
217            HandlePhysRegUse(MO.getReg(), MI);
218          }
219        }
220      }
221
222      // Loop over implicit defs, defining them.
223      for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
224           *ImplicitDefs; ++ImplicitDefs)
225        HandlePhysRegDef(*ImplicitDefs, MI);
226
227      // Process all explicit defs...
228      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
229        MachineOperand &MO = MI->getOperand(i);
230        if (MO.isDef() && MO.isRegister() && MO.getReg()) {
231          if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
232            VarInfo &VRInfo = getVarInfo(MO.getReg());
233
234            assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
235            VRInfo.DefInst = MI;
236            // Defaults to dead
237            VRInfo.Kills.push_back(std::make_pair(MI->getParent(), MI));
238          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
239                     AllocatablePhysicalRegisters[MO.getReg()]) {
240            HandlePhysRegDef(MO.getReg(), MI);
241          }
242        }
243      }
244    }
245
246    // Handle any virtual assignments from PHI nodes which might be at the
247    // bottom of this basic block.  We check all of our successor blocks to see
248    // if they have PHI nodes, and if so, we simulate an assignment at the end
249    // of the current block.
250    for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
251           E = MBB->succ_end(); SI != E; ++SI) {
252      MachineBasicBlock *Succ = *SI;
253
254      // PHI nodes are guaranteed to be at the top of the block...
255      for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
256           MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
257        for (unsigned i = 1; ; i += 2) {
258          assert(MI->getNumOperands() > i+1 &&
259                 "Didn't find an entry for our predecessor??");
260          if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
261            MachineOperand &MO = MI->getOperand(i);
262            if (!MO.getVRegValueOrNull()) {
263              VarInfo &VRInfo = getVarInfo(MO.getReg());
264
265              // Only mark it alive only in the block we are representing...
266              MarkVirtRegAliveInBlock(VRInfo, MBB);
267              break;   // Found the PHI entry for this block...
268            }
269          }
270        }
271      }
272    }
273
274    // Loop over PhysRegInfo, killing any registers that are available at the
275    // end of the basic block.  This also resets the PhysRegInfo map.
276    for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
277      if (PhysRegInfo[i])
278        HandlePhysRegDef(i, 0);
279  }
280
281  // Convert the information we have gathered into VirtRegInfo and transform it
282  // into a form usable by RegistersKilled.
283  //
284  for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
285    for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
286      if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
287        RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
288                             i + MRegisterInfo::FirstVirtualRegister));
289
290      else
291        RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
292                               i + MRegisterInfo::FirstVirtualRegister));
293    }
294
295  // Check to make sure there are no unreachable blocks in the MC CFG for the
296  // function.  If so, it is due to a bug in the instruction selector or some
297  // other part of the code generator if this happens.
298#ifndef NDEBUG
299  for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
300    assert(Visited.count(&*i) != 0 && "unreachable basic block found");
301#endif
302
303  return false;
304}
305
306/// instructionChanged - When the address of an instruction changes, this
307/// method should be called so that live variables can update its internal
308/// data structures.  This removes the records for OldMI, transfering them to
309/// the records for NewMI.
310void LiveVariables::instructionChanged(MachineInstr *OldMI,
311                                       MachineInstr *NewMI) {
312  // If the instruction defines any virtual registers, update the VarInfo for
313  // the instruction.
314  for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
315    MachineOperand &MO = OldMI->getOperand(i);
316    if (MO.isRegister() && MO.isDef() && MO.getReg() &&
317        MRegisterInfo::isVirtualRegister(MO.getReg())) {
318      unsigned Reg = MO.getReg();
319      VarInfo &VI = getVarInfo(Reg);
320      if (VI.DefInst == OldMI)
321        VI.DefInst = NewMI;
322    }
323  }
324
325  // Move the killed information over...
326  killed_iterator I, E;
327  tie(I, E) = killed_range(OldMI);
328  std::vector<unsigned> Regs;
329  for (killed_iterator A = I; A != E; ++A)
330    Regs.push_back(A->second);
331  RegistersKilled.erase(I, E);
332
333  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
334    RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
335  Regs.clear();
336
337  // Move the dead information over...
338  tie(I, E) = dead_range(OldMI);
339  for (killed_iterator A = I; A != E; ++A)
340    Regs.push_back(A->second);
341  RegistersDead.erase(I, E);
342
343  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
344    RegistersDead.insert(std::make_pair(NewMI, Regs[i]));
345}
346