1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
3 // This file implements the LiveVariable analysis pass. For each machine
4 // instruction in the function, this pass calculates the set of registers that
5 // are immediately dead after the instruction (i.e., the instruction calculates
6 // the value, but it is never used) and the set of registers that are used by
7 // the instruction, but are never used after the instruction (i.e., they are
10 // This class computes live variables using are sparse implementation based on
11 // the machine code SSA form. This class computes live variable information for
12 // each virtual and _register allocatable_ physical register in a function. It
13 // uses the dominance properties of SSA form to efficiently compute live
14 // variables for virtual registers, and assumes that physical registers are only
15 // live within a single basic block (allowing it to do a single local analysis
16 // to resolve physical register lifetimes in each basic block). If a physical
17 // register is not register allocatable, it is not tracked. This is useful for
18 // things like the stack pointer and condition codes.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CFG.h"
27 #include "Support/DepthFirstIterator.h"
29 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
31 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
32 const BasicBlock *BB) {
33 const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
34 MachineBasicBlock *MBB = Info.first;
35 unsigned BBNum = Info.second;
37 // Check to see if this basic block is one of the killing blocks. If so,
39 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
40 if (VRInfo.Kills[i].first == MBB) {
41 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
45 if (MBB == VRInfo.DefBlock) return; // Terminate recursion
47 if (VRInfo.AliveBlocks.size() <= BBNum)
48 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
50 if (VRInfo.AliveBlocks[BBNum])
51 return; // We already know the block is live
53 // Mark the variable known alive in this bb
54 VRInfo.AliveBlocks[BBNum] = true;
56 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
57 MarkVirtRegAliveInBlock(VRInfo, *PI);
60 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
62 // Check to see if this basic block is already a kill block...
63 if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
64 // Yes, this register is killed in this basic block already. Increase the
65 // live range by updating the kill instruction.
66 VRInfo.Kills.back().second = MI;
71 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
72 assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
75 assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
77 // Add a new kill entry for this basic block.
78 VRInfo.Kills.push_back(std::make_pair(MBB, MI));
80 // Update all dominating blocks to mark them known live.
81 const BasicBlock *BB = MBB->getBasicBlock();
82 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
84 MarkVirtRegAliveInBlock(VRInfo, *PI);
87 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
88 if (PhysRegInfo[Reg]) {
89 PhysRegInfo[Reg] = MI;
90 PhysRegUsed[Reg] = true;
91 } else if (const unsigned *AliasSet = RegInfo->getAliasSet(Reg)) {
92 for (; unsigned NReg = AliasSet[0]; ++AliasSet)
93 if (MachineInstr *LastUse = PhysRegInfo[NReg]) {
94 PhysRegInfo[NReg] = MI;
95 PhysRegUsed[NReg] = true;
100 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
101 // Does this kill a previous version of this register?
102 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
103 if (PhysRegUsed[Reg])
104 RegistersKilled.insert(std::make_pair(LastUse, Reg));
106 RegistersDead.insert(std::make_pair(LastUse, Reg));
107 } else if (const unsigned *AliasSet = RegInfo->getAliasSet(Reg)) {
108 for (; unsigned NReg = AliasSet[0]; ++AliasSet)
109 if (MachineInstr *LastUse = PhysRegInfo[NReg]) {
110 if (PhysRegUsed[NReg])
111 RegistersKilled.insert(std::make_pair(LastUse, NReg));
113 RegistersDead.insert(std::make_pair(LastUse, NReg));
114 PhysRegInfo[NReg] = 0; // Kill the aliased register
117 PhysRegInfo[Reg] = MI;
118 PhysRegUsed[Reg] = false;
121 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
122 // First time though, initialize AllocatablePhysicalRegisters for the target
123 if (AllocatablePhysicalRegisters.empty()) {
124 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
125 assert(&MRI && "Target doesn't have register information?");
127 // Make space, initializing to false...
128 AllocatablePhysicalRegisters.resize(MRegisterInfo::FirstVirtualRegister);
130 // Loop over all of the register classes...
131 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
132 E = MRI.regclass_end(); RCI != E; ++RCI)
133 // Loop over all of the allocatable registers in the function...
134 for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
135 E = (*RCI)->allocation_order_end(MF); I != E; ++I)
136 AllocatablePhysicalRegisters[*I] = true; // The reg is allocatable!
141 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
142 BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
144 // PhysRegInfo - Keep track of which instruction was the last use of a
145 // physical register. This is a purely local property, because all physical
146 // register references as presumed dead across basic blocks.
148 MachineInstr *PhysRegInfoA[MRegisterInfo::FirstVirtualRegister];
149 bool PhysRegUsedA[MRegisterInfo::FirstVirtualRegister];
150 std::fill(PhysRegInfoA, PhysRegInfoA+MRegisterInfo::FirstVirtualRegister,
152 PhysRegInfo = PhysRegInfoA;
153 PhysRegUsed = PhysRegUsedA;
155 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
156 RegInfo = MF.getTarget().getRegisterInfo();
158 /// Get some space for a respectable number of registers...
159 VirtRegInfo.resize(64);
161 // Calculate live variable information in depth first order on the CFG of the
162 // function. This guarantees that we will see the definition of a virtual
163 // register before its uses due to dominance properties of SSA (except for PHI
164 // nodes, which are treated as a special case).
166 const BasicBlock *Entry = MF.getFunction()->begin();
167 for (df_iterator<const BasicBlock*> DFI = df_begin(Entry), E = df_end(Entry);
169 const BasicBlock *BB = *DFI;
170 std::pair<MachineBasicBlock*, unsigned> &BBRec = BBMap.find(BB)->second;
171 MachineBasicBlock *MBB = BBRec.first;
172 unsigned BBNum = BBRec.second;
174 // Loop over all of the instructions, processing them.
175 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
177 MachineInstr *MI = *I;
178 const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
180 // Process all of the operands of the instruction...
181 unsigned NumOperandsToProcess = MI->getNumOperands();
183 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
184 // of the uses. They will be handled in other basic blocks.
185 if (MI->getOpcode() == TargetInstrInfo::PHI)
186 NumOperandsToProcess = 1;
188 // Loop over implicit uses, using them.
189 if (const unsigned *ImplicitUses = MID.ImplicitUses)
190 for (unsigned i = 0; ImplicitUses[i]; ++i)
191 HandlePhysRegUse(ImplicitUses[i], MI);
193 // Process all explicit uses...
194 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
195 MachineOperand &MO = MI->getOperand(i);
196 if (MO.opIsUse() || MO.opIsDefAndUse()) {
197 if (MO.isVirtualRegister() && !MO.getVRegValueOrNull()) {
198 unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
199 HandleVirtRegUse(getVarInfo(RegIdx), MBB, MI);
200 } else if (MO.isPhysicalRegister() &&
201 AllocatablePhysicalRegisters[MO.getReg()]) {
202 HandlePhysRegUse(MO.getReg(), MI);
207 // Loop over implicit defs, defining them.
208 if (const unsigned *ImplicitDefs = MID.ImplicitDefs)
209 for (unsigned i = 0; ImplicitDefs[i]; ++i)
210 HandlePhysRegDef(ImplicitDefs[i], MI);
212 // Process all explicit defs...
213 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
214 MachineOperand &MO = MI->getOperand(i);
215 if (MO.opIsDef() || MO.opIsDefAndUse()) {
216 if (MO.isVirtualRegister()) {
217 unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
218 VarInfo &VRInfo = getVarInfo(RegIdx);
220 assert(VRInfo.DefBlock == 0 && "Variable multiply defined!");
221 VRInfo.DefBlock = MBB; // Created here...
223 VRInfo.Kills.push_back(std::make_pair(MBB, MI)); // Defaults to dead
224 } else if (MO.isPhysicalRegister() &&
225 AllocatablePhysicalRegisters[MO.getReg()]) {
226 HandlePhysRegDef(MO.getReg(), MI);
232 // Handle any virtual assignments from PHI nodes which might be at the
233 // bottom of this basic block. We check all of our successor blocks to see
234 // if they have PHI nodes, and if so, we simulate an assignment at the end
235 // of the current block.
236 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB);
238 MachineBasicBlock *Succ = BBMap.find(*SI)->second.first;
240 // PHI nodes are guaranteed to be at the top of the block...
241 for (MachineBasicBlock::iterator I = Succ->begin(), E = Succ->end();
242 I != E && (*I)->getOpcode() == TargetInstrInfo::PHI; ++I) {
243 MachineInstr *MI = *I;
244 for (unsigned i = 1; ; i += 2)
245 if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
246 MachineOperand &MO = MI->getOperand(i);
247 if (!MO.getVRegValueOrNull()) {
248 unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
249 VarInfo &VRInfo = getVarInfo(RegIdx);
251 // Only mark it alive only in the block we are representing...
252 MarkVirtRegAliveInBlock(VRInfo, BB);
253 break; // Found the PHI entry for this block...
259 // Loop over PhysRegInfo, killing any registers that are available at the
260 // end of the basic block. This also resets the PhysRegInfo map.
261 for (unsigned i = 0, e = MRegisterInfo::FirstVirtualRegister; i != e; ++i)
263 HandlePhysRegDef(i, 0);
268 // Convert the information we have gathered into VirtRegInfo and transform it
269 // into a form usable by RegistersKilled.
271 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
272 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
273 if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
274 RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
275 i + MRegisterInfo::FirstVirtualRegister));
278 RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
279 i + MRegisterInfo::FirstVirtualRegister));