xref: /llvm-project/llvm/lib/CodeGen/LiveVariables.cpp (revision b912351ec908c049b5f40eab0052602c8dff31cd)
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 /// other instructions (?), indicate that they are killed in this machine
279 /// instruction by marking the operand as "killed". (If the machine operand
280 /// isn't found, add it first.)
281 void LiveVariables::addRegisterKills(unsigned Reg, MachineInstr *MI,
282                                      SmallSet<unsigned, 4> &SubKills) {
283   if (SubKills.count(Reg) == 0) {
284     MI->addRegisterKilled(Reg, RegInfo, true);
285     return;
286   }
287 
288   for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
289        unsigned SubReg = *SubRegs; ++SubRegs)
290     addRegisterKills(SubReg, MI, SubKills);
291 }
292 
293 /// HandlePhysRegKill - The recursive version of HandlePhysRegKill. Returns true
294 /// if:
295 ///
296 ///   - The register has no sub-registers and the machine instruction is the
297 ///     last def/use of the register, or
298 ///   - The register has sub-registers and none of them are killed elsewhere.
299 ///
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 - Calls the recursive version of HandlePhysRegKill. (See
325 /// above for details.)
326 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *RefMI) {
327   SmallSet<unsigned, 4> SubKills;
328 
329   if (HandlePhysRegKill(Reg, RefMI, SubKills)) {
330     // This machine instruction kills this register.
331     RefMI->addRegisterKilled(Reg, RegInfo, true);
332     return true;
333   }
334 
335   // Some sub-registers are killed by another machine instruction.
336   for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
337        unsigned SubReg = *SubRegs; ++SubRegs)
338     addRegisterKills(SubReg, RefMI, SubKills);
339 
340   return false;
341 }
342 
343 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
344   // Does this kill a previous version of this register?
345   if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
346     if (PhysRegUsed[Reg]) {
347       if (!HandlePhysRegKill(Reg, LastRef)) {
348         if (PhysRegPartUse[Reg])
349           PhysRegPartUse[Reg]->addRegisterKilled(Reg, RegInfo, true);
350       }
351     } else if (PhysRegPartUse[Reg]) {
352       // Add implicit use / kill to last partial use.
353       PhysRegPartUse[Reg]->addRegisterKilled(Reg, RegInfo, true);
354     } else if (LastRef != MI) {
355       // Defined, but not used. However, watch out for cases where a super-reg
356       // is also defined on the same MI.
357       LastRef->addRegisterDead(Reg, RegInfo);
358     }
359   }
360 
361   for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
362        unsigned SubReg = *SubRegs; ++SubRegs) {
363     if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
364       if (PhysRegUsed[SubReg]) {
365         if (!HandlePhysRegKill(SubReg, LastRef)) {
366           if (PhysRegPartUse[SubReg])
367             PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, RegInfo, true);
368         }
369       } else if (PhysRegPartUse[SubReg]) {
370         // Add implicit use / kill to last use of a sub-register.
371         PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, RegInfo, true);
372       } else if (LastRef != MI) {
373         // This must be a def of the subreg on the same MI.
374         LastRef->addRegisterDead(SubReg, RegInfo);
375       }
376     }
377   }
378 
379   if (MI) {
380     for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
381          unsigned SuperReg = *SuperRegs; ++SuperRegs) {
382       if (PhysRegInfo[SuperReg] && PhysRegInfo[SuperReg] != MI) {
383         // The larger register is previously defined. Now a smaller part is
384         // being re-defined. Treat it as read/mod/write.
385         // EAX =
386         // AX  =        EAX<imp-use,kill>, EAX<imp-def>
387         MI->addOperand(MachineOperand::CreateReg(SuperReg, false/*IsDef*/,
388                                                  true/*IsImp*/,true/*IsKill*/));
389         MI->addOperand(MachineOperand::CreateReg(SuperReg, true/*IsDef*/,
390                                                  true/*IsImp*/));
391         PhysRegInfo[SuperReg] = MI;
392         PhysRegUsed[SuperReg] = false;
393         PhysRegPartUse[SuperReg] = NULL;
394       } else {
395         // Remember this partial def.
396         PhysRegPartDef[SuperReg].push_back(MI);
397       }
398     }
399 
400     PhysRegInfo[Reg] = MI;
401     PhysRegUsed[Reg] = false;
402     PhysRegPartDef[Reg].clear();
403     PhysRegPartUse[Reg] = NULL;
404 
405     for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
406          unsigned SubReg = *SubRegs; ++SubRegs) {
407       PhysRegInfo[SubReg] = MI;
408       PhysRegUsed[SubReg] = false;
409       PhysRegPartDef[SubReg].clear();
410       PhysRegPartUse[SubReg] = NULL;
411     }
412   }
413 }
414 
415 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
416   MF = &mf;
417   RegInfo = MF->getTarget().getRegisterInfo();
418   MachineRegisterInfo& MRI = mf.getRegInfo();
419   assert(RegInfo && "Target doesn't have register information?");
420 
421   ReservedRegisters = RegInfo->getReservedRegs(mf);
422 
423   unsigned NumRegs = RegInfo->getNumRegs();
424   PhysRegInfo = new MachineInstr*[NumRegs];
425   PhysRegUsed = new bool[NumRegs];
426   PhysRegPartUse = new MachineInstr*[NumRegs];
427   PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
428   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
429   std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
430   std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
431   std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
432 
433   /// Get some space for a respectable number of registers.
434   VirtRegInfo.resize(64);
435 
436   analyzePHINodes(mf);
437 
438   // Calculate live variable information in depth first order on the CFG of the
439   // function.  This guarantees that we will see the definition of a virtual
440   // register before its uses due to dominance properties of SSA (except for PHI
441   // nodes, which are treated as a special case).
442   MachineBasicBlock *Entry = MF->begin();
443   SmallPtrSet<MachineBasicBlock*,16> Visited;
444 
445   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
446          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
447        DFI != E; ++DFI) {
448     MachineBasicBlock *MBB = *DFI;
449 
450     // Mark live-in registers as live-in.
451     for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
452            EE = MBB->livein_end(); II != EE; ++II) {
453       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
454              "Cannot have a live-in virtual register!");
455       HandlePhysRegDef(*II, 0);
456     }
457 
458     // Loop over all of the instructions, processing them.
459     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
460          I != E; ++I) {
461       MachineInstr *MI = I;
462 
463       // Process all of the operands of the instruction...
464       unsigned NumOperandsToProcess = MI->getNumOperands();
465 
466       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
467       // of the uses.  They will be handled in other basic blocks.
468       if (MI->getOpcode() == TargetInstrInfo::PHI)
469         NumOperandsToProcess = 1;
470 
471       // Process all uses.
472       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
473         const MachineOperand &MO = MI->getOperand(i);
474 
475         if (MO.isRegister() && MO.isUse() && MO.getReg()) {
476           unsigned MOReg = MO.getReg();
477 
478           if (TargetRegisterInfo::isVirtualRegister(MOReg))
479             HandleVirtRegUse(MOReg, MBB, MI);
480           else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
481                    !ReservedRegisters[MOReg])
482             HandlePhysRegUse(MOReg, MI);
483         }
484       }
485 
486       // Process all defs.
487       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
488         const MachineOperand &MO = MI->getOperand(i);
489 
490         if (MO.isRegister() && MO.isDef() && MO.getReg()) {
491           unsigned MOReg = MO.getReg();
492 
493           if (TargetRegisterInfo::isVirtualRegister(MOReg)) {
494             VarInfo &VRInfo = getVarInfo(MOReg);
495 
496             if (VRInfo.AliveBlocks.none())
497               // If vr is not alive in any block, then defaults to dead.
498               VRInfo.Kills.push_back(MI);
499           } else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
500                      !ReservedRegisters[MOReg]) {
501             HandlePhysRegDef(MOReg, MI);
502           }
503         }
504       }
505     }
506 
507     // Handle any virtual assignments from PHI nodes which might be at the
508     // bottom of this basic block.  We check all of our successor blocks to see
509     // if they have PHI nodes, and if so, we simulate an assignment at the end
510     // of the current block.
511     if (!PHIVarInfo[MBB->getNumber()].empty()) {
512       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
513 
514       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
515              E = VarInfoVec.end(); I != E; ++I)
516         // Mark it alive only in the block we are representing.
517         MarkVirtRegAliveInBlock(getVarInfo(*I), MRI.getVRegDef(*I)->getParent(),
518                                 MBB);
519     }
520 
521     // Finally, if the last instruction in the block is a return, make sure to
522     // mark it as using all of the live-out values in the function.
523     if (!MBB->empty() && MBB->back().getDesc().isReturn()) {
524       MachineInstr *Ret = &MBB->back();
525 
526       for (MachineRegisterInfo::liveout_iterator
527            I = MF->getRegInfo().liveout_begin(),
528            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
529         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
530                "Cannot have a live-in virtual register!");
531         HandlePhysRegUse(*I, Ret);
532 
533         // Add live-out registers as implicit uses.
534         if (Ret->findRegisterUseOperandIdx(*I) == -1)
535           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
536       }
537     }
538 
539     // Loop over PhysRegInfo, killing any registers that are available at the
540     // end of the basic block. This also resets the PhysRegInfo map.
541     for (unsigned i = 0; i != NumRegs; ++i)
542       if (PhysRegInfo[i])
543         HandlePhysRegDef(i, 0);
544 
545     // Clear some states between BB's. These are purely local information.
546     for (unsigned i = 0; i != NumRegs; ++i)
547       PhysRegPartDef[i].clear();
548 
549     std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
550     std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
551     std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
552   }
553 
554   // Convert and transfer the dead / killed information we have gathered into
555   // VirtRegInfo onto MI's.
556   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
557     for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
558       if (VirtRegInfo[i].Kills[j] ==
559           MRI.getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
560         VirtRegInfo[i]
561           .Kills[j]->addRegisterDead(i +
562                                      TargetRegisterInfo::FirstVirtualRegister,
563                                      RegInfo);
564       else
565         VirtRegInfo[i]
566           .Kills[j]->addRegisterKilled(i +
567                                        TargetRegisterInfo::FirstVirtualRegister,
568                                        RegInfo);
569 
570   // Check to make sure there are no unreachable blocks in the MC CFG for the
571   // function.  If so, it is due to a bug in the instruction selector or some
572   // other part of the code generator if this happens.
573 #ifndef NDEBUG
574   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
575     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
576 #endif
577 
578   delete[] PhysRegInfo;
579   delete[] PhysRegUsed;
580   delete[] PhysRegPartUse;
581   delete[] PhysRegPartDef;
582   delete[] PHIVarInfo;
583 
584   return false;
585 }
586 
587 /// instructionChanged - When the address of an instruction changes, this method
588 /// should be called so that live variables can update its internal data
589 /// structures.  This removes the records for OldMI, transfering them to the
590 /// records for NewMI.
591 void LiveVariables::instructionChanged(MachineInstr *OldMI,
592                                        MachineInstr *NewMI) {
593   // If the instruction defines any virtual registers, update the VarInfo,
594   // kill and dead information for the instruction.
595   for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
596     MachineOperand &MO = OldMI->getOperand(i);
597     if (MO.isRegister() && MO.getReg() &&
598         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
599       unsigned Reg = MO.getReg();
600       VarInfo &VI = getVarInfo(Reg);
601       if (MO.isDef()) {
602         if (MO.isDead()) {
603           MO.setIsDead(false);
604           addVirtualRegisterDead(Reg, NewMI);
605         }
606       }
607       if (MO.isKill()) {
608         MO.setIsKill(false);
609         addVirtualRegisterKilled(Reg, NewMI);
610       }
611       // If this is a kill of the value, update the VI kills list.
612       if (VI.removeKill(OldMI))
613         VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
614     }
615   }
616 }
617 
618 /// removeVirtualRegistersKilled - Remove all killed info for the specified
619 /// instruction.
620 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
621   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
622     MachineOperand &MO = MI->getOperand(i);
623     if (MO.isRegister() && MO.isKill()) {
624       MO.setIsKill(false);
625       unsigned Reg = MO.getReg();
626       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
627         bool removed = getVarInfo(Reg).removeKill(MI);
628         assert(removed && "kill not in register's VarInfo?");
629       }
630     }
631   }
632 }
633 
634 /// removeVirtualRegistersDead - Remove all of the dead registers for the
635 /// specified instruction from the live variable information.
636 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
637   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
638     MachineOperand &MO = MI->getOperand(i);
639     if (MO.isRegister() && MO.isDead()) {
640       MO.setIsDead(false);
641       unsigned Reg = MO.getReg();
642       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
643         bool removed = getVarInfo(Reg).removeKill(MI);
644         assert(removed && "kill not in register's VarInfo?");
645       }
646     }
647   }
648 }
649 
650 /// analyzePHINodes - Gather information about the PHI nodes in here. In
651 /// particular, we want to map the variable information of a virtual register
652 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
653 ///
654 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
655   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
656        I != E; ++I)
657     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
658          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
659       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
660         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
661           .push_back(BBI->getOperand(i).getReg());
662 }
663