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