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