LLVM API Documentation

LiveVariables.cpp
Go to the documentation of this file.
00001 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LiveVariable analysis pass.  For each machine
00011 // instruction in the function, this pass calculates the set of registers that
00012 // are immediately dead after the instruction (i.e., the instruction calculates
00013 // the value, but it is never used) and the set of registers that are used by
00014 // the instruction, but are never used after the instruction (i.e., they are
00015 // killed).
00016 //
00017 // This class computes live variables using a sparse implementation based on
00018 // the machine code SSA form.  This class computes live variable information for
00019 // each virtual and _register allocatable_ physical register in a function.  It
00020 // uses the dominance properties of SSA form to efficiently compute live
00021 // variables for virtual registers, and assumes that physical registers are only
00022 // live within a single basic block (allowing it to do a single local analysis
00023 // to resolve physical register lifetimes in each basic block).  If a physical
00024 // register is not register allocatable, it is not tracked.  This is useful for
00025 // things like the stack pointer and condition codes.
00026 //
00027 //===----------------------------------------------------------------------===//
00028 
00029 #include "llvm/CodeGen/LiveVariables.h"
00030 #include "llvm/ADT/DepthFirstIterator.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include "llvm/ADT/SmallPtrSet.h"
00033 #include "llvm/ADT/SmallSet.h"
00034 #include "llvm/CodeGen/MachineInstr.h"
00035 #include "llvm/CodeGen/MachineRegisterInfo.h"
00036 #include "llvm/CodeGen/Passes.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Target/TargetInstrInfo.h"
00040 #include "llvm/Target/TargetMachine.h"
00041 #include <algorithm>
00042 using namespace llvm;
00043 
00044 char LiveVariables::ID = 0;
00045 char &llvm::LiveVariablesID = LiveVariables::ID;
00046 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
00047                 "Live Variable Analysis", false, false)
00048 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
00049 INITIALIZE_PASS_END(LiveVariables, "livevars",
00050                 "Live Variable Analysis", false, false)
00051 
00052 
00053 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
00054   AU.addRequiredID(UnreachableMachineBlockElimID);
00055   AU.setPreservesAll();
00056   MachineFunctionPass::getAnalysisUsage(AU);
00057 }
00058 
00059 MachineInstr *
00060 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
00061   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
00062     if (Kills[i]->getParent() == MBB)
00063       return Kills[i];
00064   return NULL;
00065 }
00066 
00067 void LiveVariables::VarInfo::dump() const {
00068 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00069   dbgs() << "  Alive in blocks: ";
00070   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
00071            E = AliveBlocks.end(); I != E; ++I)
00072     dbgs() << *I << ", ";
00073   dbgs() << "\n  Killed by:";
00074   if (Kills.empty())
00075     dbgs() << " No instructions.\n";
00076   else {
00077     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
00078       dbgs() << "\n    #" << i << ": " << *Kills[i];
00079     dbgs() << "\n";
00080   }
00081 #endif
00082 }
00083 
00084 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
00085 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
00086   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
00087          "getVarInfo: not a virtual register!");
00088   VirtRegInfo.grow(RegIdx);
00089   return VirtRegInfo[RegIdx];
00090 }
00091 
00092 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
00093                                             MachineBasicBlock *DefBlock,
00094                                             MachineBasicBlock *MBB,
00095                                     std::vector<MachineBasicBlock*> &WorkList) {
00096   unsigned BBNum = MBB->getNumber();
00097 
00098   // Check to see if this basic block is one of the killing blocks.  If so,
00099   // remove it.
00100   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
00101     if (VRInfo.Kills[i]->getParent() == MBB) {
00102       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
00103       break;
00104     }
00105 
00106   if (MBB == DefBlock) return;  // Terminate recursion
00107 
00108   if (VRInfo.AliveBlocks.test(BBNum))
00109     return;  // We already know the block is live
00110 
00111   // Mark the variable known alive in this bb
00112   VRInfo.AliveBlocks.set(BBNum);
00113 
00114   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
00115   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
00116 }
00117 
00118 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
00119                                             MachineBasicBlock *DefBlock,
00120                                             MachineBasicBlock *MBB) {
00121   std::vector<MachineBasicBlock*> WorkList;
00122   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
00123 
00124   while (!WorkList.empty()) {
00125     MachineBasicBlock *Pred = WorkList.back();
00126     WorkList.pop_back();
00127     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
00128   }
00129 }
00130 
00131 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
00132                                      MachineInstr *MI) {
00133   assert(MRI->getVRegDef(reg) && "Register use before def!");
00134 
00135   unsigned BBNum = MBB->getNumber();
00136 
00137   VarInfo& VRInfo = getVarInfo(reg);
00138 
00139   // Check to see if this basic block is already a kill block.
00140   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
00141     // Yes, this register is killed in this basic block already. Increase the
00142     // live range by updating the kill instruction.
00143     VRInfo.Kills.back() = MI;
00144     return;
00145   }
00146 
00147 #ifndef NDEBUG
00148   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
00149     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
00150 #endif
00151 
00152   // This situation can occur:
00153   //
00154   //     ,------.
00155   //     |      |
00156   //     |      v
00157   //     |   t2 = phi ... t1 ...
00158   //     |      |
00159   //     |      v
00160   //     |   t1 = ...
00161   //     |  ... = ... t1 ...
00162   //     |      |
00163   //     `------'
00164   //
00165   // where there is a use in a PHI node that's a predecessor to the defining
00166   // block. We don't want to mark all predecessors as having the value "alive"
00167   // in this case.
00168   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
00169 
00170   // Add a new kill entry for this basic block. If this virtual register is
00171   // already marked as alive in this basic block, that means it is alive in at
00172   // least one of the successor blocks, it's not a kill.
00173   if (!VRInfo.AliveBlocks.test(BBNum))
00174     VRInfo.Kills.push_back(MI);
00175 
00176   // Update all dominating blocks to mark them as "known live".
00177   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
00178          E = MBB->pred_end(); PI != E; ++PI)
00179     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
00180 }
00181 
00182 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
00183   VarInfo &VRInfo = getVarInfo(Reg);
00184 
00185   if (VRInfo.AliveBlocks.empty())
00186     // If vr is not alive in any block, then defaults to dead.
00187     VRInfo.Kills.push_back(MI);
00188 }
00189 
00190 /// FindLastPartialDef - Return the last partial def of the specified register.
00191 /// Also returns the sub-registers that're defined by the instruction.
00192 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
00193                                             SmallSet<unsigned,4> &PartDefRegs) {
00194   unsigned LastDefReg = 0;
00195   unsigned LastDefDist = 0;
00196   MachineInstr *LastDef = NULL;
00197   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00198     unsigned SubReg = *SubRegs;
00199     MachineInstr *Def = PhysRegDef[SubReg];
00200     if (!Def)
00201       continue;
00202     unsigned Dist = DistanceMap[Def];
00203     if (Dist > LastDefDist) {
00204       LastDefReg  = SubReg;
00205       LastDef     = Def;
00206       LastDefDist = Dist;
00207     }
00208   }
00209 
00210   if (!LastDef)
00211     return 0;
00212 
00213   PartDefRegs.insert(LastDefReg);
00214   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
00215     MachineOperand &MO = LastDef->getOperand(i);
00216     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
00217       continue;
00218     unsigned DefReg = MO.getReg();
00219     if (TRI->isSubRegister(Reg, DefReg)) {
00220       for (MCSubRegIterator SubRegs(DefReg, TRI, /*IncludeSelf=*/true);
00221            SubRegs.isValid(); ++SubRegs)
00222         PartDefRegs.insert(*SubRegs);
00223     }
00224   }
00225   return LastDef;
00226 }
00227 
00228 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
00229 /// implicit defs to a machine instruction if there was an earlier def of its
00230 /// super-register.
00231 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
00232   MachineInstr *LastDef = PhysRegDef[Reg];
00233   // If there was a previous use or a "full" def all is well.
00234   if (!LastDef && !PhysRegUse[Reg]) {
00235     // Otherwise, the last sub-register def implicitly defines this register.
00236     // e.g.
00237     // AH =
00238     // AL = ... <imp-def EAX>, <imp-kill AH>
00239     //    = AH
00240     // ...
00241     //    = EAX
00242     // All of the sub-registers must have been defined before the use of Reg!
00243     SmallSet<unsigned, 4> PartDefRegs;
00244     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
00245     // If LastPartialDef is NULL, it must be using a livein register.
00246     if (LastPartialDef) {
00247       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
00248                                                            true/*IsImp*/));
00249       PhysRegDef[Reg] = LastPartialDef;
00250       SmallSet<unsigned, 8> Processed;
00251       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00252         unsigned SubReg = *SubRegs;
00253         if (Processed.count(SubReg))
00254           continue;
00255         if (PartDefRegs.count(SubReg))
00256           continue;
00257         // This part of Reg was defined before the last partial def. It's killed
00258         // here.
00259         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
00260                                                              false/*IsDef*/,
00261                                                              true/*IsImp*/));
00262         PhysRegDef[SubReg] = LastPartialDef;
00263         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
00264           Processed.insert(*SS);
00265       }
00266     }
00267   } else if (LastDef && !PhysRegUse[Reg] &&
00268              !LastDef->findRegisterDefOperand(Reg))
00269     // Last def defines the super register, add an implicit def of reg.
00270     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
00271                                                   true/*IsImp*/));
00272 
00273   // Remember this use.
00274   for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00275        SubRegs.isValid(); ++SubRegs)
00276     PhysRegUse[*SubRegs] =  MI;
00277 }
00278 
00279 /// FindLastRefOrPartRef - Return the last reference or partial reference of
00280 /// the specified register.
00281 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
00282   MachineInstr *LastDef = PhysRegDef[Reg];
00283   MachineInstr *LastUse = PhysRegUse[Reg];
00284   if (!LastDef && !LastUse)
00285     return 0;
00286 
00287   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
00288   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
00289   unsigned LastPartDefDist = 0;
00290   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00291     unsigned SubReg = *SubRegs;
00292     MachineInstr *Def = PhysRegDef[SubReg];
00293     if (Def && Def != LastDef) {
00294       // There was a def of this sub-register in between. This is a partial
00295       // def, keep track of the last one.
00296       unsigned Dist = DistanceMap[Def];
00297       if (Dist > LastPartDefDist)
00298         LastPartDefDist = Dist;
00299     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
00300       unsigned Dist = DistanceMap[Use];
00301       if (Dist > LastRefOrPartRefDist) {
00302         LastRefOrPartRefDist = Dist;
00303         LastRefOrPartRef = Use;
00304       }
00305     }
00306   }
00307 
00308   return LastRefOrPartRef;
00309 }
00310 
00311 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
00312   MachineInstr *LastDef = PhysRegDef[Reg];
00313   MachineInstr *LastUse = PhysRegUse[Reg];
00314   if (!LastDef && !LastUse)
00315     return false;
00316 
00317   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
00318   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
00319   // The whole register is used.
00320   // AL =
00321   // AH =
00322   //
00323   //    = AX
00324   //    = AL, AX<imp-use, kill>
00325   // AX =
00326   //
00327   // Or whole register is defined, but not used at all.
00328   // AX<dead> =
00329   // ...
00330   // AX =
00331   //
00332   // Or whole register is defined, but only partly used.
00333   // AX<dead> = AL<imp-def>
00334   //    = AL<kill>
00335   // AX =
00336   MachineInstr *LastPartDef = 0;
00337   unsigned LastPartDefDist = 0;
00338   SmallSet<unsigned, 8> PartUses;
00339   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00340     unsigned SubReg = *SubRegs;
00341     MachineInstr *Def = PhysRegDef[SubReg];
00342     if (Def && Def != LastDef) {
00343       // There was a def of this sub-register in between. This is a partial
00344       // def, keep track of the last one.
00345       unsigned Dist = DistanceMap[Def];
00346       if (Dist > LastPartDefDist) {
00347         LastPartDefDist = Dist;
00348         LastPartDef = Def;
00349       }
00350       continue;
00351     }
00352     if (MachineInstr *Use = PhysRegUse[SubReg]) {
00353       for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true); SS.isValid();
00354            ++SS)
00355         PartUses.insert(*SS);
00356       unsigned Dist = DistanceMap[Use];
00357       if (Dist > LastRefOrPartRefDist) {
00358         LastRefOrPartRefDist = Dist;
00359         LastRefOrPartRef = Use;
00360       }
00361     }
00362   }
00363 
00364   if (!PhysRegUse[Reg]) {
00365     // Partial uses. Mark register def dead and add implicit def of
00366     // sub-registers which are used.
00367     // EAX<dead>  = op  AL<imp-def>
00368     // That is, EAX def is dead but AL def extends pass it.
00369     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
00370     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00371       unsigned SubReg = *SubRegs;
00372       if (!PartUses.count(SubReg))
00373         continue;
00374       bool NeedDef = true;
00375       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
00376         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
00377         if (MO) {
00378           NeedDef = false;
00379           assert(!MO->isDead());
00380         }
00381       }
00382       if (NeedDef)
00383         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
00384                                                  true/*IsDef*/, true/*IsImp*/));
00385       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
00386       if (LastSubRef)
00387         LastSubRef->addRegisterKilled(SubReg, TRI, true);
00388       else {
00389         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
00390         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
00391              SS.isValid(); ++SS)
00392           PhysRegUse[*SS] = LastRefOrPartRef;
00393       }
00394       for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
00395         PartUses.erase(*SS);
00396     }
00397   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
00398     if (LastPartDef)
00399       // The last partial def kills the register.
00400       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
00401                                                 true/*IsImp*/, true/*IsKill*/));
00402     else {
00403       MachineOperand *MO =
00404         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
00405       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
00406       // If the last reference is the last def, then it's not used at all.
00407       // That is, unless we are currently processing the last reference itself.
00408       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
00409       if (NeedEC) {
00410         // If we are adding a subreg def and the superreg def is marked early
00411         // clobber, add an early clobber marker to the subreg def.
00412         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
00413         if (MO)
00414           MO->setIsEarlyClobber();
00415       }
00416     }
00417   } else
00418     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
00419   return true;
00420 }
00421 
00422 void LiveVariables::HandleRegMask(const MachineOperand &MO) {
00423   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
00424   // Clobbered registers are always dead, sp there is no need to use
00425   // HandlePhysRegDef().
00426   for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
00427     // Skip dead regs.
00428     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
00429       continue;
00430     // Skip mask-preserved regs.
00431     if (!MO.clobbersPhysReg(Reg))
00432       continue;
00433     // Kill the largest clobbered super-register.
00434     // This avoids needless implicit operands.
00435     unsigned Super = Reg;
00436     for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
00437       if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
00438         Super = *SR;
00439     HandlePhysRegKill(Super, 0);
00440   }
00441 }
00442 
00443 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
00444                                      SmallVector<unsigned, 4> &Defs) {
00445   // What parts of the register are previously defined?
00446   SmallSet<unsigned, 32> Live;
00447   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
00448     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00449          SubRegs.isValid(); ++SubRegs)
00450       Live.insert(*SubRegs);
00451   } else {
00452     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00453       unsigned SubReg = *SubRegs;
00454       // If a register isn't itself defined, but all parts that make up of it
00455       // are defined, then consider it also defined.
00456       // e.g.
00457       // AL =
00458       // AH =
00459       //    = AX
00460       if (Live.count(SubReg))
00461         continue;
00462       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
00463         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
00464              SS.isValid(); ++SS)
00465           Live.insert(*SS);
00466       }
00467     }
00468   }
00469 
00470   // Start from the largest piece, find the last time any part of the register
00471   // is referenced.
00472   HandlePhysRegKill(Reg, MI);
00473   // Only some of the sub-registers are used.
00474   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
00475     unsigned SubReg = *SubRegs;
00476     if (!Live.count(SubReg))
00477       // Skip if this sub-register isn't defined.
00478       continue;
00479     HandlePhysRegKill(SubReg, MI);
00480   }
00481 
00482   if (MI)
00483     Defs.push_back(Reg);  // Remember this def.
00484 }
00485 
00486 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
00487                                       SmallVector<unsigned, 4> &Defs) {
00488   while (!Defs.empty()) {
00489     unsigned Reg = Defs.back();
00490     Defs.pop_back();
00491     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
00492          SubRegs.isValid(); ++SubRegs) {
00493       unsigned SubReg = *SubRegs;
00494       PhysRegDef[SubReg]  = MI;
00495       PhysRegUse[SubReg]  = NULL;
00496     }
00497   }
00498 }
00499 
00500 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
00501   MF = &mf;
00502   MRI = &mf.getRegInfo();
00503   TRI = MF->getTarget().getRegisterInfo();
00504 
00505   unsigned NumRegs = TRI->getNumRegs();
00506   PhysRegDef  = new MachineInstr*[NumRegs];
00507   PhysRegUse  = new MachineInstr*[NumRegs];
00508   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
00509   std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
00510   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
00511   PHIJoins.clear();
00512 
00513   // FIXME: LiveIntervals will be updated to remove its dependence on
00514   // LiveVariables to improve compilation time and eliminate bizarre pass
00515   // dependencies. Until then, we can't change much in -O0.
00516   if (!MRI->isSSA())
00517     report_fatal_error("regalloc=... not currently supported with -O0");
00518 
00519   analyzePHINodes(mf);
00520 
00521   // Calculate live variable information in depth first order on the CFG of the
00522   // function.  This guarantees that we will see the definition of a virtual
00523   // register before its uses due to dominance properties of SSA (except for PHI
00524   // nodes, which are treated as a special case).
00525   MachineBasicBlock *Entry = MF->begin();
00526   SmallPtrSet<MachineBasicBlock*,16> Visited;
00527 
00528   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
00529          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
00530        DFI != E; ++DFI) {
00531     MachineBasicBlock *MBB = *DFI;
00532 
00533     // Mark live-in registers as live-in.
00534     SmallVector<unsigned, 4> Defs;
00535     for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
00536            EE = MBB->livein_end(); II != EE; ++II) {
00537       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
00538              "Cannot have a live-in virtual register!");
00539       HandlePhysRegDef(*II, 0, Defs);
00540     }
00541 
00542     // Loop over all of the instructions, processing them.
00543     DistanceMap.clear();
00544     unsigned Dist = 0;
00545     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
00546          I != E; ++I) {
00547       MachineInstr *MI = I;
00548       if (MI->isDebugValue())
00549         continue;
00550       DistanceMap.insert(std::make_pair(MI, Dist++));
00551 
00552       // Process all of the operands of the instruction...
00553       unsigned NumOperandsToProcess = MI->getNumOperands();
00554 
00555       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
00556       // of the uses.  They will be handled in other basic blocks.
00557       if (MI->isPHI())
00558         NumOperandsToProcess = 1;
00559 
00560       // Clear kill and dead markers. LV will recompute them.
00561       SmallVector<unsigned, 4> UseRegs;
00562       SmallVector<unsigned, 4> DefRegs;
00563       SmallVector<unsigned, 1> RegMasks;
00564       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
00565         MachineOperand &MO = MI->getOperand(i);
00566         if (MO.isRegMask()) {
00567           RegMasks.push_back(i);
00568           continue;
00569         }
00570         if (!MO.isReg() || MO.getReg() == 0)
00571           continue;
00572         unsigned MOReg = MO.getReg();
00573         if (MO.isUse()) {
00574           MO.setIsKill(false);
00575           if (MO.readsReg())
00576             UseRegs.push_back(MOReg);
00577         } else /*MO.isDef()*/ {
00578           MO.setIsDead(false);
00579           DefRegs.push_back(MOReg);
00580         }
00581       }
00582 
00583       // Process all uses.
00584       for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
00585         unsigned MOReg = UseRegs[i];
00586         if (TargetRegisterInfo::isVirtualRegister(MOReg))
00587           HandleVirtRegUse(MOReg, MBB, MI);
00588         else if (!MRI->isReserved(MOReg))
00589           HandlePhysRegUse(MOReg, MI);
00590       }
00591 
00592       // Process all masked registers. (Call clobbers).
00593       for (unsigned i = 0, e = RegMasks.size(); i != e; ++i)
00594         HandleRegMask(MI->getOperand(RegMasks[i]));
00595 
00596       // Process all defs.
00597       for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
00598         unsigned MOReg = DefRegs[i];
00599         if (TargetRegisterInfo::isVirtualRegister(MOReg))
00600           HandleVirtRegDef(MOReg, MI);
00601         else if (!MRI->isReserved(MOReg))
00602           HandlePhysRegDef(MOReg, MI, Defs);
00603       }
00604       UpdatePhysRegDefs(MI, Defs);
00605     }
00606 
00607     // Handle any virtual assignments from PHI nodes which might be at the
00608     // bottom of this basic block.  We check all of our successor blocks to see
00609     // if they have PHI nodes, and if so, we simulate an assignment at the end
00610     // of the current block.
00611     if (!PHIVarInfo[MBB->getNumber()].empty()) {
00612       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
00613 
00614       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
00615              E = VarInfoVec.end(); I != E; ++I)
00616         // Mark it alive only in the block we are representing.
00617         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
00618                                 MBB);
00619     }
00620 
00621     // MachineCSE may CSE instructions which write to non-allocatable physical
00622     // registers across MBBs. Remember if any reserved register is liveout.
00623     SmallSet<unsigned, 4> LiveOuts;
00624     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
00625            SE = MBB->succ_end(); SI != SE; ++SI) {
00626       MachineBasicBlock *SuccMBB = *SI;
00627       if (SuccMBB->isLandingPad())
00628         continue;
00629       for (MachineBasicBlock::livein_iterator LI = SuccMBB->livein_begin(),
00630              LE = SuccMBB->livein_end(); LI != LE; ++LI) {
00631         unsigned LReg = *LI;
00632         if (!TRI->isInAllocatableClass(LReg))
00633           // Ignore other live-ins, e.g. those that are live into landing pads.
00634           LiveOuts.insert(LReg);
00635       }
00636     }
00637 
00638     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
00639     // available at the end of the basic block.
00640     for (unsigned i = 0; i != NumRegs; ++i)
00641       if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
00642         HandlePhysRegDef(i, 0, Defs);
00643 
00644     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
00645     std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
00646   }
00647 
00648   // Convert and transfer the dead / killed information we have gathered into
00649   // VirtRegInfo onto MI's.
00650   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
00651     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00652     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
00653       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
00654         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
00655       else
00656         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
00657   }
00658 
00659   // Check to make sure there are no unreachable blocks in the MC CFG for the
00660   // function.  If so, it is due to a bug in the instruction selector or some
00661   // other part of the code generator if this happens.
00662 #ifndef NDEBUG
00663   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
00664     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
00665 #endif
00666 
00667   delete[] PhysRegDef;
00668   delete[] PhysRegUse;
00669   delete[] PHIVarInfo;
00670 
00671   return false;
00672 }
00673 
00674 /// replaceKillInstruction - Update register kill info by replacing a kill
00675 /// instruction with a new one.
00676 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
00677                                            MachineInstr *NewMI) {
00678   VarInfo &VI = getVarInfo(Reg);
00679   std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
00680 }
00681 
00682 /// removeVirtualRegistersKilled - Remove all killed info for the specified
00683 /// instruction.
00684 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
00685   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00686     MachineOperand &MO = MI->getOperand(i);
00687     if (MO.isReg() && MO.isKill()) {
00688       MO.setIsKill(false);
00689       unsigned Reg = MO.getReg();
00690       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00691         bool removed = getVarInfo(Reg).removeKill(MI);
00692         assert(removed && "kill not in register's VarInfo?");
00693         (void)removed;
00694       }
00695     }
00696   }
00697 }
00698 
00699 /// analyzePHINodes - Gather information about the PHI nodes in here. In
00700 /// particular, we want to map the variable information of a virtual register
00701 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
00702 ///
00703 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
00704   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
00705        I != E; ++I)
00706     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
00707          BBI != BBE && BBI->isPHI(); ++BBI)
00708       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
00709         if (BBI->getOperand(i).readsReg())
00710           PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
00711             .push_back(BBI->getOperand(i).getReg());
00712 }
00713 
00714 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
00715                                       unsigned Reg,
00716                                       MachineRegisterInfo &MRI) {
00717   unsigned Num = MBB.getNumber();
00718 
00719   // Reg is live-through.
00720   if (AliveBlocks.test(Num))
00721     return true;
00722 
00723   // Registers defined in MBB cannot be live in.
00724   const MachineInstr *Def = MRI.getVRegDef(Reg);
00725   if (Def && Def->getParent() == &MBB)
00726     return false;
00727 
00728  // Reg was not defined in MBB, was it killed here?
00729   return findKill(&MBB);
00730 }
00731 
00732 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
00733   LiveVariables::VarInfo &VI = getVarInfo(Reg);
00734 
00735   // Loop over all of the successors of the basic block, checking to see if
00736   // the value is either live in the block, or if it is killed in the block.
00737   SmallVector<MachineBasicBlock*, 8> OpSuccBlocks;
00738   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
00739          E = MBB.succ_end(); SI != E; ++SI) {
00740     MachineBasicBlock *SuccMBB = *SI;
00741 
00742     // Is it alive in this successor?
00743     unsigned SuccIdx = SuccMBB->getNumber();
00744     if (VI.AliveBlocks.test(SuccIdx))
00745       return true;
00746     OpSuccBlocks.push_back(SuccMBB);
00747   }
00748 
00749   // Check to see if this value is live because there is a use in a successor
00750   // that kills it.
00751   switch (OpSuccBlocks.size()) {
00752   case 1: {
00753     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
00754     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
00755       if (VI.Kills[i]->getParent() == SuccMBB)
00756         return true;
00757     break;
00758   }
00759   case 2: {
00760     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
00761     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
00762       if (VI.Kills[i]->getParent() == SuccMBB1 ||
00763           VI.Kills[i]->getParent() == SuccMBB2)
00764         return true;
00765     break;
00766   }
00767   default:
00768     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
00769     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
00770       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
00771                              VI.Kills[i]->getParent()))
00772         return true;
00773   }
00774   return false;
00775 }
00776 
00777 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
00778 /// variables that are live out of DomBB will be marked as passing live through
00779 /// BB.
00780 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
00781                                 MachineBasicBlock *DomBB,
00782                                 MachineBasicBlock *SuccBB) {
00783   const unsigned NumNew = BB->getNumber();
00784 
00785   SmallSet<unsigned, 16> Defs, Kills;
00786 
00787   MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
00788   for (; BBI != BBE && BBI->isPHI(); ++BBI) {
00789     // Record the def of the PHI node.
00790     Defs.insert(BBI->getOperand(0).getReg());
00791 
00792     // All registers used by PHI nodes in SuccBB must be live through BB.
00793     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
00794       if (BBI->getOperand(i+1).getMBB() == BB)
00795         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
00796   }
00797 
00798   // Record all vreg defs and kills of all instructions in SuccBB.
00799   for (; BBI != BBE; ++BBI) {
00800     for (MachineInstr::mop_iterator I = BBI->operands_begin(),
00801          E = BBI->operands_end(); I != E; ++I) {
00802       if (I->isReg() && TargetRegisterInfo::isVirtualRegister(I->getReg())) {
00803         if (I->isDef())
00804           Defs.insert(I->getReg());
00805         else if (I->isKill())
00806           Kills.insert(I->getReg());
00807       }
00808     }
00809   }
00810 
00811   // Update info for all live variables
00812   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00813     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00814 
00815     // If the Defs is defined in the successor it can't be live in BB.
00816     if (Defs.count(Reg))
00817       continue;
00818 
00819     // If the register is either killed in or live through SuccBB it's also live
00820     // through BB.
00821     VarInfo &VI = getVarInfo(Reg);
00822     if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
00823       VI.AliveBlocks.set(NumNew);
00824   }
00825 }