LCOV - code coverage report
Current view: top level - lib/CodeGen - LiveVariables.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 350 376 93.1 %
Date: 2017-09-14 15:23:50 Functions: 25 25 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       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 a 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/ADT/DepthFirstIterator.h"
      31             : #include "llvm/ADT/STLExtras.h"
      32             : #include "llvm/ADT/SmallPtrSet.h"
      33             : #include "llvm/ADT/SmallSet.h"
      34             : #include "llvm/CodeGen/MachineInstr.h"
      35             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      36             : #include "llvm/CodeGen/Passes.h"
      37             : #include "llvm/Support/Debug.h"
      38             : #include "llvm/Support/ErrorHandling.h"
      39             : #include "llvm/Support/raw_ostream.h"
      40             : #include "llvm/Target/TargetInstrInfo.h"
      41             : #include <algorithm>
      42             : using namespace llvm;
      43             : 
      44             : char LiveVariables::ID = 0;
      45             : char &llvm::LiveVariablesID = LiveVariables::ID;
      46       20212 : INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
      47             :                 "Live Variable Analysis", false, false)
      48       20212 : INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
      49      261332 : INITIALIZE_PASS_END(LiveVariables, "livevars",
      50             :                 "Live Variable Analysis", false, false)
      51             : 
      52             : 
      53       16441 : void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
      54       16441 :   AU.addRequiredID(UnreachableMachineBlockElimID);
      55       16441 :   AU.setPreservesAll();
      56       16441 :   MachineFunctionPass::getAnalysisUsage(AU);
      57       16441 : }
      58             : 
      59             : MachineInstr *
      60      397776 : LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
      61      808195 :   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
      62      793940 :     if (Kills[i]->getParent() == MBB)
      63             :       return Kills[i];
      64             :   return nullptr;
      65             : }
      66             : 
      67             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
      68             : LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const {
      69             :   dbgs() << "  Alive in blocks: ";
      70             :   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
      71             :            E = AliveBlocks.end(); I != E; ++I)
      72             :     dbgs() << *I << ", ";
      73             :   dbgs() << "\n  Killed by:";
      74             :   if (Kills.empty())
      75             :     dbgs() << " No instructions.\n";
      76             :   else {
      77             :     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
      78             :       dbgs() << "\n    #" << i << ": " << *Kills[i];
      79             :     dbgs() << "\n";
      80             :   }
      81             : }
      82             : #endif
      83             : 
      84             : /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
      85     5995604 : LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
      86             :   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
      87             :          "getVarInfo: not a virtual register!");
      88     5995604 :   VirtRegInfo.grow(RegIdx);
      89    11991206 :   return VirtRegInfo[RegIdx];
      90             : }
      91             : 
      92     1710260 : void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
      93             :                                             MachineBasicBlock *DefBlock,
      94             :                                             MachineBasicBlock *MBB,
      95             :                                     std::vector<MachineBasicBlock*> &WorkList) {
      96     1710260 :   unsigned BBNum = MBB->getNumber();
      97             : 
      98             :   // Check to see if this basic block is one of the killing blocks.  If so,
      99             :   // remove it.
     100     7986701 :   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
     101     9563406 :     if (VRInfo.Kills[i]->getParent() == MBB) {
     102     1077610 :       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
     103      215522 :       break;
     104             :     }
     105             : 
     106     1710260 :   if (MBB == DefBlock) return;  // Terminate recursion
     107             : 
     108     1503730 :   if (VRInfo.AliveBlocks.test(BBNum))
     109             :     return;  // We already know the block is live
     110             : 
     111             :   // Mark the variable known alive in this bb
     112      863008 :   VRInfo.AliveBlocks.set(BBNum);
     113             : 
     114             :   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
     115     3452032 :   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
     116             : }
     117             : 
     118      581525 : void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
     119             :                                             MachineBasicBlock *DefBlock,
     120             :                                             MachineBasicBlock *MBB) {
     121     1163050 :   std::vector<MachineBasicBlock*> WorkList;
     122      581525 :   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
     123             : 
     124     2838995 :   while (!WorkList.empty()) {
     125     1128735 :     MachineBasicBlock *Pred = WorkList.back();
     126     1128735 :     WorkList.pop_back();
     127     1128735 :     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
     128             :   }
     129      581525 : }
     130             : 
     131     2692815 : void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
     132             :                                      MachineInstr &MI) {
     133             :   assert(MRI->getVRegDef(reg) && "Register use before def!");
     134             : 
     135     2692815 :   unsigned BBNum = MBB->getNumber();
     136             : 
     137     2692815 :   VarInfo& VRInfo = getVarInfo(reg);
     138             : 
     139             :   // Check to see if this basic block is already a kill block.
     140     8020415 :   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
     141             :     // Yes, this register is killed in this basic block already. Increase the
     142             :     // live range by updating the kill instruction.
     143     4639006 :     VRInfo.Kills.back() = &MI;
     144     2319503 :     return;
     145             :   }
     146             : 
     147             : #ifndef NDEBUG
     148             :   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
     149             :     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
     150             : #endif
     151             : 
     152             :   // This situation can occur:
     153             :   //
     154             :   //     ,------.
     155             :   //     |      |
     156             :   //     |      v
     157             :   //     |   t2 = phi ... t1 ...
     158             :   //     |      |
     159             :   //     |      v
     160             :   //     |   t1 = ...
     161             :   //     |  ... = ... t1 ...
     162             :   //     |      |
     163             :   //     `------'
     164             :   //
     165             :   // where there is a use in a PHI node that's a predecessor to the defining
     166             :   // block. We don't want to mark all predecessors as having the value "alive"
     167             :   // in this case.
     168      373312 :   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
     169             : 
     170             :   // Add a new kill entry for this basic block. If this virtual register is
     171             :   // already marked as alive in this basic block, that means it is alive in at
     172             :   // least one of the successor blocks, it's not a kill.
     173      373312 :   if (!VRInfo.AliveBlocks.test(BBNum))
     174      307528 :     VRInfo.Kills.push_back(&MI);
     175             : 
     176             :   // Update all dominating blocks to mark them as "known live".
     177      746624 :   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
     178     1629264 :          E = MBB->pred_end(); PI != E; ++PI)
     179      509328 :     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
     180             : }
     181             : 
     182     1758202 : void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr &MI) {
     183     1758202 :   VarInfo &VRInfo = getVarInfo(Reg);
     184             : 
     185     3516404 :   if (VRInfo.AliveBlocks.empty())
     186             :     // If vr is not alive in any block, then defaults to dead.
     187     3516404 :     VRInfo.Kills.push_back(&MI);
     188     1758202 : }
     189             : 
     190             : /// FindLastPartialDef - Return the last partial def of the specified register.
     191             : /// Also returns the sub-registers that're defined by the instruction.
     192      242566 : MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
     193             :                                             SmallSet<unsigned,4> &PartDefRegs) {
     194      242566 :   unsigned LastDefReg = 0;
     195      242566 :   unsigned LastDefDist = 0;
     196      242566 :   MachineInstr *LastDef = nullptr;
     197      826782 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     198      683300 :     unsigned SubReg = *SubRegs;
     199      683300 :     MachineInstr *Def = PhysRegDef[SubReg];
     200      341650 :     if (!Def)
     201      341638 :       continue;
     202          24 :     unsigned Dist = DistanceMap[Def];
     203          12 :     if (Dist > LastDefDist) {
     204           3 :       LastDefReg  = SubReg;
     205           3 :       LastDef     = Def;
     206           3 :       LastDefDist = Dist;
     207             :     }
     208             :   }
     209             : 
     210      242566 :   if (!LastDef)
     211             :     return nullptr;
     212             : 
     213           3 :   PartDefRegs.insert(LastDefReg);
     214          12 :   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
     215          18 :     MachineOperand &MO = LastDef->getOperand(i);
     216          18 :     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
     217           3 :       continue;
     218           6 :     unsigned DefReg = MO.getReg();
     219          12 :     if (TRI->isSubRegister(Reg, DefReg)) {
     220           3 :       for (MCSubRegIterator SubRegs(DefReg, TRI, /*IncludeSelf=*/true);
     221          15 :            SubRegs.isValid(); ++SubRegs)
     222          24 :         PartDefRegs.insert(*SubRegs);
     223             :     }
     224             :   }
     225             :   return LastDef;
     226             : }
     227             : 
     228             : /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
     229             : /// implicit defs to a machine instruction if there was an earlier def of its
     230             : /// super-register.
     231      889124 : void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr &MI) {
     232     1778248 :   MachineInstr *LastDef = PhysRegDef[Reg];
     233             :   // If there was a previous use or a "full" def all is well.
     234     1131718 :   if (!LastDef && !PhysRegUse[Reg]) {
     235             :     // Otherwise, the last sub-register def implicitly defines this register.
     236             :     // e.g.
     237             :     // AH =
     238             :     // AL = ... <imp-def EAX>, <imp-kill AH>
     239             :     //    = AH
     240             :     // ...
     241             :     //    = EAX
     242             :     // All of the sub-registers must have been defined before the use of Reg!
     243      485132 :     SmallSet<unsigned, 4> PartDefRegs;
     244      242566 :     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
     245             :     // If LastPartialDef is NULL, it must be using a livein register.
     246      242566 :     if (LastPartialDef) {
     247           3 :       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
     248             :                                                            true/*IsImp*/));
     249           6 :       PhysRegDef[Reg] = LastPartialDef;
     250           6 :       SmallSet<unsigned, 8> Processed;
     251          18 :       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     252          24 :         unsigned SubReg = *SubRegs;
     253          12 :         if (Processed.count(SubReg))
     254          12 :           continue;
     255          12 :         if (PartDefRegs.count(SubReg))
     256          12 :           continue;
     257             :         // This part of Reg was defined before the last partial def. It's killed
     258             :         // here.
     259           0 :         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
     260             :                                                              false/*IsDef*/,
     261           0 :                                                              true/*IsImp*/));
     262           0 :         PhysRegDef[SubReg] = LastPartialDef;
     263           0 :         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
     264           0 :           Processed.insert(*SS);
     265             :       }
     266             :     }
     267     2584972 :   } else if (LastDef && !PhysRegUse[Reg] &&
     268      645354 :              !LastDef->findRegisterDefOperand(Reg))
     269             :     // Last def defines the super register, add an implicit def of reg.
     270         212 :     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
     271             :                                                   true/*IsImp*/));
     272             : 
     273             :   // Remember this use.
     274      889124 :   for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     275     3289445 :        SubRegs.isValid(); ++SubRegs)
     276     4800642 :     PhysRegUse[*SubRegs] = &MI;
     277      889124 : }
     278             : 
     279             : /// FindLastRefOrPartRef - Return the last reference or partial reference of
     280             : /// the specified register.
     281         361 : MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
     282         722 :   MachineInstr *LastDef = PhysRegDef[Reg];
     283         722 :   MachineInstr *LastUse = PhysRegUse[Reg];
     284         361 :   if (!LastDef && !LastUse)
     285             :     return nullptr;
     286             : 
     287         361 :   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
     288         722 :   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
     289         361 :   unsigned LastPartDefDist = 0;
     290         858 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     291         136 :     unsigned SubReg = *SubRegs;
     292         272 :     MachineInstr *Def = PhysRegDef[SubReg];
     293         136 :     if (Def && Def != LastDef) {
     294             :       // There was a def of this sub-register in between. This is a partial
     295             :       // def, keep track of the last one.
     296         164 :       unsigned Dist = DistanceMap[Def];
     297          82 :       if (Dist > LastPartDefDist)
     298          41 :         LastPartDefDist = Dist;
     299         108 :     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
     300         108 :       unsigned Dist = DistanceMap[Use];
     301          54 :       if (Dist > LastRefOrPartRefDist) {
     302           0 :         LastRefOrPartRefDist = Dist;
     303           0 :         LastRefOrPartRef = Use;
     304             :       }
     305             :     }
     306             :   }
     307             : 
     308         361 :   return LastRefOrPartRef;
     309             : }
     310             : 
     311     7465148 : bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
     312    14930296 :   MachineInstr *LastDef = PhysRegDef[Reg];
     313    14930296 :   MachineInstr *LastUse = PhysRegUse[Reg];
     314     7465148 :   if (!LastDef && !LastUse)
     315             :     return false;
     316             : 
     317     6726703 :   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
     318    13453406 :   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
     319             :   // The whole register is used.
     320             :   // AL =
     321             :   // AH =
     322             :   //
     323             :   //    = AX
     324             :   //    = AL, AX<imp-use, kill>
     325             :   // AX =
     326             :   //
     327             :   // Or whole register is defined, but not used at all.
     328             :   // AX<dead> =
     329             :   // ...
     330             :   // AX =
     331             :   //
     332             :   // Or whole register is defined, but only partly used.
     333             :   // AX<dead> = AL<imp-def>
     334             :   //    = AL<kill>
     335             :   // AX =
     336     6726703 :   MachineInstr *LastPartDef = nullptr;
     337     6726703 :   unsigned LastPartDefDist = 0;
     338    13453406 :   SmallSet<unsigned, 8> PartUses;
     339    22134056 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     340    17361300 :     unsigned SubReg = *SubRegs;
     341    17361300 :     MachineInstr *Def = PhysRegDef[SubReg];
     342     8680650 :     if (Def && Def != LastDef) {
     343             :       // There was a def of this sub-register in between. This is a partial
     344             :       // def, keep track of the last one.
     345      616886 :       unsigned Dist = DistanceMap[Def];
     346      308443 :       if (Dist > LastPartDefDist) {
     347      106807 :         LastPartDefDist = Dist;
     348      106807 :         LastPartDef = Def;
     349             :       }
     350      308443 :       continue;
     351             :     }
     352    16744414 :     if (MachineInstr *Use = PhysRegUse[SubReg]) {
     353    30924495 :       for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true); SS.isValid();
     354             :            ++SS)
     355    29096146 :         PartUses.insert(*SS);
     356    16376422 :       unsigned Dist = DistanceMap[Use];
     357     8188211 :       if (Dist > LastRefOrPartRefDist) {
     358         361 :         LastRefOrPartRefDist = Dist;
     359         361 :         LastRefOrPartRef = Use;
     360             :       }
     361             :     }
     362             :   }
     363             : 
     364    13453406 :   if (!PhysRegUse[Reg]) {
     365             :     // Partial uses. Mark register def dead and add implicit def of
     366             :     // sub-registers which are used.
     367             :     // EAX<dead>  = op  AL<imp-def>
     368             :     // That is, EAX def is dead but AL def extends pass it.
     369     1934680 :     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
     370     2121678 :     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     371      373996 :       unsigned SubReg = *SubRegs;
     372      186998 :       if (!PartUses.count(SubReg))
     373      186637 :         continue;
     374         361 :       bool NeedDef = true;
     375        1083 :       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
     376         722 :         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
     377         361 :         if (MO) {
     378             :           NeedDef = false;
     379             :           assert(!MO->isDead());
     380             :         }
     381             :       }
     382             :       if (NeedDef)
     383           0 :         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
     384           0 :                                                  true/*IsDef*/, true/*IsImp*/));
     385         361 :       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
     386         361 :       if (LastSubRef)
     387         361 :         LastSubRef->addRegisterKilled(SubReg, TRI, true);
     388             :       else {
     389           0 :         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
     390           0 :         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
     391           0 :              SS.isValid(); ++SS)
     392           0 :           PhysRegUse[*SS] = LastRefOrPartRef;
     393             :       }
     394         858 :       for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
     395         272 :         PartUses.erase(*SS);
     396             :     }
     397    11518726 :   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
     398           0 :     if (LastPartDef)
     399             :       // The last partial def kills the register.
     400           0 :       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
     401             :                                                 true/*IsImp*/, true/*IsKill*/));
     402             :     else {
     403             :       MachineOperand *MO =
     404           0 :         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
     405           0 :       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           0 :       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
     409           0 :       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           0 :         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
     413           0 :         if (MO)
     414             :           MO->setIsEarlyClobber();
     415             :       }
     416             :     }
     417             :   } else
     418     5759363 :     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
     419             :   return true;
     420             : }
     421             : 
     422      187976 : void LiveVariables::HandleRegMask(const MachineOperand &MO) {
     423             :   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
     424             :   // Clobbered registers are always dead, sp there is no need to use
     425             :   // HandlePhysRegDef().
     426    48915413 :   for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
     427             :     // Skip dead regs.
     428   144301830 :     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
     429    46681202 :       continue;
     430             :     // Skip mask-preserved regs.
     431     2046235 :     if (!MO.clobbersPhysReg(Reg))
     432      334376 :       continue;
     433             :     // Kill the largest clobbered super-register.
     434             :     // This avoids needless implicit operands.
     435     1711859 :     unsigned Super = Reg;
     436     6393992 :     for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
     437    12127227 :       if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
     438             :         Super = *SR;
     439     1711859 :     HandlePhysRegKill(Super, nullptr);
     440             :   }
     441      187976 : }
     442             : 
     443     3311779 : void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
     444             :                                      SmallVectorImpl<unsigned> &Defs) {
     445             :   // What parts of the register are previously defined?
     446     6623558 :   SmallSet<unsigned, 32> Live;
     447     7886140 :   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
     448     5146668 :     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     449     7582812 :          SubRegs.isValid(); ++SubRegs)
     450    10018956 :       Live.insert(*SubRegs);
     451             :   } else {
     452     3337767 :     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     453     2244864 :       unsigned SubReg = *SubRegs;
     454             :       // If a register isn't itself defined, but all parts that make up of it
     455             :       // are defined, then consider it also defined.
     456             :       // e.g.
     457             :       // AL =
     458             :       // AH =
     459             :       //    = AX
     460     1122432 :       if (Live.count(SubReg))
     461        2269 :         continue;
     462     3359622 :       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
     463        3097 :         for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
     464        8507 :              SS.isValid(); ++SS)
     465       10820 :           Live.insert(*SS);
     466             :       }
     467             :     }
     468             :   }
     469             : 
     470             :   // Start from the largest piece, find the last time any part of the register
     471             :   // is referenced.
     472     3311779 :   HandlePhysRegKill(Reg, MI);
     473             :   // Only some of the sub-registers are used.
     474    10182134 :   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
     475     7117152 :     unsigned SubReg = *SubRegs;
     476     3558576 :     if (!Live.count(SubReg))
     477             :       // Skip if this sub-register isn't defined.
     478     1117066 :       continue;
     479     2441510 :     HandlePhysRegKill(SubReg, MI);
     480             :   }
     481             : 
     482     3311779 :   if (MI)
     483     1290647 :     Defs.push_back(Reg);  // Remember this def.
     484     3311779 : }
     485             : 
     486     3887348 : void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
     487             :                                       SmallVectorImpl<unsigned> &Defs) {
     488     6468642 :   while (!Defs.empty()) {
     489     2581294 :     unsigned Reg = Defs.back();
     490     2581294 :     Defs.pop_back();
     491     1290647 :     for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
     492     3813396 :          SubRegs.isValid(); ++SubRegs) {
     493     2522749 :       unsigned SubReg = *SubRegs;
     494     5045498 :       PhysRegDef[SubReg] = &MI;
     495     5045498 :       PhysRegUse[SubReg]  = nullptr;
     496             :     }
     497             :   }
     498     3887348 : }
     499             : 
     500     3887348 : void LiveVariables::runOnInstr(MachineInstr &MI,
     501             :                                SmallVectorImpl<unsigned> &Defs) {
     502             :   assert(!MI.isDebugValue());
     503             :   // Process all of the operands of the instruction...
     504     3887348 :   unsigned NumOperandsToProcess = MI.getNumOperands();
     505             : 
     506             :   // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
     507             :   // of the uses.  They will be handled in other basic blocks.
     508     3853260 :   if (MI.isPHI())
     509             :     NumOperandsToProcess = 1;
     510             : 
     511             :   // Clear kill and dead markers. LV will recompute them.
     512     7774696 :   SmallVector<unsigned, 4> UseRegs;
     513     7774696 :   SmallVector<unsigned, 4> DefRegs;
     514     7774696 :   SmallVector<unsigned, 1> RegMasks;
     515    19348161 :   for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
     516    30921624 :     MachineOperand &MO = MI.getOperand(i);
     517    15648788 :     if (MO.isRegMask()) {
     518      187976 :       RegMasks.push_back(i);
     519     7108450 :       continue;
     520             :     }
     521    22005334 :     if (!MO.isReg() || MO.getReg() == 0)
     522     6732498 :       continue;
     523     8540338 :     unsigned MOReg = MO.getReg();
     524     8540338 :     if (MO.isUse()) {
     525    11775108 :       if (!(TargetRegisterInfo::isPhysicalRegister(MOReg) &&
     526     4223368 :             MRI->isReserved(MOReg)))
     527             :         MO.setIsKill(false);
     528             :       if (MO.readsReg())
     529     4803019 :         UseRegs.push_back(MOReg);
     530             :     } else {
     531             :       assert(MO.isDef());
     532             :       // FIXME: We should not remove any dead flags. However the MIPS RDDSP
     533             :       // instruction needs it at the moment: http://llvm.org/PR27116.
     534     9367676 :       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
     535     3900848 :           !MRI->isReserved(MOReg))
     536             :         MO.setIsDead(false);
     537     3708626 :       DefRegs.push_back(MOReg);
     538             :     }
     539             :   }
     540             : 
     541     3887349 :   MachineBasicBlock *MBB = MI.getParent();
     542             :   // Process all uses.
     543    12577716 :   for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
     544     9606038 :     unsigned MOReg = UseRegs[i];
     545     4803019 :     if (TargetRegisterInfo::isVirtualRegister(MOReg))
     546     2692815 :       HandleVirtRegUse(MOReg, MBB, MI);
     547     4220408 :     else if (!MRI->isReserved(MOReg))
     548      889124 :       HandlePhysRegUse(MOReg, MI);
     549             :   }
     550             : 
     551             :   // Process all masked registers. (Call clobbers).
     552     7962672 :   for (unsigned i = 0, e = RegMasks.size(); i != e; ++i)
     553      563928 :     HandleRegMask(MI.getOperand(RegMasks[i]));
     554             : 
     555             :   // Process all defs.
     556    11483323 :   for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
     557     7417254 :     unsigned MOReg = DefRegs[i];
     558     3708627 :     if (TargetRegisterInfo::isVirtualRegister(MOReg))
     559     1758202 :       HandleVirtRegDef(MOReg, MI);
     560     3900850 :     else if (!MRI->isReserved(MOReg))
     561     1290647 :       HandlePhysRegDef(MOReg, &MI, Defs);
     562             :   }
     563     3887348 :   UpdatePhysRegDefs(MI, Defs);
     564     3887348 : }
     565             : 
     566      292457 : void LiveVariables::runOnBlock(MachineBasicBlock *MBB, const unsigned NumRegs) {
     567             :   // Mark live-in registers as live-in.
     568      584914 :   SmallVector<unsigned, 4> Defs;
     569      850135 :   for (const auto &LI : MBB->liveins()) {
     570             :     assert(TargetRegisterInfo::isPhysicalRegister(LI.PhysReg) &&
     571             :            "Cannot have a live-in virtual register!");
     572      265221 :     HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
     573             :   }
     574             : 
     575             :   // Loop over all of the instructions, processing them.
     576      292457 :   DistanceMap.clear();
     577      292457 :   unsigned Dist = 0;
     578     8980336 :   for (MachineInstr &MI : *MBB) {
     579     3905254 :     if (MI.isDebugValue())
     580       17906 :       continue;
     581    11662044 :     DistanceMap.insert(std::make_pair(&MI, Dist++));
     582             : 
     583     3887348 :     runOnInstr(MI, Defs);
     584             :   }
     585             : 
     586             :   // Handle any virtual assignments from PHI nodes which might be at the
     587             :   // bottom of this basic block.  We check all of our successor blocks to see
     588             :   // if they have PHI nodes, and if so, we simulate an assignment at the end
     589             :   // of the current block.
     590      584914 :   if (!PHIVarInfo[MBB->getNumber()].empty()) {
     591             :     SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
     592             : 
     593       72197 :     for (SmallVectorImpl<unsigned>::iterator I = VarInfoVec.begin(),
     594      125748 :            E = VarInfoVec.end(); I != E; ++I)
     595             :       // Mark it alive only in the block we are representing.
     596       72197 :       MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
     597             :                               MBB);
     598             :   }
     599             : 
     600             :   // MachineCSE may CSE instructions which write to non-allocatable physical
     601             :   // registers across MBBs. Remember if any reserved register is liveout.
     602      584914 :   SmallSet<unsigned, 4> LiveOuts;
     603      584914 :   for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
     604     1087168 :          SE = MBB->succ_end(); SI != SE; ++SI) {
     605      209797 :     MachineBasicBlock *SuccMBB = *SI;
     606      209797 :     if (SuccMBB->isEHPad())
     607       26613 :       continue;
     608      366819 :     for (const auto &LI : SuccMBB->liveins()) {
     609         902 :       if (!TRI->isInAllocatableClass(LI.PhysReg))
     610             :         // Ignore other live-ins, e.g. those that are live into landing pads.
     611         447 :         LiveOuts.insert(LI.PhysReg);
     612             :     }
     613             :   }
     614             : 
     615             :   // Loop over PhysRegDef / PhysRegUse, killing any registers that are
     616             :   // available at the end of the basic block.
     617   139127418 :   for (unsigned i = 0; i != NumRegs; ++i)
     618   415204691 :     if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
     619     1755911 :       HandlePhysRegDef(i, nullptr, Defs);
     620      292457 : }
     621             : 
     622      141629 : bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
     623      141629 :   MF = &mf;
     624      141629 :   MRI = &mf.getRegInfo();
     625      141629 :   TRI = MF->getSubtarget().getRegisterInfo();
     626             : 
     627      141629 :   const unsigned NumRegs = TRI->getNumRegs();
     628      283258 :   PhysRegDef.assign(NumRegs, nullptr);
     629      283258 :   PhysRegUse.assign(NumRegs, nullptr);
     630      283258 :   PHIVarInfo.resize(MF->getNumBlockIDs());
     631      283258 :   PHIJoins.clear();
     632             : 
     633             :   // FIXME: LiveIntervals will be updated to remove its dependence on
     634             :   // LiveVariables to improve compilation time and eliminate bizarre pass
     635             :   // dependencies. Until then, we can't change much in -O0.
     636      283258 :   if (!MRI->isSSA())
     637           0 :     report_fatal_error("regalloc=... not currently supported with -O0");
     638             : 
     639      141629 :   analyzePHINodes(mf);
     640             : 
     641             :   // Calculate live variable information in depth first order on the CFG of the
     642             :   // function.  This guarantees that we will see the definition of a virtual
     643             :   // register before its uses due to dominance properties of SSA (except for PHI
     644             :   // nodes, which are treated as a special case).
     645      283258 :   MachineBasicBlock *Entry = &MF->front();
     646      283258 :   df_iterator_default_set<MachineBasicBlock*,16> Visited;
     647             : 
     648     1293059 :   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
     649      292457 :     runOnBlock(MBB, NumRegs);
     650             : 
     651      584914 :     PhysRegDef.assign(NumRegs, nullptr);
     652      584914 :     PhysRegUse.assign(NumRegs, nullptr);
     653             :   }
     654             : 
     655             :   // Convert and transfer the dead / killed information we have gathered into
     656             :   // VirtRegInfo onto MI's.
     657     2593881 :   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
     658     2310623 :     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
     659     8628313 :     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
     660     5089332 :       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
     661       17811 :         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
     662             :       else
     663     5071521 :         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
     664             :   }
     665             : 
     666             :   // Check to make sure there are no unreachable blocks in the MC CFG for the
     667             :   // function.  If so, it is due to a bug in the instruction selector or some
     668             :   // other part of the code generator if this happens.
     669             : #ifndef NDEBUG
     670             :   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
     671             :     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
     672             : #endif
     673             : 
     674      283258 :   PhysRegDef.clear();
     675      283258 :   PhysRegUse.clear();
     676      141629 :   PHIVarInfo.clear();
     677             : 
     678      283258 :   return false;
     679             : }
     680             : 
     681             : /// replaceKillInstruction - Update register kill info by replacing a kill
     682             : /// instruction with a new one.
     683      103187 : void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr &OldMI,
     684             :                                            MachineInstr &NewMI) {
     685      103187 :   VarInfo &VI = getVarInfo(Reg);
     686      412748 :   std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
     687      103187 : }
     688             : 
     689             : /// removeVirtualRegistersKilled - Remove all killed info for the specified
     690             : /// instruction.
     691       33423 : void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
     692      211452 :   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
     693      356058 :     MachineOperand &MO = MI.getOperand(i);
     694      283755 :     if (MO.isReg() && MO.isKill()) {
     695           0 :       MO.setIsKill(false);
     696           0 :       unsigned Reg = MO.getReg();
     697           0 :       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
     698           0 :         bool removed = getVarInfo(Reg).removeKill(MI);
     699             :         assert(removed && "kill not in register's VarInfo?");
     700             :         (void)removed;
     701             :       }
     702             :     }
     703             :   }
     704       33423 : }
     705             : 
     706             : /// analyzePHINodes - Gather information about the PHI nodes in here. In
     707             : /// particular, we want to map the variable information of a virtual register
     708             : /// which is used in a PHI node. We map that to the BB the vreg is coming from.
     709             : ///
     710      141628 : void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
     711      717340 :   for (const auto &MBB : Fn)
     712     1527070 :     for (const auto &BBI : MBB) {
     713             :       if (!BBI.isPHI())
     714             :         break;
     715      107764 :       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
     716      147352 :         if (BBI.getOperand(i).readsReg())
     717      216591 :           PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
     718       72197 :             .push_back(BBI.getOperand(i).getReg());
     719             :     }
     720      141629 : }
     721             : 
     722        2198 : bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
     723             :                                       unsigned Reg,
     724             :                                       MachineRegisterInfo &MRI) {
     725        2198 :   unsigned Num = MBB.getNumber();
     726             : 
     727             :   // Reg is live-through.
     728        2198 :   if (AliveBlocks.test(Num))
     729             :     return true;
     730             : 
     731             :   // Registers defined in MBB cannot be live in.
     732        1612 :   const MachineInstr *Def = MRI.getVRegDef(Reg);
     733        1612 :   if (Def && Def->getParent() == &MBB)
     734             :     return false;
     735             : 
     736             :  // Reg was not defined in MBB, was it killed here?
     737        1610 :   return findKill(&MBB);
     738             : }
     739             : 
     740       76425 : bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
     741       76425 :   LiveVariables::VarInfo &VI = getVarInfo(Reg);
     742             : 
     743      152850 :   SmallPtrSet<const MachineBasicBlock *, 8> Kills;
     744      160316 :   for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
     745       14932 :     Kills.insert(VI.Kills[i]->getParent());
     746             : 
     747             :   // Loop over all of the successors of the basic block, checking to see if
     748             :   // the value is either live in the block, or if it is killed in the block.
     749      248984 :   for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
     750             :     // Is it alive in this successor?
     751      101524 :     unsigned SuccIdx = SuccMBB->getNumber();
     752      101524 :     if (VI.AliveBlocks.test(SuccIdx))
     753             :       return true;
     754             :     // Or is it live because there is a use in a successor that kills it?
     755       98155 :     if (Kills.count(SuccMBB))
     756             :       return true;
     757             :   }
     758             : 
     759             :   return false;
     760             : }
     761             : 
     762             : /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
     763             : /// variables that are live out of DomBB will be marked as passing live through
     764             : /// BB.
     765        1503 : void LiveVariables::addNewBlock(MachineBasicBlock *BB,
     766             :                                 MachineBasicBlock *DomBB,
     767             :                                 MachineBasicBlock *SuccBB) {
     768        1503 :   const unsigned NumNew = BB->getNumber();
     769             : 
     770        6012 :   DenseSet<unsigned> Defs, Kills;
     771             : 
     772        3006 :   MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
     773        7740 :   for (; BBI != BBE && BBI->isPHI(); ++BBI) {
     774             :     // Record the def of the PHI node.
     775        4760 :     Defs.insert(BBI->getOperand(0).getReg());
     776             : 
     777             :     // All registers used by PHI nodes in SuccBB must be live through BB.
     778       15083 :     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
     779       20646 :       if (BBI->getOperand(i+1).getMBB() == BB)
     780        4770 :         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
     781             :   }
     782             : 
     783             :   // Record all vreg defs and kills of all instructions in SuccBB.
     784       12273 :   for (; BBI != BBE; ++BBI) {
     785       52447 :     for (MachineInstr::mop_iterator I = BBI->operands_begin(),
     786       21540 :          E = BBI->operands_end(); I != E; ++I) {
     787       69467 :       if (I->isReg() && TargetRegisterInfo::isVirtualRegister(I->getReg())) {
     788       12913 :         if (I->isDef())
     789        7524 :           Defs.insert(I->getReg());
     790        9151 :         else if (I->isKill())
     791        9848 :           Kills.insert(I->getReg());
     792             :       }
     793             :     }
     794             :   }
     795             : 
     796             :   // Update info for all live variables
     797      327862 :   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
     798      324856 :     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
     799             : 
     800             :     // If the Defs is defined in the successor it can't be live in BB.
     801      324856 :     if (Defs.count(Reg))
     802        6142 :       continue;
     803             : 
     804             :     // If the register is either killed in or live through SuccBB it's also live
     805             :     // through BB.
     806      318714 :     VarInfo &VI = getVarInfo(Reg);
     807      318714 :     if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
     808        7182 :       VI.AliveBlocks.set(NumNew);
     809             :   }
     810        1503 : }

Generated by: LCOV version 1.13