1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
17 // This class computes live variables using are sparse implementation based on
18 // the machine code SSA form. This class computes live variable information for
19 // each virtual and _register allocatable_ physical register in a function. It
20 // uses the dominance properties of SSA form to efficiently compute live
21 // variables for virtual registers, and assumes that physical registers are only
22 // live within a single basic block (allowing it to do a single local analysis
23 // to resolve physical register lifetimes in each basic block). If a physical
24 // register is not register allocatable, it is not tracked. This is useful for
25 // things like the stack pointer and condition codes.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/CodeGen/LiveVariables.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/CFG.h"
34 #include "Support/DepthFirstIterator.h"
38 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
40 const std::pair<MachineBasicBlock*, unsigned> &
41 LiveVariables::getMachineBasicBlockInfo(MachineBasicBlock *MBB) const{
42 return BBMap.find(MBB->getBasicBlock())->second;
45 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
46 assert(RegIdx >= MRegisterInfo::FirstVirtualRegister &&
47 "getVarInfo: not a virtual register!");
48 RegIdx -= MRegisterInfo::FirstVirtualRegister;
49 if (RegIdx >= VirtRegInfo.size()) {
50 if (RegIdx >= 2*VirtRegInfo.size())
51 VirtRegInfo.resize(RegIdx*2);
53 VirtRegInfo.resize(2*VirtRegInfo.size());
55 return VirtRegInfo[RegIdx];
60 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
61 const BasicBlock *BB) {
62 const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
63 MachineBasicBlock *MBB = Info.first;
64 unsigned BBNum = Info.second;
66 // Check to see if this basic block is one of the killing blocks. If so,
68 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
69 if (VRInfo.Kills[i].first == MBB) {
70 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
74 if (MBB == VRInfo.DefBlock) return; // Terminate recursion
76 if (VRInfo.AliveBlocks.size() <= BBNum)
77 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
79 if (VRInfo.AliveBlocks[BBNum])
80 return; // We already know the block is live
82 // Mark the variable known alive in this bb
83 VRInfo.AliveBlocks[BBNum] = true;
85 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
86 MarkVirtRegAliveInBlock(VRInfo, *PI);
89 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
91 // Check to see if this basic block is already a kill block...
92 if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
93 // Yes, this register is killed in this basic block already. Increase the
94 // live range by updating the kill instruction.
95 VRInfo.Kills.back().second = MI;
100 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
101 assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
104 assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
106 // Add a new kill entry for this basic block.
107 VRInfo.Kills.push_back(std::make_pair(MBB, MI));
109 // Update all dominating blocks to mark them known live.
110 const BasicBlock *BB = MBB->getBasicBlock();
111 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
113 MarkVirtRegAliveInBlock(VRInfo, *PI);
116 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
117 PhysRegInfo[Reg] = MI;
118 PhysRegUsed[Reg] = true;
121 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
122 // Does this kill a previous version of this register?
123 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
124 if (PhysRegUsed[Reg])
125 RegistersKilled.insert(std::make_pair(LastUse, Reg));
127 RegistersDead.insert(std::make_pair(LastUse, Reg));
129 PhysRegInfo[Reg] = MI;
130 PhysRegUsed[Reg] = false;
132 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
133 *AliasSet; ++AliasSet) {
134 if (MachineInstr *LastUse = PhysRegInfo[*AliasSet]) {
135 if (PhysRegUsed[*AliasSet])
136 RegistersKilled.insert(std::make_pair(LastUse, *AliasSet));
138 RegistersDead.insert(std::make_pair(LastUse, *AliasSet));
140 PhysRegInfo[*AliasSet] = MI;
141 PhysRegUsed[*AliasSet] = false;
145 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
146 // First time though, initialize AllocatablePhysicalRegisters for the target
147 if (AllocatablePhysicalRegisters.empty()) {
148 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
149 assert(&MRI && "Target doesn't have register information?");
151 // Make space, initializing to false...
152 AllocatablePhysicalRegisters.resize(MRegisterInfo::FirstVirtualRegister);
154 // Loop over all of the register classes...
155 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
156 E = MRI.regclass_end(); RCI != E; ++RCI)
157 // Loop over all of the allocatable registers in the function...
158 for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
159 E = (*RCI)->allocation_order_end(MF); I != E; ++I)
160 AllocatablePhysicalRegisters[*I] = true; // The reg is allocatable!
165 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
166 BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
168 // PhysRegInfo - Keep track of which instruction was the last use of a
169 // physical register. This is a purely local property, because all physical
170 // register references as presumed dead across basic blocks.
172 MachineInstr *PhysRegInfoA[MRegisterInfo::FirstVirtualRegister];
173 bool PhysRegUsedA[MRegisterInfo::FirstVirtualRegister];
174 std::fill(PhysRegInfoA, PhysRegInfoA+MRegisterInfo::FirstVirtualRegister,
176 PhysRegInfo = PhysRegInfoA;
177 PhysRegUsed = PhysRegUsedA;
179 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
180 RegInfo = MF.getTarget().getRegisterInfo();
182 /// Get some space for a respectable number of registers...
183 VirtRegInfo.resize(64);
185 // Calculate live variable information in depth first order on the CFG of the
186 // function. This guarantees that we will see the definition of a virtual
187 // register before its uses due to dominance properties of SSA (except for PHI
188 // nodes, which are treated as a special case).
190 const BasicBlock *Entry = MF.getFunction()->begin();
191 for (df_iterator<const BasicBlock*> DFI = df_begin(Entry), E = df_end(Entry);
193 const BasicBlock *BB = *DFI;
194 std::pair<MachineBasicBlock*, unsigned> &BBRec = BBMap.find(BB)->second;
195 MachineBasicBlock *MBB = BBRec.first;
196 unsigned BBNum = BBRec.second;
198 // Loop over all of the instructions, processing them.
199 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
201 MachineInstr *MI = *I;
202 const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
204 // Process all of the operands of the instruction...
205 unsigned NumOperandsToProcess = MI->getNumOperands();
207 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
208 // of the uses. They will be handled in other basic blocks.
209 if (MI->getOpcode() == TargetInstrInfo::PHI)
210 NumOperandsToProcess = 1;
212 // Loop over implicit uses, using them.
213 for (const unsigned *ImplicitUses = MID.ImplicitUses;
214 *ImplicitUses; ++ImplicitUses)
215 HandlePhysRegUse(*ImplicitUses, MI);
217 // Process all explicit uses...
218 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
219 MachineOperand &MO = MI->getOperand(i);
221 if (MO.isVirtualRegister() && !MO.getVRegValueOrNull()) {
222 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
223 } else if (MO.isPhysicalRegister() &&
224 AllocatablePhysicalRegisters[MO.getReg()]) {
225 HandlePhysRegUse(MO.getReg(), MI);
230 // Loop over implicit defs, defining them.
231 for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
232 *ImplicitDefs; ++ImplicitDefs)
233 HandlePhysRegDef(*ImplicitDefs, MI);
235 // Process all explicit defs...
236 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
237 MachineOperand &MO = MI->getOperand(i);
239 if (MO.isVirtualRegister()) {
240 VarInfo &VRInfo = getVarInfo(MO.getReg());
242 assert(VRInfo.DefBlock == 0 && "Variable multiply defined!");
243 VRInfo.DefBlock = MBB; // Created here...
245 VRInfo.Kills.push_back(std::make_pair(MBB, MI)); // Defaults to dead
246 } else if (MO.isPhysicalRegister() &&
247 AllocatablePhysicalRegisters[MO.getReg()]) {
248 HandlePhysRegDef(MO.getReg(), MI);
254 // Handle any virtual assignments from PHI nodes which might be at the
255 // bottom of this basic block. We check all of our successor blocks to see
256 // if they have PHI nodes, and if so, we simulate an assignment at the end
257 // of the current block.
258 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB);
260 MachineBasicBlock *Succ = BBMap.find(*SI)->second.first;
262 // PHI nodes are guaranteed to be at the top of the block...
263 for (MachineBasicBlock::iterator I = Succ->begin(), E = Succ->end();
264 I != E && (*I)->getOpcode() == TargetInstrInfo::PHI; ++I) {
265 MachineInstr *MI = *I;
266 for (unsigned i = 1; ; i += 2)
267 if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
268 MachineOperand &MO = MI->getOperand(i);
269 if (!MO.getVRegValueOrNull()) {
270 VarInfo &VRInfo = getVarInfo(MO.getReg());
272 // Only mark it alive only in the block we are representing...
273 MarkVirtRegAliveInBlock(VRInfo, BB);
274 break; // Found the PHI entry for this block...
280 // Loop over PhysRegInfo, killing any registers that are available at the
281 // end of the basic block. This also resets the PhysRegInfo map.
282 for (unsigned i = 0, e = MRegisterInfo::FirstVirtualRegister; i != e; ++i)
284 HandlePhysRegDef(i, 0);
287 // Convert the information we have gathered into VirtRegInfo and transform it
288 // into a form usable by RegistersKilled.
290 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
291 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
292 if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
293 RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
294 i + MRegisterInfo::FirstVirtualRegister));
297 RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
298 i + MRegisterInfo::FirstVirtualRegister));
304 } // End llvm namespace