809048e8ef7c634e53cdc4f258bd7d6a52d4536e
[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 is distributed under the University of Illinois Open Source
6 // 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/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/ADT/DepthFirstIterator.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Config/alloca.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 char LiveVariables::ID = 0;
43 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
44
45 void LiveVariables::VarInfo::dump() const {
46   cerr << "  Alive in blocks: ";
47   for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
48     if (AliveBlocks[i]) cerr << i << ", ";
49   cerr << "  Used in blocks: ";
50   for (unsigned i = 0, e = UsedBlocks.size(); i != e; ++i)
51     if (UsedBlocks[i]) cerr << i << ", ";
52   cerr << "\n  Killed by:";
53   if (Kills.empty())
54     cerr << " No instructions.\n";
55   else {
56     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57       cerr << "\n    #" << i << ": " << *Kills[i];
58     cerr << "\n";
59   }
60 }
61
62 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
63 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
64   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
65          "getVarInfo: not a virtual register!");
66   RegIdx -= TargetRegisterInfo::FirstVirtualRegister;
67   if (RegIdx >= VirtRegInfo.size()) {
68     if (RegIdx >= 2*VirtRegInfo.size())
69       VirtRegInfo.resize(RegIdx*2);
70     else
71       VirtRegInfo.resize(2*VirtRegInfo.size());
72   }
73   VarInfo &VI = VirtRegInfo[RegIdx];
74   VI.AliveBlocks.resize(MF->getNumBlockIDs());
75   VI.UsedBlocks.resize(MF->getNumBlockIDs());
76   return VI;
77 }
78
79 /// KillsRegister - Returns true if the machine instruction kills the specified
80 /// register.
81 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
82   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
83     const MachineOperand &MO = MI->getOperand(i);
84     if (MO.isRegister() && MO.isKill()) {
85       unsigned MOReg = MO.getReg();
86       if (MOReg == Reg ||
87           (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
88            TargetRegisterInfo::isPhysicalRegister(Reg) &&
89            RegInfo->isSubRegister(MOReg, Reg)))
90         return true;
91     }
92   }
93   return false;
94 }
95
96 /// RegisterDefIsDead - Returns true if the register is dead in this machine
97 /// instruction.
98 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
99   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
100     const MachineOperand &MO = MI->getOperand(i);
101     if (MO.isRegister() && MO.isDead()) {
102       unsigned MOReg = MO.getReg();
103       if ((MOReg == Reg) ||
104           (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
105            TargetRegisterInfo::isPhysicalRegister(Reg) &&
106            RegInfo->isSubRegister(MOReg, Reg)))
107         return true;
108     }
109   }
110   return false;
111 }
112
113 /// ModifiesRegister - Returns true if the machine instruction modifies the
114 /// register.
115 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
116   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
117     const MachineOperand &MO = MI->getOperand(i);
118     if (MO.isRegister() && MO.isDef() && MO.getReg() == Reg)
119       return true;
120   }
121   return false;
122 }
123
124 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
125                                             MachineBasicBlock *DefBlock,
126                                             MachineBasicBlock *MBB,
127                                     std::vector<MachineBasicBlock*> &WorkList) {
128   unsigned BBNum = MBB->getNumber();
129   
130   // Check to see if this basic block is one of the killing blocks.  If so,
131   // remove it.
132   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
133     if (VRInfo.Kills[i]->getParent() == MBB) {
134       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
135       break;
136     }
137   
138   if (MBB == DefBlock) return;  // Terminate recursion
139
140   if (VRInfo.AliveBlocks[BBNum])
141     return;  // We already know the block is live
142
143   // Mark the variable known alive in this bb
144   VRInfo.AliveBlocks[BBNum] = true;
145
146   for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
147          E = MBB->pred_rend(); PI != E; ++PI)
148     WorkList.push_back(*PI);
149 }
150
151 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
152                                             MachineBasicBlock *DefBlock,
153                                             MachineBasicBlock *MBB) {
154   std::vector<MachineBasicBlock*> WorkList;
155   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
156
157   while (!WorkList.empty()) {
158     MachineBasicBlock *Pred = WorkList.back();
159     WorkList.pop_back();
160     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
161   }
162 }
163
164 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
165                                      MachineInstr *MI) {
166   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
167   assert(MRI.getVRegDef(reg) && "Register use before def!");
168
169   unsigned BBNum = MBB->getNumber();
170
171   VarInfo& VRInfo = getVarInfo(reg);
172   VRInfo.UsedBlocks[BBNum] = true;
173   VRInfo.NumUses++;
174
175   // Check to see if this basic block is already a kill block.
176   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
177     // Yes, this register is killed in this basic block already. Increase the
178     // live range by updating the kill instruction.
179     VRInfo.Kills.back() = MI;
180     return;
181   }
182
183 #ifndef NDEBUG
184   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
185     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
186 #endif
187
188   assert(MBB != MRI.getVRegDef(reg)->getParent() &&
189          "Should have kill for defblock!");
190
191   // Add a new kill entry for this basic block. If this virtual register is
192   // already marked as alive in this basic block, that means it is alive in at
193   // least one of the successor blocks, it's not a kill.
194   if (!VRInfo.AliveBlocks[BBNum])
195     VRInfo.Kills.push_back(MI);
196
197   // Update all dominating blocks to mark them as "known live".
198   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
199          E = MBB->pred_end(); PI != E; ++PI)
200     MarkVirtRegAliveInBlock(VRInfo, MRI.getVRegDef(reg)->getParent(), *PI);
201 }
202
203 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
204 /// implicit defs to a machine instruction if there was an earlier def of its
205 /// super-register.
206 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
207   // Turn previous partial def's into read/mod/write.
208   for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
209     MachineInstr *Def = PhysRegPartDef[Reg][i];
210
211     // First one is just a def. This means the use is reading some undef bits.
212     if (i != 0)
213       Def->addOperand(MachineOperand::CreateReg(Reg,
214                                                 false /*IsDef*/,
215                                                 true  /*IsImp*/,
216                                                 true  /*IsKill*/));
217
218     Def->addOperand(MachineOperand::CreateReg(Reg,
219                                               true  /*IsDef*/,
220                                               true  /*IsImp*/));
221   }
222
223   PhysRegPartDef[Reg].clear();
224
225   // There was an earlier def of a super-register. Add implicit def to that MI.
226   //
227   //   A: EAX = ...
228   //   B: ... = AX
229   //
230   // Add implicit def to A.
231   if (PhysRegInfo[Reg] && PhysRegInfo[Reg] != PhysRegPartUse[Reg] &&
232       !PhysRegUsed[Reg]) {
233     MachineInstr *Def = PhysRegInfo[Reg];
234
235     if (!Def->findRegisterDefOperand(Reg))
236       Def->addOperand(MachineOperand::CreateReg(Reg,
237                                                 true  /*IsDef*/,
238                                                 true  /*IsImp*/));
239   }
240
241   // There is a now a proper use, forget about the last partial use.
242   PhysRegPartUse[Reg] = NULL;
243   PhysRegInfo[Reg] = MI;
244   PhysRegUsed[Reg] = true;
245
246   // Now reset the use information for the sub-registers.
247   for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
248        unsigned SubReg = *SubRegs; ++SubRegs) {
249     // FIXME: Should we do: "PhysRegPartUse[SubReg] = NULL;" here?
250     PhysRegInfo[SubReg] = MI;
251     PhysRegUsed[SubReg] = true;
252   }
253
254   for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
255        unsigned SuperReg = *SuperRegs; ++SuperRegs) {
256     // Remember the partial use of this super-register if it was previously
257     // defined.
258     bool HasPrevDef = PhysRegInfo[SuperReg] != NULL;
259
260     if (!HasPrevDef)
261       // FIXME: This only goes back one level of super-registers. It might miss
262       // some.
263       for (const unsigned *SSRegs = RegInfo->getSuperRegisters(SuperReg);
264            unsigned SSReg = *SSRegs; ++SSRegs)
265         if (PhysRegInfo[SSReg] != NULL) {
266           HasPrevDef = true;
267           break;
268         }
269
270     if (HasPrevDef) {
271       PhysRegInfo[SuperReg] = MI;
272       PhysRegPartUse[SuperReg] = MI;
273     }
274   }
275 }
276
277 /// addRegisterKills - For all of a register's sub-registers that are killed in
278 /// at this machine instruction, mark them as "killed". (If the machine operand
279 /// isn't found, add it first.)
280 void LiveVariables::addRegisterKills(unsigned Reg, MachineInstr *MI,
281                                      SmallSet<unsigned, 4> &SubKills) {
282   if (SubKills.count(Reg) == 0) {
283     MI->addRegisterKilled(Reg, RegInfo, true);
284     return;
285   }
286
287   for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
288        unsigned SubReg = *SubRegs; ++SubRegs)
289     addRegisterKills(SubReg, MI, SubKills);
290 }
291
292 /// HandlePhysRegKill - The recursive version of HandlePhysRegKill. Returns true
293 /// if:
294 ///
295 ///   - The register has no sub-registers and the machine instruction is the
296 ///     last def/use of the register, or
297 ///   - The register has sub-registers and none of them are killed elsewhere.
298 ///
299 /// SubKills is filled with the set of sub-registers that are killed elsewhere.
300 bool LiveVariables::HandlePhysRegKill(unsigned Reg, const MachineInstr *RefMI,
301                                       SmallSet<unsigned, 4> &SubKills) {
302   const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
303
304   for (; unsigned SubReg = *SubRegs; ++SubRegs) {
305     const MachineInstr *LastRef = PhysRegInfo[SubReg];
306
307     if (LastRef != RefMI ||
308         !HandlePhysRegKill(SubReg, RefMI, SubKills))
309       SubKills.insert(SubReg);
310   }
311
312   if (*SubRegs == 0) {
313     // No sub-registers, just check if reg is killed by RefMI.
314     if (PhysRegInfo[Reg] == RefMI)
315       return true;
316   } else if (SubKills.empty()) {
317     // None of the sub-registers are killed elsewhere.
318     return true;
319   }
320
321   return false;
322 }
323
324 /// HandlePhysRegKill - Returns true if the whole register is killed in the
325 /// machine instruction. If only some of its sub-registers are killed in this
326 /// machine instruction, then mark those as killed and return false.
327 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *RefMI) {
328   SmallSet<unsigned, 4> SubKills;
329
330   if (HandlePhysRegKill(Reg, RefMI, SubKills)) {
331     // This machine instruction kills this register.
332     RefMI->addRegisterKilled(Reg, RegInfo, true);
333     return true;
334   }
335
336   // Some sub-registers are killed by another machine instruction.
337   for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
338        unsigned SubReg = *SubRegs; ++SubRegs)
339     addRegisterKills(SubReg, RefMI, SubKills);
340
341   return false;
342 }
343
344 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
345   // Does this kill a previous version of this register?
346   if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
347     if (PhysRegUsed[Reg]) {
348       if (!HandlePhysRegKill(Reg, LastRef)) {
349         if (PhysRegPartUse[Reg])
350           PhysRegPartUse[Reg]->addRegisterKilled(Reg, RegInfo, true);
351       }
352     } else if (PhysRegPartUse[Reg]) {
353       // Add implicit use / kill to last partial use.
354       PhysRegPartUse[Reg]->addRegisterKilled(Reg, RegInfo, true);
355     } else if (LastRef != MI) {
356       // Defined, but not used. However, watch out for cases where a super-reg
357       // is also defined on the same MI.
358       LastRef->addRegisterDead(Reg, RegInfo);
359     }
360   }
361
362   for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
363        unsigned SubReg = *SubRegs; ++SubRegs) {
364     if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
365       if (PhysRegUsed[SubReg]) {
366         if (!HandlePhysRegKill(SubReg, LastRef)) {
367           if (PhysRegPartUse[SubReg])
368             PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, RegInfo, true);
369         }
370       } else if (PhysRegPartUse[SubReg]) {
371         // Add implicit use / kill to last use of a sub-register.
372         PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, RegInfo, true);
373       } else if (LastRef != MI) {
374         // This must be a def of the subreg on the same MI.
375         LastRef->addRegisterDead(SubReg, RegInfo);
376       }
377     }
378   }
379
380   if (MI) {
381     for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
382          unsigned SuperReg = *SuperRegs; ++SuperRegs) {
383       if (PhysRegInfo[SuperReg] && PhysRegInfo[SuperReg] != MI) {
384         // The larger register is previously defined. Now a smaller part is
385         // being re-defined. Treat it as read/mod/write.
386         // EAX =
387         // AX  =        EAX<imp-use,kill>, EAX<imp-def>
388         MI->addOperand(MachineOperand::CreateReg(SuperReg, false/*IsDef*/,
389                                                  true/*IsImp*/,true/*IsKill*/));
390         MI->addOperand(MachineOperand::CreateReg(SuperReg, true/*IsDef*/,
391                                                  true/*IsImp*/));
392         PhysRegInfo[SuperReg] = MI;
393         PhysRegUsed[SuperReg] = false;
394         PhysRegPartUse[SuperReg] = NULL;
395       } else {
396         // Remember this partial def.
397         PhysRegPartDef[SuperReg].push_back(MI);
398       }
399     }
400
401     PhysRegInfo[Reg] = MI;
402     PhysRegUsed[Reg] = false;
403     PhysRegPartDef[Reg].clear();
404     PhysRegPartUse[Reg] = NULL;
405
406     for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
407          unsigned SubReg = *SubRegs; ++SubRegs) {
408       PhysRegInfo[SubReg] = MI;
409       PhysRegUsed[SubReg] = false;
410       PhysRegPartDef[SubReg].clear();
411       PhysRegPartUse[SubReg] = NULL;
412     }
413   }
414 }
415
416 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
417   MF = &mf;
418   RegInfo = MF->getTarget().getRegisterInfo();
419   MachineRegisterInfo& MRI = mf.getRegInfo();
420   assert(RegInfo && "Target doesn't have register information?");
421
422   ReservedRegisters = RegInfo->getReservedRegs(mf);
423
424   unsigned NumRegs = RegInfo->getNumRegs();
425   PhysRegInfo = new MachineInstr*[NumRegs];
426   PhysRegUsed = new bool[NumRegs];
427   PhysRegPartUse = new MachineInstr*[NumRegs];
428   PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
429   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
430   std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
431   std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
432   std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
433
434   /// Get some space for a respectable number of registers.
435   VirtRegInfo.resize(64);
436
437   analyzePHINodes(mf);
438
439   // Calculate live variable information in depth first order on the CFG of the
440   // function.  This guarantees that we will see the definition of a virtual
441   // register before its uses due to dominance properties of SSA (except for PHI
442   // nodes, which are treated as a special case).
443   MachineBasicBlock *Entry = MF->begin();
444   SmallPtrSet<MachineBasicBlock*,16> Visited;
445
446   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
447          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
448        DFI != E; ++DFI) {
449     MachineBasicBlock *MBB = *DFI;
450
451     // Mark live-in registers as live-in.
452     for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
453            EE = MBB->livein_end(); II != EE; ++II) {
454       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
455              "Cannot have a live-in virtual register!");
456       HandlePhysRegDef(*II, 0);
457     }
458
459     // Loop over all of the instructions, processing them.
460     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
461          I != E; ++I) {
462       MachineInstr *MI = I;
463
464       // Process all of the operands of the instruction...
465       unsigned NumOperandsToProcess = MI->getNumOperands();
466
467       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
468       // of the uses.  They will be handled in other basic blocks.
469       if (MI->getOpcode() == TargetInstrInfo::PHI)
470         NumOperandsToProcess = 1;
471
472       // Process all uses.
473       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
474         const MachineOperand &MO = MI->getOperand(i);
475
476         if (MO.isRegister() && MO.isUse() && MO.getReg()) {
477           unsigned MOReg = MO.getReg();
478
479           if (TargetRegisterInfo::isVirtualRegister(MOReg))
480             HandleVirtRegUse(MOReg, MBB, MI);
481           else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
482                    !ReservedRegisters[MOReg])
483             HandlePhysRegUse(MOReg, MI);
484         }
485       }
486
487       // Process all defs.
488       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
489         const MachineOperand &MO = MI->getOperand(i);
490
491         if (MO.isRegister() && MO.isDef() && MO.getReg()) {
492           unsigned MOReg = MO.getReg();
493
494           if (TargetRegisterInfo::isVirtualRegister(MOReg)) {
495             VarInfo &VRInfo = getVarInfo(MOReg);
496
497             if (VRInfo.AliveBlocks.none())
498               // If vr is not alive in any block, then defaults to dead.
499               VRInfo.Kills.push_back(MI);
500           } else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
501                      !ReservedRegisters[MOReg]) {
502             HandlePhysRegDef(MOReg, MI);
503           }
504         }
505       }
506     }
507
508     // Handle any virtual assignments from PHI nodes which might be at the
509     // bottom of this basic block.  We check all of our successor blocks to see
510     // if they have PHI nodes, and if so, we simulate an assignment at the end
511     // of the current block.
512     if (!PHIVarInfo[MBB->getNumber()].empty()) {
513       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
514
515       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
516              E = VarInfoVec.end(); I != E; ++I)
517         // Mark it alive only in the block we are representing.
518         MarkVirtRegAliveInBlock(getVarInfo(*I), MRI.getVRegDef(*I)->getParent(),
519                                 MBB);
520     }
521
522     // Finally, if the last instruction in the block is a return, make sure to
523     // mark it as using all of the live-out values in the function.
524     if (!MBB->empty() && MBB->back().getDesc().isReturn()) {
525       MachineInstr *Ret = &MBB->back();
526
527       for (MachineRegisterInfo::liveout_iterator
528            I = MF->getRegInfo().liveout_begin(),
529            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
530         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
531                "Cannot have a live-in virtual register!");
532         HandlePhysRegUse(*I, Ret);
533
534         // Add live-out registers as implicit uses.
535         if (Ret->findRegisterUseOperandIdx(*I) == -1)
536           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
537       }
538     }
539
540     // Loop over PhysRegInfo, killing any registers that are available at the
541     // end of the basic block. This also resets the PhysRegInfo map.
542     for (unsigned i = 0; i != NumRegs; ++i)
543       if (PhysRegInfo[i])
544         HandlePhysRegDef(i, 0);
545
546     // Clear some states between BB's. These are purely local information.
547     for (unsigned i = 0; i != NumRegs; ++i)
548       PhysRegPartDef[i].clear();
549
550     std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
551     std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
552     std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
553   }
554
555   // Convert and transfer the dead / killed information we have gathered into
556   // VirtRegInfo onto MI's.
557   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
558     for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
559       if (VirtRegInfo[i].Kills[j] ==
560           MRI.getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
561         VirtRegInfo[i]
562           .Kills[j]->addRegisterDead(i +
563                                      TargetRegisterInfo::FirstVirtualRegister,
564                                      RegInfo);
565       else
566         VirtRegInfo[i]
567           .Kills[j]->addRegisterKilled(i +
568                                        TargetRegisterInfo::FirstVirtualRegister,
569                                        RegInfo);
570
571   // Check to make sure there are no unreachable blocks in the MC CFG for the
572   // function.  If so, it is due to a bug in the instruction selector or some
573   // other part of the code generator if this happens.
574 #ifndef NDEBUG
575   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
576     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
577 #endif
578
579   delete[] PhysRegInfo;
580   delete[] PhysRegUsed;
581   delete[] PhysRegPartUse;
582   delete[] PhysRegPartDef;
583   delete[] PHIVarInfo;
584
585   return false;
586 }
587
588 /// instructionChanged - When the address of an instruction changes, this method
589 /// should be called so that live variables can update its internal data
590 /// structures.  This removes the records for OldMI, transfering them to the
591 /// records for NewMI.
592 void LiveVariables::instructionChanged(MachineInstr *OldMI,
593                                        MachineInstr *NewMI) {
594   // If the instruction defines any virtual registers, update the VarInfo,
595   // kill and dead information for the instruction.
596   for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
597     MachineOperand &MO = OldMI->getOperand(i);
598     if (MO.isRegister() && MO.getReg() &&
599         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
600       unsigned Reg = MO.getReg();
601       VarInfo &VI = getVarInfo(Reg);
602       if (MO.isDef()) {
603         if (MO.isDead()) {
604           MO.setIsDead(false);
605           addVirtualRegisterDead(Reg, NewMI);
606         }
607       }
608       if (MO.isKill()) {
609         MO.setIsKill(false);
610         addVirtualRegisterKilled(Reg, NewMI);
611       }
612       // If this is a kill of the value, update the VI kills list.
613       if (VI.removeKill(OldMI))
614         VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
615     }
616   }
617 }
618
619 /// removeVirtualRegistersKilled - Remove all killed info for the specified
620 /// instruction.
621 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
622   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
623     MachineOperand &MO = MI->getOperand(i);
624     if (MO.isRegister() && MO.isKill()) {
625       MO.setIsKill(false);
626       unsigned Reg = MO.getReg();
627       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
628         bool removed = getVarInfo(Reg).removeKill(MI);
629         assert(removed && "kill not in register's VarInfo?");
630       }
631     }
632   }
633 }
634
635 /// removeVirtualRegistersDead - Remove all of the dead registers for the
636 /// specified instruction from the live variable information.
637 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
638   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
639     MachineOperand &MO = MI->getOperand(i);
640     if (MO.isRegister() && MO.isDead()) {
641       MO.setIsDead(false);
642       unsigned Reg = MO.getReg();
643       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
644         bool removed = getVarInfo(Reg).removeKill(MI);
645         assert(removed && "kill not in register's VarInfo?");
646       }
647     }
648   }
649 }
650
651 /// analyzePHINodes - Gather information about the PHI nodes in here. In
652 /// particular, we want to map the variable information of a virtual register
653 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
654 ///
655 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
656   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
657        I != E; ++I)
658     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
659          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
660       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
661         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
662           .push_back(BBI->getOperand(i).getReg());
663 }