Home | History | Annotate | Download | only in CodeGen
      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/CodeGen/Passes.h"
     33 #include "llvm/Support/Debug.h"
     34 #include "llvm/Target/TargetInstrInfo.h"
     35 #include "llvm/Target/TargetMachine.h"
     36 #include "llvm/ADT/DepthFirstIterator.h"
     37 #include "llvm/ADT/SmallPtrSet.h"
     38 #include "llvm/ADT/SmallSet.h"
     39 #include "llvm/ADT/STLExtras.h"
     40 #include <algorithm>
     41 using namespace llvm;
     42 
     43 char LiveVariables::ID = 0;
     44 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
     45                 "Live Variable Analysis", false, false)
     46 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
     47 INITIALIZE_PASS_END(LiveVariables, "livevars",
     48                 "Live Variable Analysis", false, false)
     49 
     50 
     51 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
     52   AU.addRequiredID(UnreachableMachineBlockElimID);
     53   AU.setPreservesAll();
     54   MachineFunctionPass::getAnalysisUsage(AU);
     55 }
     56 
     57 MachineInstr *
     58 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
     59   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
     60     if (Kills[i]->getParent() == MBB)
     61       return Kills[i];
     62   return NULL;
     63 }
     64 
     65 void LiveVariables::VarInfo::dump() const {
     66   dbgs() << "  Alive in blocks: ";
     67   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
     68            E = AliveBlocks.end(); I != E; ++I)
     69     dbgs() << *I << ", ";
     70   dbgs() << "\n  Killed by:";
     71   if (Kills.empty())
     72     dbgs() << " No instructions.\n";
     73   else {
     74     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
     75       dbgs() << "\n    #" << i << ": " << *Kills[i];
     76     dbgs() << "\n";
     77   }
     78 }
     79 
     80 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
     81 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
     82   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
     83          "getVarInfo: not a virtual register!");
     84   VirtRegInfo.grow(RegIdx);
     85   return VirtRegInfo[RegIdx];
     86 }
     87 
     88 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
     89                                             MachineBasicBlock *DefBlock,
     90                                             MachineBasicBlock *MBB,
     91                                     std::vector<MachineBasicBlock*> &WorkList) {
     92   unsigned BBNum = MBB->getNumber();
     93 
     94   // Check to see if this basic block is one of the killing blocks.  If so,
     95   // remove it.
     96   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
     97     if (VRInfo.Kills[i]->getParent() == MBB) {
     98       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
     99       break;
    100     }
    101 
    102   if (MBB == DefBlock) return;  // Terminate recursion
    103 
    104   if (VRInfo.AliveBlocks.test(BBNum))
    105     return;  // We already know the block is live
    106 
    107   // Mark the variable known alive in this bb
    108   VRInfo.AliveBlocks.set(BBNum);
    109 
    110   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
    111 }
    112 
    113 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
    114                                             MachineBasicBlock *DefBlock,
    115                                             MachineBasicBlock *MBB) {
    116   std::vector<MachineBasicBlock*> WorkList;
    117   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
    118 
    119   while (!WorkList.empty()) {
    120     MachineBasicBlock *Pred = WorkList.back();
    121     WorkList.pop_back();
    122     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
    123   }
    124 }
    125 
    126 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
    127                                      MachineInstr *MI) {
    128   assert(MRI->getVRegDef(reg) && "Register use before def!");
    129 
    130   unsigned BBNum = MBB->getNumber();
    131 
    132   VarInfo& VRInfo = getVarInfo(reg);
    133   VRInfo.NumUses++;
    134 
    135   // Check to see if this basic block is already a kill block.
    136   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
    137     // Yes, this register is killed in this basic block already. Increase the
    138     // live range by updating the kill instruction.
    139     VRInfo.Kills.back() = MI;
    140     return;
    141   }
    142 
    143 #ifndef NDEBUG
    144   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
    145     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
    146 #endif
    147 
    148   // This situation can occur:
    149   //
    150   //     ,------.
    151   //     |      |
    152   //     |      v
    153   //     |   t2 = phi ... t1 ...
    154   //     |      |
    155   //     |      v
    156   //     |   t1 = ...
    157   //     |  ... = ... t1 ...
    158   //     |      |
    159   //     `------'
    160   //
    161   // where there is a use in a PHI node that's a predecessor to the defining
    162   // block. We don't want to mark all predecessors as having the value "alive"
    163   // in this case.
    164   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
    165 
    166   // Add a new kill entry for this basic block. If this virtual register is
    167   // already marked as alive in this basic block, that means it is alive in at
    168   // least one of the successor blocks, it's not a kill.
    169   if (!VRInfo.AliveBlocks.test(BBNum))
    170     VRInfo.Kills.push_back(MI);
    171 
    172   // Update all dominating blocks to mark them as "known live".
    173   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
    174          E = MBB->pred_end(); PI != E; ++PI)
    175     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
    176 }
    177 
    178 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
    179   VarInfo &VRInfo = getVarInfo(Reg);
    180 
    181   if (VRInfo.AliveBlocks.empty())
    182     // If vr is not alive in any block, then defaults to dead.
    183     VRInfo.Kills.push_back(MI);
    184 }
    185 
    186 /// FindLastPartialDef - Return the last partial def of the specified register.
    187 /// Also returns the sub-registers that're defined by the instruction.
    188 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
    189                                             SmallSet<unsigned,4> &PartDefRegs) {
    190   unsigned LastDefReg = 0;
    191   unsigned LastDefDist = 0;
    192   MachineInstr *LastDef = NULL;
    193   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    194        unsigned SubReg = *SubRegs; ++SubRegs) {
    195     MachineInstr *Def = PhysRegDef[SubReg];
    196     if (!Def)
    197       continue;
    198     unsigned Dist = DistanceMap[Def];
    199     if (Dist > LastDefDist) {
    200       LastDefReg  = SubReg;
    201       LastDef     = Def;
    202       LastDefDist = Dist;
    203     }
    204   }
    205 
    206   if (!LastDef)
    207     return 0;
    208 
    209   PartDefRegs.insert(LastDefReg);
    210   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
    211     MachineOperand &MO = LastDef->getOperand(i);
    212     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
    213       continue;
    214     unsigned DefReg = MO.getReg();
    215     if (TRI->isSubRegister(Reg, DefReg)) {
    216       PartDefRegs.insert(DefReg);
    217       for (const unsigned *SubRegs = TRI->getSubRegisters(DefReg);
    218            unsigned SubReg = *SubRegs; ++SubRegs)
    219         PartDefRegs.insert(SubReg);
    220     }
    221   }
    222   return LastDef;
    223 }
    224 
    225 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
    226 /// implicit defs to a machine instruction if there was an earlier def of its
    227 /// super-register.
    228 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
    229   MachineInstr *LastDef = PhysRegDef[Reg];
    230   // If there was a previous use or a "full" def all is well.
    231   if (!LastDef && !PhysRegUse[Reg]) {
    232     // Otherwise, the last sub-register def implicitly defines this register.
    233     // e.g.
    234     // AH =
    235     // AL = ... <imp-def EAX>, <imp-kill AH>
    236     //    = AH
    237     // ...
    238     //    = EAX
    239     // All of the sub-registers must have been defined before the use of Reg!
    240     SmallSet<unsigned, 4> PartDefRegs;
    241     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
    242     // If LastPartialDef is NULL, it must be using a livein register.
    243     if (LastPartialDef) {
    244       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
    245                                                            true/*IsImp*/));
    246       PhysRegDef[Reg] = LastPartialDef;
    247       SmallSet<unsigned, 8> Processed;
    248       for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    249            unsigned SubReg = *SubRegs; ++SubRegs) {
    250         if (Processed.count(SubReg))
    251           continue;
    252         if (PartDefRegs.count(SubReg))
    253           continue;
    254         // This part of Reg was defined before the last partial def. It's killed
    255         // here.
    256         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
    257                                                              false/*IsDef*/,
    258                                                              true/*IsImp*/));
    259         PhysRegDef[SubReg] = LastPartialDef;
    260         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
    261           Processed.insert(*SS);
    262       }
    263     }
    264   }
    265   else if (LastDef && !PhysRegUse[Reg] &&
    266            !LastDef->findRegisterDefOperand(Reg))
    267     // Last def defines the super register, add an implicit def of reg.
    268     LastDef->addOperand(MachineOperand::CreateReg(Reg,
    269                                                  true/*IsDef*/, true/*IsImp*/));
    270 
    271   // Remember this use.
    272   PhysRegUse[Reg]  = MI;
    273   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    274        unsigned SubReg = *SubRegs; ++SubRegs)
    275     PhysRegUse[SubReg] =  MI;
    276 }
    277 
    278 /// FindLastRefOrPartRef - Return the last reference or partial reference of
    279 /// the specified register.
    280 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
    281   MachineInstr *LastDef = PhysRegDef[Reg];
    282   MachineInstr *LastUse = PhysRegUse[Reg];
    283   if (!LastDef && !LastUse)
    284     return 0;
    285 
    286   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
    287   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
    288   unsigned LastPartDefDist = 0;
    289   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    290        unsigned SubReg = *SubRegs; ++SubRegs) {
    291     MachineInstr *Def = PhysRegDef[SubReg];
    292     if (Def && Def != LastDef) {
    293       // There was a def of this sub-register in between. This is a partial
    294       // def, keep track of the last one.
    295       unsigned Dist = DistanceMap[Def];
    296       if (Dist > LastPartDefDist)
    297         LastPartDefDist = Dist;
    298     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
    299       unsigned Dist = DistanceMap[Use];
    300       if (Dist > LastRefOrPartRefDist) {
    301         LastRefOrPartRefDist = Dist;
    302         LastRefOrPartRef = Use;
    303       }
    304     }
    305   }
    306 
    307   return LastRefOrPartRef;
    308 }
    309 
    310 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
    311   MachineInstr *LastDef = PhysRegDef[Reg];
    312   MachineInstr *LastUse = PhysRegUse[Reg];
    313   if (!LastDef && !LastUse)
    314     return false;
    315 
    316   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
    317   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
    318   // The whole register is used.
    319   // AL =
    320   // AH =
    321   //
    322   //    = AX
    323   //    = AL, AX<imp-use, kill>
    324   // AX =
    325   //
    326   // Or whole register is defined, but not used at all.
    327   // AX<dead> =
    328   // ...
    329   // AX =
    330   //
    331   // Or whole register is defined, but only partly used.
    332   // AX<dead> = AL<imp-def>
    333   //    = AL<kill>
    334   // AX =
    335   MachineInstr *LastPartDef = 0;
    336   unsigned LastPartDefDist = 0;
    337   SmallSet<unsigned, 8> PartUses;
    338   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    339        unsigned SubReg = *SubRegs; ++SubRegs) {
    340     MachineInstr *Def = PhysRegDef[SubReg];
    341     if (Def && Def != LastDef) {
    342       // There was a def of this sub-register in between. This is a partial
    343       // def, keep track of the last one.
    344       unsigned Dist = DistanceMap[Def];
    345       if (Dist > LastPartDefDist) {
    346         LastPartDefDist = Dist;
    347         LastPartDef = Def;
    348       }
    349       continue;
    350     }
    351     if (MachineInstr *Use = PhysRegUse[SubReg]) {
    352       PartUses.insert(SubReg);
    353       for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
    354         PartUses.insert(*SS);
    355       unsigned Dist = DistanceMap[Use];
    356       if (Dist > LastRefOrPartRefDist) {
    357         LastRefOrPartRefDist = Dist;
    358         LastRefOrPartRef = Use;
    359       }
    360     }
    361   }
    362 
    363   if (!PhysRegUse[Reg]) {
    364     // Partial uses. Mark register def dead and add implicit def of
    365     // sub-registers which are used.
    366     // EAX<dead>  = op  AL<imp-def>
    367     // That is, EAX def is dead but AL def extends pass it.
    368     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
    369     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    370          unsigned SubReg = *SubRegs; ++SubRegs) {
    371       if (!PartUses.count(SubReg))
    372         continue;
    373       bool NeedDef = true;
    374       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
    375         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
    376         if (MO) {
    377           NeedDef = false;
    378           assert(!MO->isDead());
    379         }
    380       }
    381       if (NeedDef)
    382         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
    383                                                  true/*IsDef*/, true/*IsImp*/));
    384       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
    385       if (LastSubRef)
    386         LastSubRef->addRegisterKilled(SubReg, TRI, true);
    387       else {
    388         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
    389         PhysRegUse[SubReg] = LastRefOrPartRef;
    390         for (const unsigned *SSRegs = TRI->getSubRegisters(SubReg);
    391              unsigned SSReg = *SSRegs; ++SSRegs)
    392           PhysRegUse[SSReg] = LastRefOrPartRef;
    393       }
    394       for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
    395         PartUses.erase(*SS);
    396     }
    397   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
    398     if (LastPartDef)
    399       // The last partial def kills the register.
    400       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
    401                                                 true/*IsImp*/, true/*IsKill*/));
    402     else {
    403       MachineOperand *MO =
    404         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
    405       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
    406       // If the last reference is the last def, then it's not used at all.
    407       // That is, unless we are currently processing the last reference itself.
    408       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
    409       if (NeedEC) {
    410         // If we are adding a subreg def and the superreg def is marked early
    411         // clobber, add an early clobber marker to the subreg def.
    412         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
    413         if (MO)
    414           MO->setIsEarlyClobber();
    415       }
    416     }
    417   } else
    418     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
    419   return true;
    420 }
    421 
    422 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
    423                                      SmallVector<unsigned, 4> &Defs) {
    424   // What parts of the register are previously defined?
    425   SmallSet<unsigned, 32> Live;
    426   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
    427     Live.insert(Reg);
    428     for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
    429       Live.insert(*SS);
    430   } else {
    431     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    432          unsigned SubReg = *SubRegs; ++SubRegs) {
    433       // If a register isn't itself defined, but all parts that make up of it
    434       // are defined, then consider it also defined.
    435       // e.g.
    436       // AL =
    437       // AH =
    438       //    = AX
    439       if (Live.count(SubReg))
    440         continue;
    441       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
    442         Live.insert(SubReg);
    443         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
    444           Live.insert(*SS);
    445       }
    446     }
    447   }
    448 
    449   // Start from the largest piece, find the last time any part of the register
    450   // is referenced.
    451   HandlePhysRegKill(Reg, MI);
    452   // Only some of the sub-registers are used.
    453   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    454        unsigned SubReg = *SubRegs; ++SubRegs) {
    455     if (!Live.count(SubReg))
    456       // Skip if this sub-register isn't defined.
    457       continue;
    458     HandlePhysRegKill(SubReg, MI);
    459   }
    460 
    461   if (MI)
    462     Defs.push_back(Reg);  // Remember this def.
    463 }
    464 
    465 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
    466                                       SmallVector<unsigned, 4> &Defs) {
    467   while (!Defs.empty()) {
    468     unsigned Reg = Defs.back();
    469     Defs.pop_back();
    470     PhysRegDef[Reg]  = MI;
    471     PhysRegUse[Reg]  = NULL;
    472     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
    473          unsigned SubReg = *SubRegs; ++SubRegs) {
    474       PhysRegDef[SubReg]  = MI;
    475       PhysRegUse[SubReg]  = NULL;
    476     }
    477   }
    478 }
    479 
    480 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
    481   MF = &mf;
    482   MRI = &mf.getRegInfo();
    483   TRI = MF->getTarget().getRegisterInfo();
    484 
    485   ReservedRegisters = TRI->getReservedRegs(mf);
    486 
    487   unsigned NumRegs = TRI->getNumRegs();
    488   PhysRegDef  = new MachineInstr*[NumRegs];
    489   PhysRegUse  = new MachineInstr*[NumRegs];
    490   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
    491   std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
    492   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
    493   PHIJoins.clear();
    494 
    495   analyzePHINodes(mf);
    496 
    497   // Calculate live variable information in depth first order on the CFG of the
    498   // function.  This guarantees that we will see the definition of a virtual
    499   // register before its uses due to dominance properties of SSA (except for PHI
    500   // nodes, which are treated as a special case).
    501   MachineBasicBlock *Entry = MF->begin();
    502   SmallPtrSet<MachineBasicBlock*,16> Visited;
    503 
    504   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
    505          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
    506        DFI != E; ++DFI) {
    507     MachineBasicBlock *MBB = *DFI;
    508 
    509     // Mark live-in registers as live-in.
    510     SmallVector<unsigned, 4> Defs;
    511     for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
    512            EE = MBB->livein_end(); II != EE; ++II) {
    513       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
    514              "Cannot have a live-in virtual register!");
    515       HandlePhysRegDef(*II, 0, Defs);
    516     }
    517 
    518     // Loop over all of the instructions, processing them.
    519     DistanceMap.clear();
    520     unsigned Dist = 0;
    521     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
    522          I != E; ++I) {
    523       MachineInstr *MI = I;
    524       if (MI->isDebugValue())
    525         continue;
    526       DistanceMap.insert(std::make_pair(MI, Dist++));
    527 
    528       // Process all of the operands of the instruction...
    529       unsigned NumOperandsToProcess = MI->getNumOperands();
    530 
    531       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
    532       // of the uses.  They will be handled in other basic blocks.
    533       if (MI->isPHI())
    534         NumOperandsToProcess = 1;
    535 
    536       // Clear kill and dead markers. LV will recompute them.
    537       SmallVector<unsigned, 4> UseRegs;
    538       SmallVector<unsigned, 4> DefRegs;
    539       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
    540         MachineOperand &MO = MI->getOperand(i);
    541         if (!MO.isReg() || MO.getReg() == 0)
    542           continue;
    543         unsigned MOReg = MO.getReg();
    544         if (MO.isUse()) {
    545           MO.setIsKill(false);
    546           UseRegs.push_back(MOReg);
    547         } else /*MO.isDef()*/ {
    548           MO.setIsDead(false);
    549           DefRegs.push_back(MOReg);
    550         }
    551       }
    552 
    553       // Process all uses.
    554       for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
    555         unsigned MOReg = UseRegs[i];
    556         if (TargetRegisterInfo::isVirtualRegister(MOReg))
    557           HandleVirtRegUse(MOReg, MBB, MI);
    558         else if (!ReservedRegisters[MOReg])
    559           HandlePhysRegUse(MOReg, MI);
    560       }
    561 
    562       // Process all defs.
    563       for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
    564         unsigned MOReg = DefRegs[i];
    565         if (TargetRegisterInfo::isVirtualRegister(MOReg))
    566           HandleVirtRegDef(MOReg, MI);
    567         else if (!ReservedRegisters[MOReg])
    568           HandlePhysRegDef(MOReg, MI, Defs);
    569       }
    570       UpdatePhysRegDefs(MI, Defs);
    571     }
    572 
    573     // Handle any virtual assignments from PHI nodes which might be at the
    574     // bottom of this basic block.  We check all of our successor blocks to see
    575     // if they have PHI nodes, and if so, we simulate an assignment at the end
    576     // of the current block.
    577     if (!PHIVarInfo[MBB->getNumber()].empty()) {
    578       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
    579 
    580       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
    581              E = VarInfoVec.end(); I != E; ++I)
    582         // Mark it alive only in the block we are representing.
    583         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
    584                                 MBB);
    585     }
    586 
    587     // Finally, if the last instruction in the block is a return, make sure to
    588     // mark it as using all of the live-out values in the function.
    589     // Things marked both call and return are tail calls; do not do this for
    590     // them.  The tail callee need not take the same registers as input
    591     // that it produces as output, and there are dependencies for its input
    592     // registers elsewhere.
    593     if (!MBB->empty() && MBB->back().getDesc().isReturn()
    594         && !MBB->back().getDesc().isCall()) {
    595       MachineInstr *Ret = &MBB->back();
    596 
    597       for (MachineRegisterInfo::liveout_iterator
    598            I = MF->getRegInfo().liveout_begin(),
    599            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
    600         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
    601                "Cannot have a live-out virtual register!");
    602         HandlePhysRegUse(*I, Ret);
    603 
    604         // Add live-out registers as implicit uses.
    605         if (!Ret->readsRegister(*I))
    606           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
    607       }
    608     }
    609 
    610     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
    611     // available at the end of the basic block.
    612     for (unsigned i = 0; i != NumRegs; ++i)
    613       if (PhysRegDef[i] || PhysRegUse[i])
    614         HandlePhysRegDef(i, 0, Defs);
    615 
    616     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
    617     std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
    618   }
    619 
    620   // Convert and transfer the dead / killed information we have gathered into
    621   // VirtRegInfo onto MI's.
    622   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
    623     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
    624     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
    625       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
    626         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
    627       else
    628         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
    629   }
    630 
    631   // Check to make sure there are no unreachable blocks in the MC CFG for the
    632   // function.  If so, it is due to a bug in the instruction selector or some
    633   // other part of the code generator if this happens.
    634 #ifndef NDEBUG
    635   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
    636     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
    637 #endif
    638 
    639   delete[] PhysRegDef;
    640   delete[] PhysRegUse;
    641   delete[] PHIVarInfo;
    642 
    643   return false;
    644 }
    645 
    646 /// replaceKillInstruction - Update register kill info by replacing a kill
    647 /// instruction with a new one.
    648 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
    649                                            MachineInstr *NewMI) {
    650   VarInfo &VI = getVarInfo(Reg);
    651   std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
    652 }
    653 
    654 /// removeVirtualRegistersKilled - Remove all killed info for the specified
    655 /// instruction.
    656 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
    657   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    658     MachineOperand &MO = MI->getOperand(i);
    659     if (MO.isReg() && MO.isKill()) {
    660       MO.setIsKill(false);
    661       unsigned Reg = MO.getReg();
    662       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
    663         bool removed = getVarInfo(Reg).removeKill(MI);
    664         assert(removed && "kill not in register's VarInfo?");
    665         (void)removed;
    666       }
    667     }
    668   }
    669 }
    670 
    671 /// analyzePHINodes - Gather information about the PHI nodes in here. In
    672 /// particular, we want to map the variable information of a virtual register
    673 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
    674 ///
    675 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
    676   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
    677        I != E; ++I)
    678     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
    679          BBI != BBE && BBI->isPHI(); ++BBI)
    680       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
    681         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
    682           .push_back(BBI->getOperand(i).getReg());
    683 }
    684 
    685 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
    686                                       unsigned Reg,
    687                                       MachineRegisterInfo &MRI) {
    688   unsigned Num = MBB.getNumber();
    689 
    690   // Reg is live-through.
    691   if (AliveBlocks.test(Num))
    692     return true;
    693 
    694   // Registers defined in MBB cannot be live in.
    695   const MachineInstr *Def = MRI.getVRegDef(Reg);
    696   if (Def && Def->getParent() == &MBB)
    697     return false;
    698 
    699  // Reg was not defined in MBB, was it killed here?
    700   return findKill(&MBB);
    701 }
    702 
    703 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
    704   LiveVariables::VarInfo &VI = getVarInfo(Reg);
    705 
    706   // Loop over all of the successors of the basic block, checking to see if
    707   // the value is either live in the block, or if it is killed in the block.
    708   SmallVector<MachineBasicBlock*, 8> OpSuccBlocks;
    709   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
    710          E = MBB.succ_end(); SI != E; ++SI) {
    711     MachineBasicBlock *SuccMBB = *SI;
    712 
    713     // Is it alive in this successor?
    714     unsigned SuccIdx = SuccMBB->getNumber();
    715     if (VI.AliveBlocks.test(SuccIdx))
    716       return true;
    717     OpSuccBlocks.push_back(SuccMBB);
    718   }
    719 
    720   // Check to see if this value is live because there is a use in a successor
    721   // that kills it.
    722   switch (OpSuccBlocks.size()) {
    723   case 1: {
    724     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
    725     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
    726       if (VI.Kills[i]->getParent() == SuccMBB)
    727         return true;
    728     break;
    729   }
    730   case 2: {
    731     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
    732     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
    733       if (VI.Kills[i]->getParent() == SuccMBB1 ||
    734           VI.Kills[i]->getParent() == SuccMBB2)
    735         return true;
    736     break;
    737   }
    738   default:
    739     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
    740     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
    741       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
    742                              VI.Kills[i]->getParent()))
    743         return true;
    744   }
    745   return false;
    746 }
    747 
    748 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
    749 /// variables that are live out of DomBB will be marked as passing live through
    750 /// BB.
    751 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
    752                                 MachineBasicBlock *DomBB,
    753                                 MachineBasicBlock *SuccBB) {
    754   const unsigned NumNew = BB->getNumber();
    755 
    756   // All registers used by PHI nodes in SuccBB must be live through BB.
    757   for (MachineBasicBlock::const_iterator BBI = SuccBB->begin(),
    758          BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI)
    759     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
    760       if (BBI->getOperand(i+1).getMBB() == BB)
    761         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
    762 
    763   // Update info for all live variables
    764   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
    765     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
    766     VarInfo &VI = getVarInfo(Reg);
    767     if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI))
    768       VI.AliveBlocks.set(NumNew);
    769   }
    770 }
    771