Fix an iterator invalidation problem. :(
[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 #include "Support/STLExtras.h"
37 using namespace llvm;
38
39 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
40
41 const std::pair<MachineBasicBlock*, unsigned> &
42 LiveVariables::getMachineBasicBlockInfo(MachineBasicBlock *MBB) const{
43   return BBMap.find(MBB->getBasicBlock())->second;
44 }
45   
46 /// getIndexMachineBasicBlock() - Given a block index, return the
47 /// MachineBasicBlock corresponding to it.
48 MachineBasicBlock *LiveVariables::getIndexMachineBasicBlock(unsigned Idx) {
49   if (BBIdxMap.empty()) {
50     BBIdxMap.resize(BBMap.size());
51     for (std::map<const BasicBlock*, std::pair<MachineBasicBlock*, unsigned> >
52            ::iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) {
53       assert(BBIdxMap.size() > I->second.second &&"Indices are not sequential");
54       assert(BBIdxMap[I->second.second] == 0 && "Multiple idx collision!");
55       BBIdxMap[I->second.second] = I->second.first;
56     }
57   }
58   assert(Idx < BBIdxMap.size() && "BB Index out of range!");
59   return BBIdxMap[Idx];
60 }
61
62 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
63   assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
64          "getVarInfo: not a virtual register!");
65   RegIdx -= MRegisterInfo::FirstVirtualRegister;
66   if (RegIdx >= VirtRegInfo.size()) {
67     if (RegIdx >= 2*VirtRegInfo.size())
68       VirtRegInfo.resize(RegIdx*2);
69     else
70       VirtRegInfo.resize(2*VirtRegInfo.size());
71   }
72   return VirtRegInfo[RegIdx];
73 }
74
75
76
77 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
78                                             const BasicBlock *BB) {
79   const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
80   MachineBasicBlock *MBB = Info.first;
81   unsigned BBNum = Info.second;
82
83   // Check to see if this basic block is one of the killing blocks.  If so,
84   // remove it...
85   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
86     if (VRInfo.Kills[i].first == MBB) {
87       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
88       break;
89     }
90
91   if (MBB == VRInfo.DefBlock) return;  // Terminate recursion
92
93   if (VRInfo.AliveBlocks.size() <= BBNum)
94     VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
95
96   if (VRInfo.AliveBlocks[BBNum])
97     return;  // We already know the block is live
98
99   // Mark the variable known alive in this bb
100   VRInfo.AliveBlocks[BBNum] = true;
101
102   for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
103     MarkVirtRegAliveInBlock(VRInfo, *PI);
104 }
105
106 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
107                                      MachineInstr *MI) {
108   // Check to see if this basic block is already a kill block...
109   if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
110     // Yes, this register is killed in this basic block already.  Increase the
111     // live range by updating the kill instruction.
112     VRInfo.Kills.back().second = MI;
113     return;
114   }
115
116 #ifndef NDEBUG
117   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
118     assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
119 #endif
120
121   assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
122
123   // Add a new kill entry for this basic block.
124   VRInfo.Kills.push_back(std::make_pair(MBB, MI));
125
126   // Update all dominating blocks to mark them known live.
127   const BasicBlock *BB = MBB->getBasicBlock();
128   for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
129        PI != E; ++PI)
130     MarkVirtRegAliveInBlock(VRInfo, *PI);
131 }
132
133 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
134   PhysRegInfo[Reg] = MI;
135   PhysRegUsed[Reg] = true;
136 }
137
138 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
139   // Does this kill a previous version of this register?
140   if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
141     if (PhysRegUsed[Reg])
142       RegistersKilled.insert(std::make_pair(LastUse, Reg));
143     else
144       RegistersDead.insert(std::make_pair(LastUse, Reg));
145   }
146   PhysRegInfo[Reg] = MI;
147   PhysRegUsed[Reg] = false;
148
149   for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
150        *AliasSet; ++AliasSet) {
151     unsigned Alias = *AliasSet;
152     if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
153       if (PhysRegUsed[Alias])
154         RegistersKilled.insert(std::make_pair(LastUse, Alias));
155       else
156         RegistersDead.insert(std::make_pair(LastUse, Alias));
157     }
158     PhysRegInfo[Alias] = MI;
159     PhysRegUsed[Alias] = false;
160   }
161 }
162
163 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
164   const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
165   RegInfo = MF.getTarget().getRegisterInfo();
166   assert(RegInfo && "Target doesn't have register information?");
167
168   // First time though, initialize AllocatablePhysicalRegisters for the target
169   if (AllocatablePhysicalRegisters.empty()) {
170     // Make space, initializing to false...
171     AllocatablePhysicalRegisters.resize(RegInfo->getNumRegs());
172
173     // Loop over all of the register classes...
174     for (MRegisterInfo::regclass_iterator RCI = RegInfo->regclass_begin(),
175            E = RegInfo->regclass_end(); RCI != E; ++RCI)
176       // Loop over all of the allocatable registers in the function...
177       for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
178              E = (*RCI)->allocation_order_end(MF); I != E; ++I)
179         AllocatablePhysicalRegisters[*I] = true;  // The reg is allocatable!
180   }
181
182   // Build BBMap... 
183   unsigned BBNum = 0;
184   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
185     BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
186
187   // PhysRegInfo - Keep track of which instruction was the last use of a
188   // physical register.  This is a purely local property, because all physical
189   // register references as presumed dead across basic blocks.
190   //
191   MachineInstr *PhysRegInfoA[RegInfo->getNumRegs()];
192   bool          PhysRegUsedA[RegInfo->getNumRegs()];
193   std::fill(PhysRegInfoA, PhysRegInfoA+RegInfo->getNumRegs(), (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 MI = Succ->begin(), ME = Succ->end();
279            MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
280         for (unsigned i = 1; ; i += 2)
281           if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
282             MachineOperand &MO = MI->getOperand(i);
283             if (!MO.getVRegValueOrNull()) {
284               VarInfo &VRInfo = getVarInfo(MO.getReg());
285
286               // Only mark it alive only in the block we are representing...
287               MarkVirtRegAliveInBlock(VRInfo, BB);
288               break;   // Found the PHI entry for this block...
289             }
290           }
291       }
292     }
293     
294     // Loop over PhysRegInfo, killing any registers that are available at the
295     // end of the basic block.  This also resets the PhysRegInfo map.
296     for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
297       if (PhysRegInfo[i])
298         HandlePhysRegDef(i, 0);
299   }
300
301   // Convert the information we have gathered into VirtRegInfo and transform it
302   // into a form usable by RegistersKilled.
303   //
304   for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
305     for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
306       if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
307         RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
308                     i + MRegisterInfo::FirstVirtualRegister));
309
310       else
311         RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
312                     i + MRegisterInfo::FirstVirtualRegister));
313     }
314   
315   return false;
316 }
317
318 /// instructionChanged - When the address of an instruction changes, this
319 /// method should be called so that live variables can update its internal
320 /// data structures.  This removes the records for OldMI, transfering them to
321 /// the records for NewMI.
322 void LiveVariables::instructionChanged(MachineInstr *OldMI,
323                                        MachineInstr *NewMI) {
324   // If the instruction defines any virtual registers, update the VarInfo for
325   // the instruction.
326   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
327     MachineOperand &MO = NewMI->getOperand(i);
328     if (MO.isRegister() && MO.isDef() &&
329         MRegisterInfo::isVirtualRegister(MO.getReg())) {
330       unsigned Reg = MO.getReg();
331       VarInfo &VI = getVarInfo(Reg);
332       if (VI.DefInst == OldMI)
333         VI.DefInst = NewMI; 
334     }
335   }
336
337   // Move the killed information over...
338   killed_iterator I, E;
339   tie(I, E) = killed_range(OldMI);
340   std::vector<unsigned> Regs;
341   for (killed_iterator A = I; A != E; ++A)
342     Regs.push_back(A->second);
343   RegistersKilled.erase(I, E);
344
345   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
346     RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
347   Regs.clear();
348
349
350   // Move the dead information over...
351   tie(I, E) = dead_range(OldMI);
352   for (killed_iterator A = I; A != E; ++A)
353     Regs.push_back(A->second);
354   RegistersDead.erase(I, E);
355
356   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
357     RegistersDead.insert(std::make_pair(NewMI, Regs[i]));
358 }