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