Add a LiveVariables::VarInfo::dump method
[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/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Config/alloca.h"
37 #include <algorithm>
38 #include <iostream>
39 using namespace llvm;
40
41 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
42
43 void LiveVariables::VarInfo::dump() const {
44   std::cerr << "Register Defined by: ";
45   if (DefInst) 
46     std::cerr << *DefInst;
47   else
48     std::cerr << "<null>\n";
49   std::cerr << "  Alive in blocks: ";
50   for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
51     if (AliveBlocks[i]) std::cerr << i << ", ";
52   std::cerr << "\n  Killed by:";
53   if (Kills.empty())
54     std::cerr << " No instructions.\n";
55   else {
56     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57       std::cerr << "\n    #" << i << ": " << *Kills[i];
58     std::cerr << "\n";
59   }
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 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
76   std::map<MachineInstr*, std::vector<unsigned> >::const_iterator I = 
77   RegistersKilled.find(MI);
78   if (I == RegistersKilled.end()) return false;
79   
80   // Do a binary search, as these lists can grow pretty big, particularly for
81   // call instructions on targets with lots of call-clobbered registers.
82   return std::binary_search(I->second.begin(), I->second.end(), Reg);
83 }
84
85 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
86   std::map<MachineInstr*, std::vector<unsigned> >::const_iterator I = 
87   RegistersDead.find(MI);
88   if (I == RegistersDead.end()) return false;
89   
90   // Do a binary search, as these lists can grow pretty big, particularly for
91   // call instructions on targets with lots of call-clobbered registers.
92   return std::binary_search(I->second.begin(), I->second.end(), Reg);
93 }
94
95
96 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
97                                             MachineBasicBlock *MBB) {
98   unsigned BBNum = MBB->getNumber();
99
100   // Check to see if this basic block is one of the killing blocks.  If so,
101   // remove it...
102   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
103     if (VRInfo.Kills[i]->getParent() == MBB) {
104       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
105       break;
106     }
107
108   if (MBB == VRInfo.DefInst->getParent()) return;  // Terminate recursion
109
110   if (VRInfo.AliveBlocks.size() <= BBNum)
111     VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
112
113   if (VRInfo.AliveBlocks[BBNum])
114     return;  // We already know the block is live
115
116   // Mark the variable known alive in this bb
117   VRInfo.AliveBlocks[BBNum] = true;
118
119   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
120          E = MBB->pred_end(); PI != E; ++PI)
121     MarkVirtRegAliveInBlock(VRInfo, *PI);
122 }
123
124 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
125                                      MachineInstr *MI) {
126   assert(VRInfo.DefInst && "Register use before def!");
127
128   // Check to see if this basic block is already a kill block...
129   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
130     // Yes, this register is killed in this basic block already.  Increase the
131     // live range by updating the kill instruction.
132     VRInfo.Kills.back() = MI;
133     return;
134   }
135
136 #ifndef NDEBUG
137   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
138     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
139 #endif
140
141   assert(MBB != VRInfo.DefInst->getParent() &&
142          "Should have kill for defblock!");
143
144   // Add a new kill entry for this basic block.
145   VRInfo.Kills.push_back(MI);
146
147   // Update all dominating blocks to mark them known live.
148   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
149          E = MBB->pred_end(); PI != E; ++PI)
150     MarkVirtRegAliveInBlock(VRInfo, *PI);
151 }
152
153 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
154   PhysRegInfo[Reg] = MI;
155   PhysRegUsed[Reg] = true;
156
157   for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
158        unsigned Alias = *AliasSet; ++AliasSet) {
159     PhysRegInfo[Alias] = MI;
160     PhysRegUsed[Alias] = true;
161   }
162 }
163
164 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
165   // Does this kill a previous version of this register?
166   if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
167     if (PhysRegUsed[Reg])
168       RegistersKilled[LastUse].push_back(Reg);
169     else
170       RegistersDead[LastUse].push_back(Reg);
171   }
172   PhysRegInfo[Reg] = MI;
173   PhysRegUsed[Reg] = false;
174
175   for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
176        unsigned Alias = *AliasSet; ++AliasSet) {
177     if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
178       if (PhysRegUsed[Alias])
179         RegistersKilled[LastUse].push_back(Alias);
180       else
181         RegistersDead[LastUse].push_back(Alias);
182     }
183     PhysRegInfo[Alias] = MI;
184     PhysRegUsed[Alias] = false;
185   }
186 }
187
188 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
189   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
190   RegInfo = MF.getTarget().getRegisterInfo();
191   assert(RegInfo && "Target doesn't have register information?");
192
193   AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
194
195   // PhysRegInfo - Keep track of which instruction was the last use of a
196   // physical register.  This is a purely local property, because all physical
197   // register references as presumed dead across basic blocks.
198   //
199   PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
200                                        RegInfo->getNumRegs());
201   PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
202   std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
203
204   /// Get some space for a respectable number of registers...
205   VirtRegInfo.resize(64);
206
207   // Mark live-in registers as live-in.
208   for (MachineFunction::livein_iterator I = MF.livein_begin(),
209          E = MF.livein_end(); I != E; ++I) {
210     assert(MRegisterInfo::isPhysicalRegister(I->first) &&
211            "Cannot have a live-in virtual register!");
212     HandlePhysRegDef(I->first, 0);
213   }
214
215   // Calculate live variable information in depth first order on the CFG of the
216   // function.  This guarantees that we will see the definition of a virtual
217   // register before its uses due to dominance properties of SSA (except for PHI
218   // nodes, which are treated as a special case).
219   //
220   MachineBasicBlock *Entry = MF.begin();
221   std::set<MachineBasicBlock*> Visited;
222   for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
223          E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
224     MachineBasicBlock *MBB = *DFI;
225     unsigned BBNum = MBB->getNumber();
226
227     // Loop over all of the instructions, processing them.
228     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
229          I != E; ++I) {
230       MachineInstr *MI = I;
231       const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
232
233       // Process all of the operands of the instruction...
234       unsigned NumOperandsToProcess = MI->getNumOperands();
235
236       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
237       // of the uses.  They will be handled in other basic blocks.
238       if (MI->getOpcode() == TargetInstrInfo::PHI)
239         NumOperandsToProcess = 1;
240
241       // Loop over implicit uses, using them.
242       for (const unsigned *ImplicitUses = MID.ImplicitUses;
243            *ImplicitUses; ++ImplicitUses)
244         HandlePhysRegUse(*ImplicitUses, MI);
245
246       // Process all explicit uses...
247       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
248         MachineOperand &MO = MI->getOperand(i);
249         if (MO.isUse() && MO.isRegister() && MO.getReg()) {
250           if (MRegisterInfo::isVirtualRegister(MO.getReg())){
251             HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
252           } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
253                      AllocatablePhysicalRegisters[MO.getReg()]) {
254             HandlePhysRegUse(MO.getReg(), MI);
255           }
256         }
257       }
258
259       // Loop over implicit defs, defining them.
260       for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
261            *ImplicitDefs; ++ImplicitDefs)
262         HandlePhysRegDef(*ImplicitDefs, MI);
263
264       // Process all explicit defs...
265       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
266         MachineOperand &MO = MI->getOperand(i);
267         if (MO.isDef() && MO.isRegister() && MO.getReg()) {
268           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
269             VarInfo &VRInfo = getVarInfo(MO.getReg());
270
271             assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
272             VRInfo.DefInst = MI;
273             // Defaults to dead
274             VRInfo.Kills.push_back(MI);
275           } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
276                      AllocatablePhysicalRegisters[MO.getReg()]) {
277             HandlePhysRegDef(MO.getReg(), MI);
278           }
279         }
280       }
281     }
282
283     // Handle any virtual assignments from PHI nodes which might be at the
284     // bottom of this basic block.  We check all of our successor blocks to see
285     // if they have PHI nodes, and if so, we simulate an assignment at the end
286     // of the current block.
287     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
288            E = MBB->succ_end(); SI != E; ++SI) {
289       MachineBasicBlock *Succ = *SI;
290
291       // PHI nodes are guaranteed to be at the top of the block...
292       for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
293            MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
294         for (unsigned i = 1; ; i += 2) {
295           assert(MI->getNumOperands() > i+1 &&
296                  "Didn't find an entry for our predecessor??");
297           if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
298             MachineOperand &MO = MI->getOperand(i);
299             if (!MO.getVRegValueOrNull()) {
300               VarInfo &VRInfo = getVarInfo(MO.getReg());
301               assert(VRInfo.DefInst && "Register use before def (or no def)!");
302
303               // Only mark it alive only in the block we are representing.
304               MarkVirtRegAliveInBlock(VRInfo, MBB);
305               break;   // Found the PHI entry for this block.
306             }
307           }
308         }
309       }
310     }
311
312     // Finally, if the last block in the function is a return, make sure to mark
313     // it as using all of the live-out values in the function.
314     if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
315       MachineInstr *Ret = &MBB->back();
316       for (MachineFunction::liveout_iterator I = MF.liveout_begin(),
317              E = MF.liveout_end(); I != E; ++I) {
318         assert(MRegisterInfo::isPhysicalRegister(*I) &&
319                "Cannot have a live-in virtual register!");
320         HandlePhysRegUse(*I, Ret);
321       }
322     }
323
324     // Loop over PhysRegInfo, killing any registers that are available at the
325     // end of the basic block.  This also resets the PhysRegInfo map.
326     for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
327       if (PhysRegInfo[i])
328         HandlePhysRegDef(i, 0);
329   }
330
331   // Convert the information we have gathered into VirtRegInfo and transform it
332   // into a form usable by RegistersKilled.
333   //
334   for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
335     for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
336       if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
337         RegistersDead[VirtRegInfo[i].Kills[j]].push_back(
338                                     i + MRegisterInfo::FirstVirtualRegister);
339
340       else
341         RegistersKilled[VirtRegInfo[i].Kills[j]].push_back(
342                                     i + MRegisterInfo::FirstVirtualRegister);
343     }
344
345   // Walk through the RegistersKilled/Dead sets, and sort the registers killed
346   // or dead.  This allows us to use efficient binary search for membership
347   // testing.
348   for (std::map<MachineInstr*, std::vector<unsigned> >::iterator
349        I = RegistersKilled.begin(), E = RegistersKilled.end(); I != E; ++I)
350     std::sort(I->second.begin(), I->second.end());
351   for (std::map<MachineInstr*, std::vector<unsigned> >::iterator
352        I = RegistersDead.begin(), E = RegistersDead.end(); I != E; ++I)
353     std::sort(I->second.begin(), I->second.end());
354   
355   // Check to make sure there are no unreachable blocks in the MC CFG for the
356   // function.  If so, it is due to a bug in the instruction selector or some
357   // other part of the code generator if this happens.
358 #ifndef NDEBUG
359   for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
360     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
361 #endif
362
363   return false;
364 }
365
366 /// instructionChanged - When the address of an instruction changes, this
367 /// method should be called so that live variables can update its internal
368 /// data structures.  This removes the records for OldMI, transfering them to
369 /// the records for NewMI.
370 void LiveVariables::instructionChanged(MachineInstr *OldMI,
371                                        MachineInstr *NewMI) {
372   // If the instruction defines any virtual registers, update the VarInfo for
373   // the instruction.
374   for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
375     MachineOperand &MO = OldMI->getOperand(i);
376     if (MO.isRegister() && MO.getReg() &&
377         MRegisterInfo::isVirtualRegister(MO.getReg())) {
378       unsigned Reg = MO.getReg();
379       VarInfo &VI = getVarInfo(Reg);
380       if (MO.isDef()) {
381         // Update the defining instruction.
382         if (VI.DefInst == OldMI)
383           VI.DefInst = NewMI;
384       }
385       if (MO.isUse()) {
386         // If this is a kill of the value, update the VI kills list.
387         if (VI.removeKill(OldMI))
388           VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
389       }
390     }
391   }
392
393   // Move the killed information over...
394   killed_iterator I, E;
395   tie(I, E) = killed_range(OldMI);
396   if (I != E) {
397     std::vector<unsigned> &V = RegistersKilled[NewMI];
398     bool WasEmpty = V.empty();
399     V.insert(V.end(), I, E);
400     if (!WasEmpty)
401       std::sort(V.begin(), V.end());   // Keep the reg list sorted.
402     RegistersKilled.erase(OldMI);
403   }
404
405   // Move the dead information over...
406   tie(I, E) = dead_range(OldMI);
407   if (I != E) {
408     std::vector<unsigned> &V = RegistersDead[NewMI];
409     bool WasEmpty = V.empty();
410     V.insert(V.end(), I, E);
411     if (!WasEmpty)
412       std::sort(V.begin(), V.end());   // Keep the reg list sorted.
413     RegistersDead.erase(OldMI);
414   }
415 }