10b57cec5SDimitry Andric //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the LiveVariable analysis pass.  For each machine
100b57cec5SDimitry Andric // instruction in the function, this pass calculates the set of registers that
110b57cec5SDimitry Andric // are immediately dead after the instruction (i.e., the instruction calculates
120b57cec5SDimitry Andric // the value, but it is never used) and the set of registers that are used by
130b57cec5SDimitry Andric // the instruction, but are never used after the instruction (i.e., they are
140b57cec5SDimitry Andric // killed).
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric // This class computes live variables using a sparse implementation based on
170b57cec5SDimitry Andric // the machine code SSA form.  This class computes live variable information for
180b57cec5SDimitry Andric // each virtual and _register allocatable_ physical register in a function.  It
190b57cec5SDimitry Andric // uses the dominance properties of SSA form to efficiently compute live
200b57cec5SDimitry Andric // variables for virtual registers, and assumes that physical registers are only
210b57cec5SDimitry Andric // live within a single basic block (allowing it to do a single local analysis
220b57cec5SDimitry Andric // to resolve physical register lifetimes in each basic block).  If a physical
230b57cec5SDimitry Andric // register is not register allocatable, it is not tracked.  This is useful for
240b57cec5SDimitry Andric // things like the stack pointer and condition codes.
250b57cec5SDimitry Andric //
260b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
298bcb0991SDimitry Andric #include "llvm/ADT/DenseSet.h"
300b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
310b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
320b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
330b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
370b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
380b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
390b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
400b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
410b57cec5SDimitry Andric #include <algorithm>
420b57cec5SDimitry Andric using namespace llvm;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric char LiveVariables::ID = 0;
450b57cec5SDimitry Andric char &llvm::LiveVariablesID = LiveVariables::ID;
460b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
470b57cec5SDimitry Andric                 "Live Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)480b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
490b57cec5SDimitry Andric INITIALIZE_PASS_END(LiveVariables, "livevars",
500b57cec5SDimitry Andric                 "Live Variable Analysis", false, false)
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
540b57cec5SDimitry Andric   AU.addRequiredID(UnreachableMachineBlockElimID);
550b57cec5SDimitry Andric   AU.setPreservesAll();
560b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric MachineInstr *
findKill(const MachineBasicBlock * MBB) const600b57cec5SDimitry Andric LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
614824e7fdSDimitry Andric   for (MachineInstr *MI : Kills)
624824e7fdSDimitry Andric     if (MI->getParent() == MBB)
634824e7fdSDimitry Andric       return MI;
640b57cec5SDimitry Andric   return nullptr;
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const680b57cec5SDimitry Andric LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const {
690b57cec5SDimitry Andric   dbgs() << "  Alive in blocks: ";
70fe6060f1SDimitry Andric   for (unsigned AB : AliveBlocks)
71fe6060f1SDimitry Andric     dbgs() << AB << ", ";
720b57cec5SDimitry Andric   dbgs() << "\n  Killed by:";
730b57cec5SDimitry Andric   if (Kills.empty())
740b57cec5SDimitry Andric     dbgs() << " No instructions.\n";
750b57cec5SDimitry Andric   else {
760b57cec5SDimitry Andric     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
770b57cec5SDimitry Andric       dbgs() << "\n    #" << i << ": " << *Kills[i];
780b57cec5SDimitry Andric     dbgs() << "\n";
790b57cec5SDimitry Andric   }
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric #endif
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
getVarInfo(Register Reg)84e8d8bef9SDimitry Andric LiveVariables::VarInfo &LiveVariables::getVarInfo(Register Reg) {
85e8d8bef9SDimitry Andric   assert(Reg.isVirtual() && "getVarInfo: not a virtual register!");
86e8d8bef9SDimitry Andric   VirtRegInfo.grow(Reg);
87e8d8bef9SDimitry Andric   return VirtRegInfo[Reg];
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric 
MarkVirtRegAliveInBlock(VarInfo & VRInfo,MachineBasicBlock * DefBlock,MachineBasicBlock * MBB,SmallVectorImpl<MachineBasicBlock * > & WorkList)90e8d8bef9SDimitry Andric void LiveVariables::MarkVirtRegAliveInBlock(
91e8d8bef9SDimitry Andric     VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *MBB,
92e8d8bef9SDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &WorkList) {
930b57cec5SDimitry Andric   unsigned BBNum = MBB->getNumber();
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   // Check to see if this basic block is one of the killing blocks.  If so,
960b57cec5SDimitry Andric   // remove it.
970b57cec5SDimitry Andric   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
980b57cec5SDimitry Andric     if (VRInfo.Kills[i]->getParent() == MBB) {
990b57cec5SDimitry Andric       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
1000b57cec5SDimitry Andric       break;
1010b57cec5SDimitry Andric     }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric   if (MBB == DefBlock) return;  // Terminate recursion
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   if (VRInfo.AliveBlocks.test(BBNum))
1060b57cec5SDimitry Andric     return;  // We already know the block is live
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // Mark the variable known alive in this bb
1090b57cec5SDimitry Andric   VRInfo.AliveBlocks.set(BBNum);
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
1120b57cec5SDimitry Andric   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
1130b57cec5SDimitry Andric }
1140b57cec5SDimitry Andric 
MarkVirtRegAliveInBlock(VarInfo & VRInfo,MachineBasicBlock * DefBlock,MachineBasicBlock * MBB)1150b57cec5SDimitry Andric void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
1160b57cec5SDimitry Andric                                             MachineBasicBlock *DefBlock,
1170b57cec5SDimitry Andric                                             MachineBasicBlock *MBB) {
118e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 16> WorkList;
1190b57cec5SDimitry Andric   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   while (!WorkList.empty()) {
122349cc55cSDimitry Andric     MachineBasicBlock *Pred = WorkList.pop_back_val();
1230b57cec5SDimitry Andric     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
HandleVirtRegUse(Register Reg,MachineBasicBlock * MBB,MachineInstr & MI)127e8d8bef9SDimitry Andric void LiveVariables::HandleVirtRegUse(Register Reg, MachineBasicBlock *MBB,
1280b57cec5SDimitry Andric                                      MachineInstr &MI) {
129e8d8bef9SDimitry Andric   assert(MRI->getVRegDef(Reg) && "Register use before def!");
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   unsigned BBNum = MBB->getNumber();
1320b57cec5SDimitry Andric 
133e8d8bef9SDimitry Andric   VarInfo &VRInfo = getVarInfo(Reg);
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   // Check to see if this basic block is already a kill block.
1360b57cec5SDimitry Andric   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
1370b57cec5SDimitry Andric     // Yes, this register is killed in this basic block already. Increase the
1380b57cec5SDimitry Andric     // live range by updating the kill instruction.
1390b57cec5SDimitry Andric     VRInfo.Kills.back() = &MI;
1400b57cec5SDimitry Andric     return;
1410b57cec5SDimitry Andric   }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric #ifndef NDEBUG
1440eae32dcSDimitry Andric   for (MachineInstr *Kill : VRInfo.Kills)
1450eae32dcSDimitry Andric     assert(Kill->getParent() != MBB && "entry should be at end!");
1460b57cec5SDimitry Andric #endif
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   // This situation can occur:
1490b57cec5SDimitry Andric   //
1500b57cec5SDimitry Andric   //     ,------.
1510b57cec5SDimitry Andric   //     |      |
1520b57cec5SDimitry Andric   //     |      v
1530b57cec5SDimitry Andric   //     |   t2 = phi ... t1 ...
1540b57cec5SDimitry Andric   //     |      |
1550b57cec5SDimitry Andric   //     |      v
1560b57cec5SDimitry Andric   //     |   t1 = ...
1570b57cec5SDimitry Andric   //     |  ... = ... t1 ...
1580b57cec5SDimitry Andric   //     |      |
1590b57cec5SDimitry Andric   //     `------'
1600b57cec5SDimitry Andric   //
1610b57cec5SDimitry Andric   // where there is a use in a PHI node that's a predecessor to the defining
1620b57cec5SDimitry Andric   // block. We don't want to mark all predecessors as having the value "alive"
1630b57cec5SDimitry Andric   // in this case.
164e8d8bef9SDimitry Andric   if (MBB == MRI->getVRegDef(Reg)->getParent())
165e8d8bef9SDimitry Andric     return;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   // Add a new kill entry for this basic block. If this virtual register is
1680b57cec5SDimitry Andric   // already marked as alive in this basic block, that means it is alive in at
1690b57cec5SDimitry Andric   // least one of the successor blocks, it's not a kill.
1700b57cec5SDimitry Andric   if (!VRInfo.AliveBlocks.test(BBNum))
1710b57cec5SDimitry Andric     VRInfo.Kills.push_back(&MI);
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Update all dominating blocks to mark them as "known live".
174fe6060f1SDimitry Andric   for (MachineBasicBlock *Pred : MBB->predecessors())
175fe6060f1SDimitry Andric     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(Reg)->getParent(), Pred);
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
HandleVirtRegDef(Register Reg,MachineInstr & MI)178e8d8bef9SDimitry Andric void LiveVariables::HandleVirtRegDef(Register Reg, MachineInstr &MI) {
1790b57cec5SDimitry Andric   VarInfo &VRInfo = getVarInfo(Reg);
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   if (VRInfo.AliveBlocks.empty())
1820b57cec5SDimitry Andric     // If vr is not alive in any block, then defaults to dead.
1830b57cec5SDimitry Andric     VRInfo.Kills.push_back(&MI);
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric /// FindLastPartialDef - Return the last partial def of the specified register.
1870b57cec5SDimitry Andric /// Also returns the sub-registers that're defined by the instruction.
188e8d8bef9SDimitry Andric MachineInstr *
FindLastPartialDef(Register Reg,SmallSet<unsigned,4> & PartDefRegs)189e8d8bef9SDimitry Andric LiveVariables::FindLastPartialDef(Register Reg,
1900b57cec5SDimitry Andric                                   SmallSet<unsigned, 4> &PartDefRegs) {
1910b57cec5SDimitry Andric   unsigned LastDefReg = 0;
1920b57cec5SDimitry Andric   unsigned LastDefDist = 0;
1930b57cec5SDimitry Andric   MachineInstr *LastDef = nullptr;
194fe013be4SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
1950b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
1960b57cec5SDimitry Andric     if (!Def)
1970b57cec5SDimitry Andric       continue;
1980b57cec5SDimitry Andric     unsigned Dist = DistanceMap[Def];
1990b57cec5SDimitry Andric     if (Dist > LastDefDist) {
2000b57cec5SDimitry Andric       LastDefReg  = SubReg;
2010b57cec5SDimitry Andric       LastDef     = Def;
2020b57cec5SDimitry Andric       LastDefDist = Dist;
2030b57cec5SDimitry Andric     }
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   if (!LastDef)
2070b57cec5SDimitry Andric     return nullptr;
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   PartDefRegs.insert(LastDefReg);
210fe013be4SDimitry Andric   for (MachineOperand &MO : LastDef->all_defs()) {
211fe013be4SDimitry Andric     if (MO.getReg() == 0)
2120b57cec5SDimitry Andric       continue;
2138bcb0991SDimitry Andric     Register DefReg = MO.getReg();
2140b57cec5SDimitry Andric     if (TRI->isSubRegister(Reg, DefReg)) {
215fe013be4SDimitry Andric       for (MCPhysReg SubReg : TRI->subregs_inclusive(DefReg))
216fe013be4SDimitry Andric         PartDefRegs.insert(SubReg);
2170b57cec5SDimitry Andric     }
2180b57cec5SDimitry Andric   }
2190b57cec5SDimitry Andric   return LastDef;
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
2230b57cec5SDimitry Andric /// implicit defs to a machine instruction if there was an earlier def of its
2240b57cec5SDimitry Andric /// super-register.
HandlePhysRegUse(Register Reg,MachineInstr & MI)225e8d8bef9SDimitry Andric void LiveVariables::HandlePhysRegUse(Register Reg, MachineInstr &MI) {
2260b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
2270b57cec5SDimitry Andric   // If there was a previous use or a "full" def all is well.
2280b57cec5SDimitry Andric   if (!LastDef && !PhysRegUse[Reg]) {
2290b57cec5SDimitry Andric     // Otherwise, the last sub-register def implicitly defines this register.
2300b57cec5SDimitry Andric     // e.g.
2310b57cec5SDimitry Andric     // AH =
2320b57cec5SDimitry Andric     // AL = ... implicit-def EAX, implicit killed AH
2330b57cec5SDimitry Andric     //    = AH
2340b57cec5SDimitry Andric     // ...
2350b57cec5SDimitry Andric     //    = EAX
2360b57cec5SDimitry Andric     // All of the sub-registers must have been defined before the use of Reg!
2370b57cec5SDimitry Andric     SmallSet<unsigned, 4> PartDefRegs;
2380b57cec5SDimitry Andric     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
2390b57cec5SDimitry Andric     // If LastPartialDef is NULL, it must be using a livein register.
2400b57cec5SDimitry Andric     if (LastPartialDef) {
2410b57cec5SDimitry Andric       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
2420b57cec5SDimitry Andric                                                            true/*IsImp*/));
2430b57cec5SDimitry Andric       PhysRegDef[Reg] = LastPartialDef;
2440b57cec5SDimitry Andric       SmallSet<unsigned, 8> Processed;
245fe013be4SDimitry Andric       for (MCPhysReg SubReg : TRI->subregs(Reg)) {
2460b57cec5SDimitry Andric         if (Processed.count(SubReg))
2470b57cec5SDimitry Andric           continue;
2480b57cec5SDimitry Andric         if (PartDefRegs.count(SubReg))
2490b57cec5SDimitry Andric           continue;
2500b57cec5SDimitry Andric         // This part of Reg was defined before the last partial def. It's killed
2510b57cec5SDimitry Andric         // here.
2520b57cec5SDimitry Andric         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
2530b57cec5SDimitry Andric                                                              false/*IsDef*/,
2540b57cec5SDimitry Andric                                                              true/*IsImp*/));
2550b57cec5SDimitry Andric         PhysRegDef[SubReg] = LastPartialDef;
256fe013be4SDimitry Andric         for (MCPhysReg SS : TRI->subregs(SubReg))
257fe013be4SDimitry Andric           Processed.insert(SS);
2580b57cec5SDimitry Andric       }
2590b57cec5SDimitry Andric     }
2600b57cec5SDimitry Andric   } else if (LastDef && !PhysRegUse[Reg] &&
2610b57cec5SDimitry Andric              !LastDef->findRegisterDefOperand(Reg))
2620b57cec5SDimitry Andric     // Last def defines the super register, add an implicit def of reg.
2630b57cec5SDimitry Andric     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
2640b57cec5SDimitry Andric                                                   true/*IsImp*/));
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   // Remember this use.
267fe013be4SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
268fe013be4SDimitry Andric     PhysRegUse[SubReg] = &MI;
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric /// FindLastRefOrPartRef - Return the last reference or partial reference of
2720b57cec5SDimitry Andric /// the specified register.
FindLastRefOrPartRef(Register Reg)273e8d8bef9SDimitry Andric MachineInstr *LiveVariables::FindLastRefOrPartRef(Register Reg) {
2740b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
2750b57cec5SDimitry Andric   MachineInstr *LastUse = PhysRegUse[Reg];
2760b57cec5SDimitry Andric   if (!LastDef && !LastUse)
2770b57cec5SDimitry Andric     return nullptr;
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
2800b57cec5SDimitry Andric   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
2810b57cec5SDimitry Andric   unsigned LastPartDefDist = 0;
282fe013be4SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
2830b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
2840b57cec5SDimitry Andric     if (Def && Def != LastDef) {
2850b57cec5SDimitry Andric       // There was a def of this sub-register in between. This is a partial
2860b57cec5SDimitry Andric       // def, keep track of the last one.
2870b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Def];
2880b57cec5SDimitry Andric       if (Dist > LastPartDefDist)
2890b57cec5SDimitry Andric         LastPartDefDist = Dist;
2900b57cec5SDimitry Andric     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
2910b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Use];
2920b57cec5SDimitry Andric       if (Dist > LastRefOrPartRefDist) {
2930b57cec5SDimitry Andric         LastRefOrPartRefDist = Dist;
2940b57cec5SDimitry Andric         LastRefOrPartRef = Use;
2950b57cec5SDimitry Andric       }
2960b57cec5SDimitry Andric     }
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   return LastRefOrPartRef;
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
HandlePhysRegKill(Register Reg,MachineInstr * MI)302e8d8bef9SDimitry Andric bool LiveVariables::HandlePhysRegKill(Register Reg, MachineInstr *MI) {
3030b57cec5SDimitry Andric   MachineInstr *LastDef = PhysRegDef[Reg];
3040b57cec5SDimitry Andric   MachineInstr *LastUse = PhysRegUse[Reg];
3050b57cec5SDimitry Andric   if (!LastDef && !LastUse)
3060b57cec5SDimitry Andric     return false;
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
3090b57cec5SDimitry Andric   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
3100b57cec5SDimitry Andric   // The whole register is used.
3110b57cec5SDimitry Andric   // AL =
3120b57cec5SDimitry Andric   // AH =
3130b57cec5SDimitry Andric   //
3140b57cec5SDimitry Andric   //    = AX
3150b57cec5SDimitry Andric   //    = AL, implicit killed AX
3160b57cec5SDimitry Andric   // AX =
3170b57cec5SDimitry Andric   //
3180b57cec5SDimitry Andric   // Or whole register is defined, but not used at all.
3190b57cec5SDimitry Andric   // dead AX =
3200b57cec5SDimitry Andric   // ...
3210b57cec5SDimitry Andric   // AX =
3220b57cec5SDimitry Andric   //
3230b57cec5SDimitry Andric   // Or whole register is defined, but only partly used.
3240b57cec5SDimitry Andric   // dead AX = implicit-def AL
3250b57cec5SDimitry Andric   //    = killed AL
3260b57cec5SDimitry Andric   // AX =
3270b57cec5SDimitry Andric   MachineInstr *LastPartDef = nullptr;
3280b57cec5SDimitry Andric   unsigned LastPartDefDist = 0;
3290b57cec5SDimitry Andric   SmallSet<unsigned, 8> PartUses;
330fe013be4SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
3310b57cec5SDimitry Andric     MachineInstr *Def = PhysRegDef[SubReg];
3320b57cec5SDimitry Andric     if (Def && Def != LastDef) {
3330b57cec5SDimitry Andric       // There was a def of this sub-register in between. This is a partial
3340b57cec5SDimitry Andric       // def, keep track of the last one.
3350b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Def];
3360b57cec5SDimitry Andric       if (Dist > LastPartDefDist) {
3370b57cec5SDimitry Andric         LastPartDefDist = Dist;
3380b57cec5SDimitry Andric         LastPartDef = Def;
3390b57cec5SDimitry Andric       }
3400b57cec5SDimitry Andric       continue;
3410b57cec5SDimitry Andric     }
3420b57cec5SDimitry Andric     if (MachineInstr *Use = PhysRegUse[SubReg]) {
343fe013be4SDimitry Andric       for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
344fe013be4SDimitry Andric         PartUses.insert(SS);
3450b57cec5SDimitry Andric       unsigned Dist = DistanceMap[Use];
3460b57cec5SDimitry Andric       if (Dist > LastRefOrPartRefDist) {
3470b57cec5SDimitry Andric         LastRefOrPartRefDist = Dist;
3480b57cec5SDimitry Andric         LastRefOrPartRef = Use;
3490b57cec5SDimitry Andric       }
3500b57cec5SDimitry Andric     }
3510b57cec5SDimitry Andric   }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   if (!PhysRegUse[Reg]) {
3540b57cec5SDimitry Andric     // Partial uses. Mark register def dead and add implicit def of
3550b57cec5SDimitry Andric     // sub-registers which are used.
3560b57cec5SDimitry Andric     // dead EAX  = op  implicit-def AL
3570b57cec5SDimitry Andric     // That is, EAX def is dead but AL def extends pass it.
3580b57cec5SDimitry Andric     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
359fe013be4SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs(Reg)) {
3600b57cec5SDimitry Andric       if (!PartUses.count(SubReg))
3610b57cec5SDimitry Andric         continue;
3620b57cec5SDimitry Andric       bool NeedDef = true;
3630b57cec5SDimitry Andric       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
3640b57cec5SDimitry Andric         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
3650b57cec5SDimitry Andric         if (MO) {
3660b57cec5SDimitry Andric           NeedDef = false;
3670b57cec5SDimitry Andric           assert(!MO->isDead());
3680b57cec5SDimitry Andric         }
3690b57cec5SDimitry Andric       }
3700b57cec5SDimitry Andric       if (NeedDef)
3710b57cec5SDimitry Andric         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
3720b57cec5SDimitry Andric                                                  true/*IsDef*/, true/*IsImp*/));
3730b57cec5SDimitry Andric       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
3740b57cec5SDimitry Andric       if (LastSubRef)
3750b57cec5SDimitry Andric         LastSubRef->addRegisterKilled(SubReg, TRI, true);
3760b57cec5SDimitry Andric       else {
3770b57cec5SDimitry Andric         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
378fe013be4SDimitry Andric         for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
379fe013be4SDimitry Andric           PhysRegUse[SS] = LastRefOrPartRef;
3800b57cec5SDimitry Andric       }
381fe013be4SDimitry Andric       for (MCPhysReg SS : TRI->subregs(SubReg))
382fe013be4SDimitry Andric         PartUses.erase(SS);
3830b57cec5SDimitry Andric     }
3840b57cec5SDimitry Andric   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
3850b57cec5SDimitry Andric     if (LastPartDef)
3860b57cec5SDimitry Andric       // The last partial def kills the register.
3870b57cec5SDimitry Andric       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
3880b57cec5SDimitry Andric                                                 true/*IsImp*/, true/*IsKill*/));
3890b57cec5SDimitry Andric     else {
3900b57cec5SDimitry Andric       MachineOperand *MO =
3910b57cec5SDimitry Andric         LastRefOrPartRef->findRegisterDefOperand(Reg, false, false, TRI);
3920b57cec5SDimitry Andric       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
3930b57cec5SDimitry Andric       // If the last reference is the last def, then it's not used at all.
3940b57cec5SDimitry Andric       // That is, unless we are currently processing the last reference itself.
3950b57cec5SDimitry Andric       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
3960b57cec5SDimitry Andric       if (NeedEC) {
3970b57cec5SDimitry Andric         // If we are adding a subreg def and the superreg def is marked early
3980b57cec5SDimitry Andric         // clobber, add an early clobber marker to the subreg def.
3990b57cec5SDimitry Andric         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
4000b57cec5SDimitry Andric         if (MO)
4010b57cec5SDimitry Andric           MO->setIsEarlyClobber();
4020b57cec5SDimitry Andric       }
4030b57cec5SDimitry Andric     }
4040b57cec5SDimitry Andric   } else
4050b57cec5SDimitry Andric     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
4060b57cec5SDimitry Andric   return true;
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric 
HandleRegMask(const MachineOperand & MO,unsigned NumRegs)409*c9157d92SDimitry Andric void LiveVariables::HandleRegMask(const MachineOperand &MO, unsigned NumRegs) {
4100b57cec5SDimitry Andric   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
4110b57cec5SDimitry Andric   // Clobbered registers are always dead, sp there is no need to use
4120b57cec5SDimitry Andric   // HandlePhysRegDef().
413*c9157d92SDimitry Andric   for (unsigned Reg = 1; Reg != NumRegs; ++Reg) {
4140b57cec5SDimitry Andric     // Skip dead regs.
4150b57cec5SDimitry Andric     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
4160b57cec5SDimitry Andric       continue;
4170b57cec5SDimitry Andric     // Skip mask-preserved regs.
4180b57cec5SDimitry Andric     if (!MO.clobbersPhysReg(Reg))
4190b57cec5SDimitry Andric       continue;
4200b57cec5SDimitry Andric     // Kill the largest clobbered super-register.
4210b57cec5SDimitry Andric     // This avoids needless implicit operands.
4220b57cec5SDimitry Andric     unsigned Super = Reg;
423fe013be4SDimitry Andric     for (MCPhysReg SR : TRI->superregs(Reg))
424*c9157d92SDimitry Andric       if (SR < NumRegs && (PhysRegDef[SR] || PhysRegUse[SR]) &&
425*c9157d92SDimitry Andric           MO.clobbersPhysReg(SR))
426fe013be4SDimitry Andric         Super = SR;
4270b57cec5SDimitry Andric     HandlePhysRegKill(Super, nullptr);
4280b57cec5SDimitry Andric   }
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
HandlePhysRegDef(Register Reg,MachineInstr * MI,SmallVectorImpl<unsigned> & Defs)431e8d8bef9SDimitry Andric void LiveVariables::HandlePhysRegDef(Register Reg, MachineInstr *MI,
4320b57cec5SDimitry Andric                                      SmallVectorImpl<unsigned> &Defs) {
4330b57cec5SDimitry Andric   // What parts of the register are previously defined?
4340b57cec5SDimitry Andric   SmallSet<unsigned, 32> Live;
4350b57cec5SDimitry Andric   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
436fe013be4SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
437fe013be4SDimitry Andric       Live.insert(SubReg);
4380b57cec5SDimitry Andric   } else {
439fe013be4SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs(Reg)) {
4400b57cec5SDimitry Andric       // If a register isn't itself defined, but all parts that make up of it
4410b57cec5SDimitry Andric       // are defined, then consider it also defined.
4420b57cec5SDimitry Andric       // e.g.
4430b57cec5SDimitry Andric       // AL =
4440b57cec5SDimitry Andric       // AH =
4450b57cec5SDimitry Andric       //    = AX
4460b57cec5SDimitry Andric       if (Live.count(SubReg))
4470b57cec5SDimitry Andric         continue;
4480b57cec5SDimitry Andric       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
449fe013be4SDimitry Andric         for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
450fe013be4SDimitry Andric           Live.insert(SS);
4510b57cec5SDimitry Andric       }
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // Start from the largest piece, find the last time any part of the register
4560b57cec5SDimitry Andric   // is referenced.
4570b57cec5SDimitry Andric   HandlePhysRegKill(Reg, MI);
4580b57cec5SDimitry Andric   // Only some of the sub-registers are used.
459fe013be4SDimitry Andric   for (MCPhysReg SubReg : TRI->subregs(Reg)) {
4600b57cec5SDimitry Andric     if (!Live.count(SubReg))
4610b57cec5SDimitry Andric       // Skip if this sub-register isn't defined.
4620b57cec5SDimitry Andric       continue;
4630b57cec5SDimitry Andric     HandlePhysRegKill(SubReg, MI);
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   if (MI)
4670b57cec5SDimitry Andric     Defs.push_back(Reg);  // Remember this def.
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
UpdatePhysRegDefs(MachineInstr & MI,SmallVectorImpl<unsigned> & Defs)4700b57cec5SDimitry Andric void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
4710b57cec5SDimitry Andric                                       SmallVectorImpl<unsigned> &Defs) {
4720b57cec5SDimitry Andric   while (!Defs.empty()) {
473349cc55cSDimitry Andric     Register Reg = Defs.pop_back_val();
474fe013be4SDimitry Andric     for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg)) {
4750b57cec5SDimitry Andric       PhysRegDef[SubReg] = &MI;
4760b57cec5SDimitry Andric       PhysRegUse[SubReg]  = nullptr;
4770b57cec5SDimitry Andric     }
4780b57cec5SDimitry Andric   }
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
runOnInstr(MachineInstr & MI,SmallVectorImpl<unsigned> & Defs,unsigned NumRegs)4810b57cec5SDimitry Andric void LiveVariables::runOnInstr(MachineInstr &MI,
482*c9157d92SDimitry Andric                                SmallVectorImpl<unsigned> &Defs,
483*c9157d92SDimitry Andric                                unsigned NumRegs) {
484fe6060f1SDimitry Andric   assert(!MI.isDebugOrPseudoInstr());
4850b57cec5SDimitry Andric   // Process all of the operands of the instruction...
4860b57cec5SDimitry Andric   unsigned NumOperandsToProcess = MI.getNumOperands();
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric   // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
4890b57cec5SDimitry Andric   // of the uses.  They will be handled in other basic blocks.
4900b57cec5SDimitry Andric   if (MI.isPHI())
4910b57cec5SDimitry Andric     NumOperandsToProcess = 1;
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // Clear kill and dead markers. LV will recompute them.
4940b57cec5SDimitry Andric   SmallVector<unsigned, 4> UseRegs;
4950b57cec5SDimitry Andric   SmallVector<unsigned, 4> DefRegs;
4960b57cec5SDimitry Andric   SmallVector<unsigned, 1> RegMasks;
4970b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
4980b57cec5SDimitry Andric     MachineOperand &MO = MI.getOperand(i);
4990b57cec5SDimitry Andric     if (MO.isRegMask()) {
5000b57cec5SDimitry Andric       RegMasks.push_back(i);
5010b57cec5SDimitry Andric       continue;
5020b57cec5SDimitry Andric     }
5030b57cec5SDimitry Andric     if (!MO.isReg() || MO.getReg() == 0)
5040b57cec5SDimitry Andric       continue;
5058bcb0991SDimitry Andric     Register MOReg = MO.getReg();
5060b57cec5SDimitry Andric     if (MO.isUse()) {
507bdd1243dSDimitry Andric       if (!(MOReg.isPhysical() && MRI->isReserved(MOReg)))
5080b57cec5SDimitry Andric         MO.setIsKill(false);
5090b57cec5SDimitry Andric       if (MO.readsReg())
5100b57cec5SDimitry Andric         UseRegs.push_back(MOReg);
5110b57cec5SDimitry Andric     } else {
5120b57cec5SDimitry Andric       assert(MO.isDef());
5130b57cec5SDimitry Andric       // FIXME: We should not remove any dead flags. However the MIPS RDDSP
5140b57cec5SDimitry Andric       // instruction needs it at the moment: http://llvm.org/PR27116.
515bdd1243dSDimitry Andric       if (MOReg.isPhysical() && !MRI->isReserved(MOReg))
5160b57cec5SDimitry Andric         MO.setIsDead(false);
5170b57cec5SDimitry Andric       DefRegs.push_back(MOReg);
5180b57cec5SDimitry Andric     }
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
5220b57cec5SDimitry Andric   // Process all uses.
5230eae32dcSDimitry Andric   for (unsigned MOReg : UseRegs) {
5248bcb0991SDimitry Andric     if (Register::isVirtualRegister(MOReg))
5250b57cec5SDimitry Andric       HandleVirtRegUse(MOReg, MBB, MI);
5260b57cec5SDimitry Andric     else if (!MRI->isReserved(MOReg))
5270b57cec5SDimitry Andric       HandlePhysRegUse(MOReg, MI);
5280b57cec5SDimitry Andric   }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   // Process all masked registers. (Call clobbers).
5310eae32dcSDimitry Andric   for (unsigned Mask : RegMasks)
532*c9157d92SDimitry Andric     HandleRegMask(MI.getOperand(Mask), NumRegs);
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // Process all defs.
5350eae32dcSDimitry Andric   for (unsigned MOReg : DefRegs) {
5368bcb0991SDimitry Andric     if (Register::isVirtualRegister(MOReg))
5370b57cec5SDimitry Andric       HandleVirtRegDef(MOReg, MI);
5380b57cec5SDimitry Andric     else if (!MRI->isReserved(MOReg))
5390b57cec5SDimitry Andric       HandlePhysRegDef(MOReg, &MI, Defs);
5400b57cec5SDimitry Andric   }
5410b57cec5SDimitry Andric   UpdatePhysRegDefs(MI, Defs);
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
runOnBlock(MachineBasicBlock * MBB,unsigned NumRegs)544*c9157d92SDimitry Andric void LiveVariables::runOnBlock(MachineBasicBlock *MBB, unsigned NumRegs) {
5450b57cec5SDimitry Andric   // Mark live-in registers as live-in.
5460b57cec5SDimitry Andric   SmallVector<unsigned, 4> Defs;
5470b57cec5SDimitry Andric   for (const auto &LI : MBB->liveins()) {
5488bcb0991SDimitry Andric     assert(Register::isPhysicalRegister(LI.PhysReg) &&
5490b57cec5SDimitry Andric            "Cannot have a live-in virtual register!");
5500b57cec5SDimitry Andric     HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
5510b57cec5SDimitry Andric   }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   // Loop over all of the instructions, processing them.
5540b57cec5SDimitry Andric   DistanceMap.clear();
5550b57cec5SDimitry Andric   unsigned Dist = 0;
5560b57cec5SDimitry Andric   for (MachineInstr &MI : *MBB) {
557fe6060f1SDimitry Andric     if (MI.isDebugOrPseudoInstr())
5580b57cec5SDimitry Andric       continue;
5590b57cec5SDimitry Andric     DistanceMap.insert(std::make_pair(&MI, Dist++));
5600b57cec5SDimitry Andric 
561*c9157d92SDimitry Andric     runOnInstr(MI, Defs, NumRegs);
5620b57cec5SDimitry Andric   }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   // Handle any virtual assignments from PHI nodes which might be at the
5650b57cec5SDimitry Andric   // bottom of this basic block.  We check all of our successor blocks to see
5660b57cec5SDimitry Andric   // if they have PHI nodes, and if so, we simulate an assignment at the end
5670b57cec5SDimitry Andric   // of the current block.
5680b57cec5SDimitry Andric   if (!PHIVarInfo[MBB->getNumber()].empty()) {
5690b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
5700b57cec5SDimitry Andric 
571fe6060f1SDimitry Andric     for (unsigned I : VarInfoVec)
5720b57cec5SDimitry Andric       // Mark it alive only in the block we are representing.
573fe6060f1SDimitry Andric       MarkVirtRegAliveInBlock(getVarInfo(I), MRI->getVRegDef(I)->getParent(),
5740b57cec5SDimitry Andric                               MBB);
5750b57cec5SDimitry Andric   }
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // MachineCSE may CSE instructions which write to non-allocatable physical
5780b57cec5SDimitry Andric   // registers across MBBs. Remember if any reserved register is liveout.
5790b57cec5SDimitry Andric   SmallSet<unsigned, 4> LiveOuts;
580fe6060f1SDimitry Andric   for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
5810b57cec5SDimitry Andric     if (SuccMBB->isEHPad())
5820b57cec5SDimitry Andric       continue;
5830b57cec5SDimitry Andric     for (const auto &LI : SuccMBB->liveins()) {
5840b57cec5SDimitry Andric       if (!TRI->isInAllocatableClass(LI.PhysReg))
5850b57cec5SDimitry Andric         // Ignore other live-ins, e.g. those that are live into landing pads.
5860b57cec5SDimitry Andric         LiveOuts.insert(LI.PhysReg);
5870b57cec5SDimitry Andric     }
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   // Loop over PhysRegDef / PhysRegUse, killing any registers that are
5910b57cec5SDimitry Andric   // available at the end of the basic block.
5920b57cec5SDimitry Andric   for (unsigned i = 0; i != NumRegs; ++i)
5930b57cec5SDimitry Andric     if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
5940b57cec5SDimitry Andric       HandlePhysRegDef(i, nullptr, Defs);
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & mf)5970b57cec5SDimitry Andric bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
5980b57cec5SDimitry Andric   MF = &mf;
5990b57cec5SDimitry Andric   MRI = &mf.getRegInfo();
6000b57cec5SDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
6010b57cec5SDimitry Andric 
602*c9157d92SDimitry Andric   const unsigned NumRegs = TRI->getNumSupportedRegs(mf);
6030b57cec5SDimitry Andric   PhysRegDef.assign(NumRegs, nullptr);
6040b57cec5SDimitry Andric   PhysRegUse.assign(NumRegs, nullptr);
6050b57cec5SDimitry Andric   PHIVarInfo.resize(MF->getNumBlockIDs());
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   // FIXME: LiveIntervals will be updated to remove its dependence on
6080b57cec5SDimitry Andric   // LiveVariables to improve compilation time and eliminate bizarre pass
6090b57cec5SDimitry Andric   // dependencies. Until then, we can't change much in -O0.
6100b57cec5SDimitry Andric   if (!MRI->isSSA())
6110b57cec5SDimitry Andric     report_fatal_error("regalloc=... not currently supported with -O0");
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   analyzePHINodes(mf);
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   // Calculate live variable information in depth first order on the CFG of the
6160b57cec5SDimitry Andric   // function.  This guarantees that we will see the definition of a virtual
6170b57cec5SDimitry Andric   // register before its uses due to dominance properties of SSA (except for PHI
6180b57cec5SDimitry Andric   // nodes, which are treated as a special case).
6190b57cec5SDimitry Andric   MachineBasicBlock *Entry = &MF->front();
6200b57cec5SDimitry Andric   df_iterator_default_set<MachineBasicBlock*,16> Visited;
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
6230b57cec5SDimitry Andric     runOnBlock(MBB, NumRegs);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     PhysRegDef.assign(NumRegs, nullptr);
6260b57cec5SDimitry Andric     PhysRegUse.assign(NumRegs, nullptr);
6270b57cec5SDimitry Andric   }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   // Convert and transfer the dead / killed information we have gathered into
6300b57cec5SDimitry Andric   // VirtRegInfo onto MI's.
6310b57cec5SDimitry Andric   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
632e8d8bef9SDimitry Andric     const Register Reg = Register::index2VirtReg(i);
6330b57cec5SDimitry Andric     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
6340b57cec5SDimitry Andric       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
6350b57cec5SDimitry Andric         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
6360b57cec5SDimitry Andric       else
6370b57cec5SDimitry Andric         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Check to make sure there are no unreachable blocks in the MC CFG for the
6410b57cec5SDimitry Andric   // function.  If so, it is due to a bug in the instruction selector or some
6420b57cec5SDimitry Andric   // other part of the code generator if this happens.
6430b57cec5SDimitry Andric #ifndef NDEBUG
644fe6060f1SDimitry Andric   for (const MachineBasicBlock &MBB : *MF)
645fe6060f1SDimitry Andric     assert(Visited.contains(&MBB) && "unreachable basic block found");
6460b57cec5SDimitry Andric #endif
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   PhysRegDef.clear();
6490b57cec5SDimitry Andric   PhysRegUse.clear();
6500b57cec5SDimitry Andric   PHIVarInfo.clear();
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   return false;
6530b57cec5SDimitry Andric }
6540b57cec5SDimitry Andric 
recomputeForSingleDefVirtReg(Register Reg)655349cc55cSDimitry Andric void LiveVariables::recomputeForSingleDefVirtReg(Register Reg) {
656349cc55cSDimitry Andric   assert(Reg.isVirtual());
657349cc55cSDimitry Andric 
658349cc55cSDimitry Andric   VarInfo &VI = getVarInfo(Reg);
659349cc55cSDimitry Andric   VI.AliveBlocks.clear();
660349cc55cSDimitry Andric   VI.Kills.clear();
661349cc55cSDimitry Andric 
662349cc55cSDimitry Andric   MachineInstr &DefMI = *MRI->getUniqueVRegDef(Reg);
663349cc55cSDimitry Andric   MachineBasicBlock &DefBB = *DefMI.getParent();
664349cc55cSDimitry Andric 
665349cc55cSDimitry Andric   // Initialize a worklist of BBs that Reg is live-to-end of. (Here
666349cc55cSDimitry Andric   // "live-to-end" means Reg is live at the end of a block even if it is only
667349cc55cSDimitry Andric   // live because of phi uses in a successor. This is different from isLiveOut()
668349cc55cSDimitry Andric   // which does not consider phi uses.)
669349cc55cSDimitry Andric   SmallVector<MachineBasicBlock *> LiveToEndBlocks;
670349cc55cSDimitry Andric   SparseBitVector<> UseBlocks;
671*c9157d92SDimitry Andric   unsigned NumRealUses = 0;
672349cc55cSDimitry Andric   for (auto &UseMO : MRI->use_nodbg_operands(Reg)) {
673349cc55cSDimitry Andric     UseMO.setIsKill(false);
674*c9157d92SDimitry Andric     if (!UseMO.readsReg())
675*c9157d92SDimitry Andric       continue;
676*c9157d92SDimitry Andric     ++NumRealUses;
677349cc55cSDimitry Andric     MachineInstr &UseMI = *UseMO.getParent();
678349cc55cSDimitry Andric     MachineBasicBlock &UseBB = *UseMI.getParent();
679349cc55cSDimitry Andric     UseBlocks.set(UseBB.getNumber());
680349cc55cSDimitry Andric     if (UseMI.isPHI()) {
681349cc55cSDimitry Andric       // If Reg is used in a phi then it is live-to-end of the corresponding
682349cc55cSDimitry Andric       // predecessor.
683fe013be4SDimitry Andric       unsigned Idx = UseMO.getOperandNo();
684349cc55cSDimitry Andric       LiveToEndBlocks.push_back(UseMI.getOperand(Idx + 1).getMBB());
685349cc55cSDimitry Andric     } else if (&UseBB == &DefBB) {
686349cc55cSDimitry Andric       // A non-phi use in the same BB as the single def must come after the def.
687349cc55cSDimitry Andric     } else {
688349cc55cSDimitry Andric       // Otherwise Reg must be live-to-end of all predecessors.
689349cc55cSDimitry Andric       LiveToEndBlocks.append(UseBB.pred_begin(), UseBB.pred_end());
690349cc55cSDimitry Andric     }
691349cc55cSDimitry Andric   }
692349cc55cSDimitry Andric 
693*c9157d92SDimitry Andric   // Handle the case where all uses have been removed.
694*c9157d92SDimitry Andric   if (NumRealUses == 0) {
695*c9157d92SDimitry Andric     VI.Kills.push_back(&DefMI);
696*c9157d92SDimitry Andric     DefMI.addRegisterDead(Reg, nullptr);
697*c9157d92SDimitry Andric     return;
698*c9157d92SDimitry Andric   }
699*c9157d92SDimitry Andric   DefMI.clearRegisterDeads(Reg);
700*c9157d92SDimitry Andric 
701349cc55cSDimitry Andric   // Iterate over the worklist adding blocks to AliveBlocks.
702349cc55cSDimitry Andric   bool LiveToEndOfDefBB = false;
703349cc55cSDimitry Andric   while (!LiveToEndBlocks.empty()) {
704349cc55cSDimitry Andric     MachineBasicBlock &BB = *LiveToEndBlocks.pop_back_val();
705349cc55cSDimitry Andric     if (&BB == &DefBB) {
706349cc55cSDimitry Andric       LiveToEndOfDefBB = true;
707349cc55cSDimitry Andric       continue;
708349cc55cSDimitry Andric     }
709349cc55cSDimitry Andric     if (VI.AliveBlocks.test(BB.getNumber()))
710349cc55cSDimitry Andric       continue;
711349cc55cSDimitry Andric     VI.AliveBlocks.set(BB.getNumber());
712349cc55cSDimitry Andric     LiveToEndBlocks.append(BB.pred_begin(), BB.pred_end());
713349cc55cSDimitry Andric   }
714349cc55cSDimitry Andric 
715349cc55cSDimitry Andric   // Recompute kill flags. For each block in which Reg is used but is not
716349cc55cSDimitry Andric   // live-through, find the last instruction that uses Reg. Ignore phi nodes
717349cc55cSDimitry Andric   // because they should not be included in Kills.
718349cc55cSDimitry Andric   for (unsigned UseBBNum : UseBlocks) {
719349cc55cSDimitry Andric     if (VI.AliveBlocks.test(UseBBNum))
720349cc55cSDimitry Andric       continue;
721349cc55cSDimitry Andric     MachineBasicBlock &UseBB = *MF->getBlockNumbered(UseBBNum);
722349cc55cSDimitry Andric     if (&UseBB == &DefBB && LiveToEndOfDefBB)
723349cc55cSDimitry Andric       continue;
724349cc55cSDimitry Andric     for (auto &MI : reverse(UseBB)) {
725349cc55cSDimitry Andric       if (MI.isDebugOrPseudoInstr())
726349cc55cSDimitry Andric         continue;
727349cc55cSDimitry Andric       if (MI.isPHI())
728349cc55cSDimitry Andric         break;
729*c9157d92SDimitry Andric       if (MI.readsVirtualRegister(Reg)) {
730349cc55cSDimitry Andric         assert(!MI.killsRegister(Reg));
731349cc55cSDimitry Andric         MI.addRegisterKilled(Reg, nullptr);
732349cc55cSDimitry Andric         VI.Kills.push_back(&MI);
733349cc55cSDimitry Andric         break;
734349cc55cSDimitry Andric       }
735349cc55cSDimitry Andric     }
736349cc55cSDimitry Andric   }
737349cc55cSDimitry Andric }
738349cc55cSDimitry Andric 
7390b57cec5SDimitry Andric /// replaceKillInstruction - Update register kill info by replacing a kill
7400b57cec5SDimitry Andric /// instruction with a new one.
replaceKillInstruction(Register Reg,MachineInstr & OldMI,MachineInstr & NewMI)741e8d8bef9SDimitry Andric void LiveVariables::replaceKillInstruction(Register Reg, MachineInstr &OldMI,
7420b57cec5SDimitry Andric                                            MachineInstr &NewMI) {
7430b57cec5SDimitry Andric   VarInfo &VI = getVarInfo(Reg);
7440b57cec5SDimitry Andric   std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
7450b57cec5SDimitry Andric }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric /// removeVirtualRegistersKilled - Remove all killed info for the specified
7480b57cec5SDimitry Andric /// instruction.
removeVirtualRegistersKilled(MachineInstr & MI)7490b57cec5SDimitry Andric void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
750fcaf7f86SDimitry Andric   for (MachineOperand &MO : MI.operands()) {
7510b57cec5SDimitry Andric     if (MO.isReg() && MO.isKill()) {
7520b57cec5SDimitry Andric       MO.setIsKill(false);
7538bcb0991SDimitry Andric       Register Reg = MO.getReg();
754bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
7550b57cec5SDimitry Andric         bool removed = getVarInfo(Reg).removeKill(MI);
7560b57cec5SDimitry Andric         assert(removed && "kill not in register's VarInfo?");
7570b57cec5SDimitry Andric         (void)removed;
7580b57cec5SDimitry Andric       }
7590b57cec5SDimitry Andric     }
7600b57cec5SDimitry Andric   }
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric /// analyzePHINodes - Gather information about the PHI nodes in here. In
7640b57cec5SDimitry Andric /// particular, we want to map the variable information of a virtual register
7650b57cec5SDimitry Andric /// which is used in a PHI node. We map that to the BB the vreg is coming from.
7660b57cec5SDimitry Andric ///
analyzePHINodes(const MachineFunction & Fn)7670b57cec5SDimitry Andric void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
7680b57cec5SDimitry Andric   for (const auto &MBB : Fn)
7690b57cec5SDimitry Andric     for (const auto &BBI : MBB) {
7700b57cec5SDimitry Andric       if (!BBI.isPHI())
7710b57cec5SDimitry Andric         break;
7720b57cec5SDimitry Andric       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
7730b57cec5SDimitry Andric         if (BBI.getOperand(i).readsReg())
7740b57cec5SDimitry Andric           PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
7750b57cec5SDimitry Andric             .push_back(BBI.getOperand(i).getReg());
7760b57cec5SDimitry Andric     }
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric 
isLiveIn(const MachineBasicBlock & MBB,Register Reg,MachineRegisterInfo & MRI)7790b57cec5SDimitry Andric bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
780e8d8bef9SDimitry Andric                                       Register Reg, MachineRegisterInfo &MRI) {
7810b57cec5SDimitry Andric   unsigned Num = MBB.getNumber();
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   // Reg is live-through.
7840b57cec5SDimitry Andric   if (AliveBlocks.test(Num))
7850b57cec5SDimitry Andric     return true;
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric   // Registers defined in MBB cannot be live in.
7880b57cec5SDimitry Andric   const MachineInstr *Def = MRI.getVRegDef(Reg);
7890b57cec5SDimitry Andric   if (Def && Def->getParent() == &MBB)
7900b57cec5SDimitry Andric     return false;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric  // Reg was not defined in MBB, was it killed here?
7930b57cec5SDimitry Andric   return findKill(&MBB);
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
isLiveOut(Register Reg,const MachineBasicBlock & MBB)796e8d8bef9SDimitry Andric bool LiveVariables::isLiveOut(Register Reg, const MachineBasicBlock &MBB) {
7970b57cec5SDimitry Andric   LiveVariables::VarInfo &VI = getVarInfo(Reg);
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> Kills;
8004824e7fdSDimitry Andric   for (MachineInstr *MI : VI.Kills)
8014824e7fdSDimitry Andric     Kills.insert(MI->getParent());
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // Loop over all of the successors of the basic block, checking to see if
8040b57cec5SDimitry Andric   // the value is either live in the block, or if it is killed in the block.
8050b57cec5SDimitry Andric   for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
8060b57cec5SDimitry Andric     // Is it alive in this successor?
8070b57cec5SDimitry Andric     unsigned SuccIdx = SuccMBB->getNumber();
8080b57cec5SDimitry Andric     if (VI.AliveBlocks.test(SuccIdx))
8090b57cec5SDimitry Andric       return true;
8100b57cec5SDimitry Andric     // Or is it live because there is a use in a successor that kills it?
8110b57cec5SDimitry Andric     if (Kills.count(SuccMBB))
8120b57cec5SDimitry Andric       return true;
8130b57cec5SDimitry Andric   }
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   return false;
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
8190b57cec5SDimitry Andric /// variables that are live out of DomBB will be marked as passing live through
8200b57cec5SDimitry Andric /// BB.
addNewBlock(MachineBasicBlock * BB,MachineBasicBlock * DomBB,MachineBasicBlock * SuccBB)8210b57cec5SDimitry Andric void LiveVariables::addNewBlock(MachineBasicBlock *BB,
8220b57cec5SDimitry Andric                                 MachineBasicBlock *DomBB,
8230b57cec5SDimitry Andric                                 MachineBasicBlock *SuccBB) {
8240b57cec5SDimitry Andric   const unsigned NumNew = BB->getNumber();
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   DenseSet<unsigned> Defs, Kills;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
8290b57cec5SDimitry Andric   for (; BBI != BBE && BBI->isPHI(); ++BBI) {
8300b57cec5SDimitry Andric     // Record the def of the PHI node.
8310b57cec5SDimitry Andric     Defs.insert(BBI->getOperand(0).getReg());
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric     // All registers used by PHI nodes in SuccBB must be live through BB.
8340b57cec5SDimitry Andric     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
8350b57cec5SDimitry Andric       if (BBI->getOperand(i+1).getMBB() == BB)
8360b57cec5SDimitry Andric         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
8370b57cec5SDimitry Andric   }
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // Record all vreg defs and kills of all instructions in SuccBB.
8400b57cec5SDimitry Andric   for (; BBI != BBE; ++BBI) {
841fe6060f1SDimitry Andric     for (const MachineOperand &Op : BBI->operands()) {
842bdd1243dSDimitry Andric       if (Op.isReg() && Op.getReg().isVirtual()) {
843fe6060f1SDimitry Andric         if (Op.isDef())
844fe6060f1SDimitry Andric           Defs.insert(Op.getReg());
845fe6060f1SDimitry Andric         else if (Op.isKill())
846fe6060f1SDimitry Andric           Kills.insert(Op.getReg());
8470b57cec5SDimitry Andric       }
8480b57cec5SDimitry Andric     }
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   // Update info for all live variables
8520b57cec5SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
853e8d8bef9SDimitry Andric     Register Reg = Register::index2VirtReg(i);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     // If the Defs is defined in the successor it can't be live in BB.
8560b57cec5SDimitry Andric     if (Defs.count(Reg))
8570b57cec5SDimitry Andric       continue;
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     // If the register is either killed in or live through SuccBB it's also live
8600b57cec5SDimitry Andric     // through BB.
8610b57cec5SDimitry Andric     VarInfo &VI = getVarInfo(Reg);
8620b57cec5SDimitry Andric     if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
8630b57cec5SDimitry Andric       VI.AliveBlocks.set(NumNew);
8640b57cec5SDimitry Andric   }
8650b57cec5SDimitry Andric }
8665ffd83dbSDimitry Andric 
8675ffd83dbSDimitry Andric /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
8685ffd83dbSDimitry Andric /// variables that are live out of DomBB will be marked as passing live through
8695ffd83dbSDimitry Andric /// BB. LiveInSets[BB] is *not* updated (because it is not needed during
8705ffd83dbSDimitry Andric /// PHIElimination).
addNewBlock(MachineBasicBlock * BB,MachineBasicBlock * DomBB,MachineBasicBlock * SuccBB,std::vector<SparseBitVector<>> & LiveInSets)8715ffd83dbSDimitry Andric void LiveVariables::addNewBlock(MachineBasicBlock *BB,
8725ffd83dbSDimitry Andric                                 MachineBasicBlock *DomBB,
8735ffd83dbSDimitry Andric                                 MachineBasicBlock *SuccBB,
8745ffd83dbSDimitry Andric                                 std::vector<SparseBitVector<>> &LiveInSets) {
8755ffd83dbSDimitry Andric   const unsigned NumNew = BB->getNumber();
8765ffd83dbSDimitry Andric 
8775ffd83dbSDimitry Andric   SparseBitVector<> &BV = LiveInSets[SuccBB->getNumber()];
878fe6060f1SDimitry Andric   for (unsigned R : BV) {
879fe6060f1SDimitry Andric     Register VirtReg = Register::index2VirtReg(R);
8805ffd83dbSDimitry Andric     LiveVariables::VarInfo &VI = getVarInfo(VirtReg);
8815ffd83dbSDimitry Andric     VI.AliveBlocks.set(NumNew);
8825ffd83dbSDimitry Andric   }
8835ffd83dbSDimitry Andric   // All registers used by PHI nodes in SuccBB must be live through BB.
8845ffd83dbSDimitry Andric   for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
8855ffd83dbSDimitry Andric          BBE = SuccBB->end();
8865ffd83dbSDimitry Andric        BBI != BBE && BBI->isPHI(); ++BBI) {
8875ffd83dbSDimitry Andric     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
8885ffd83dbSDimitry Andric       if (BBI->getOperand(i + 1).getMBB() == BB &&
8895ffd83dbSDimitry Andric           BBI->getOperand(i).readsReg())
8905ffd83dbSDimitry Andric         getVarInfo(BBI->getOperand(i).getReg())
8915ffd83dbSDimitry Andric           .AliveBlocks.set(NumNew);
8925ffd83dbSDimitry Andric   }
8935ffd83dbSDimitry Andric }
894