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/MRegisterInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/CFG.h"
35 #include "Support/DepthFirstIterator.h"
36 #include "Support/STLExtras.h"
39 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
41 const std::pair<MachineBasicBlock*, unsigned> &
42 LiveVariables::getMachineBasicBlockInfo(MachineBasicBlock *MBB) const{
43 return BBMap.find(MBB->getBasicBlock())->second;
46 /// getIndexMachineBasicBlock() - Given a block index, return the
47 /// MachineBasicBlock corresponding to it.
48 MachineBasicBlock *LiveVariables::getIndexMachineBasicBlock(unsigned Idx) {
49 if (BBIdxMap.empty()) {
50 BBIdxMap.resize(BBMap.size());
51 for (std::map<const BasicBlock*, std::pair<MachineBasicBlock*, unsigned> >
52 ::iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) {
53 assert(BBIdxMap.size() > I->second.second &&"Indices are not sequential");
54 assert(BBIdxMap[I->second.second] == 0 && "Multiple idx collision!");
55 BBIdxMap[I->second.second] = I->second.first;
58 assert(Idx < BBIdxMap.size() && "BB Index out of range!");
62 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
63 assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
64 "getVarInfo: not a virtual register!");
65 RegIdx -= MRegisterInfo::FirstVirtualRegister;
66 if (RegIdx >= VirtRegInfo.size()) {
67 if (RegIdx >= 2*VirtRegInfo.size())
68 VirtRegInfo.resize(RegIdx*2);
70 VirtRegInfo.resize(2*VirtRegInfo.size());
72 return VirtRegInfo[RegIdx];
77 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
78 const BasicBlock *BB) {
79 const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
80 MachineBasicBlock *MBB = Info.first;
81 unsigned BBNum = Info.second;
83 // Check to see if this basic block is one of the killing blocks. If so,
85 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
86 if (VRInfo.Kills[i].first == MBB) {
87 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
91 if (MBB == VRInfo.DefBlock) return; // Terminate recursion
93 if (VRInfo.AliveBlocks.size() <= BBNum)
94 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
96 if (VRInfo.AliveBlocks[BBNum])
97 return; // We already know the block is live
99 // Mark the variable known alive in this bb
100 VRInfo.AliveBlocks[BBNum] = true;
102 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
103 MarkVirtRegAliveInBlock(VRInfo, *PI);
106 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
108 // Check to see if this basic block is already a kill block...
109 if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
110 // Yes, this register is killed in this basic block already. Increase the
111 // live range by updating the kill instruction.
112 VRInfo.Kills.back().second = MI;
117 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
118 assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
121 assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
123 // Add a new kill entry for this basic block.
124 VRInfo.Kills.push_back(std::make_pair(MBB, MI));
126 // Update all dominating blocks to mark them known live.
127 const BasicBlock *BB = MBB->getBasicBlock();
128 for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
130 MarkVirtRegAliveInBlock(VRInfo, *PI);
133 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
134 PhysRegInfo[Reg] = MI;
135 PhysRegUsed[Reg] = true;
138 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
139 // Does this kill a previous version of this register?
140 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
141 if (PhysRegUsed[Reg])
142 RegistersKilled.insert(std::make_pair(LastUse, Reg));
144 RegistersDead.insert(std::make_pair(LastUse, Reg));
146 PhysRegInfo[Reg] = MI;
147 PhysRegUsed[Reg] = false;
149 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
150 *AliasSet; ++AliasSet) {
151 unsigned Alias = *AliasSet;
152 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
153 if (PhysRegUsed[Alias])
154 RegistersKilled.insert(std::make_pair(LastUse, Alias));
156 RegistersDead.insert(std::make_pair(LastUse, Alias));
158 PhysRegInfo[Alias] = MI;
159 PhysRegUsed[Alias] = false;
163 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
164 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
165 RegInfo = MF.getTarget().getRegisterInfo();
166 assert(RegInfo && "Target doesn't have register information?");
168 // First time though, initialize AllocatablePhysicalRegisters for the target
169 if (AllocatablePhysicalRegisters.empty()) {
170 // Make space, initializing to false...
171 AllocatablePhysicalRegisters.resize(RegInfo->getNumRegs());
173 // Loop over all of the register classes...
174 for (MRegisterInfo::regclass_iterator RCI = RegInfo->regclass_begin(),
175 E = RegInfo->regclass_end(); RCI != E; ++RCI)
176 // Loop over all of the allocatable registers in the function...
177 for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
178 E = (*RCI)->allocation_order_end(MF); I != E; ++I)
179 AllocatablePhysicalRegisters[*I] = true; // The reg is allocatable!
184 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
185 BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
187 // PhysRegInfo - Keep track of which instruction was the last use of a
188 // physical register. This is a purely local property, because all physical
189 // register references as presumed dead across basic blocks.
191 MachineInstr *PhysRegInfoA[RegInfo->getNumRegs()];
192 bool PhysRegUsedA[RegInfo->getNumRegs()];
193 std::fill(PhysRegInfoA, PhysRegInfoA+RegInfo->getNumRegs(), (MachineInstr*)0);
194 PhysRegInfo = PhysRegInfoA;
195 PhysRegUsed = PhysRegUsedA;
197 /// Get some space for a respectable number of registers...
198 VirtRegInfo.resize(64);
200 // Calculate live variable information in depth first order on the CFG of the
201 // function. This guarantees that we will see the definition of a virtual
202 // register before its uses due to dominance properties of SSA (except for PHI
203 // nodes, which are treated as a special case).
205 const BasicBlock *Entry = MF.getFunction()->begin();
206 for (df_iterator<const BasicBlock*> DFI = df_begin(Entry), E = df_end(Entry);
208 const BasicBlock *BB = *DFI;
209 std::pair<MachineBasicBlock*, unsigned> &BBRec = BBMap.find(BB)->second;
210 MachineBasicBlock *MBB = BBRec.first;
211 unsigned BBNum = BBRec.second;
213 // Loop over all of the instructions, processing them.
214 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
216 MachineInstr *MI = I;
217 const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
219 // Process all of the operands of the instruction...
220 unsigned NumOperandsToProcess = MI->getNumOperands();
222 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
223 // of the uses. They will be handled in other basic blocks.
224 if (MI->getOpcode() == TargetInstrInfo::PHI)
225 NumOperandsToProcess = 1;
227 // Loop over implicit uses, using them.
228 for (const unsigned *ImplicitUses = MID.ImplicitUses;
229 *ImplicitUses; ++ImplicitUses)
230 HandlePhysRegUse(*ImplicitUses, MI);
232 // Process all explicit uses...
233 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
234 MachineOperand &MO = MI->getOperand(i);
235 if (MO.isUse() && MO.isRegister() && MO.getReg()) {
236 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
237 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
238 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
239 AllocatablePhysicalRegisters[MO.getReg()]) {
240 HandlePhysRegUse(MO.getReg(), MI);
245 // Loop over implicit defs, defining them.
246 for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
247 *ImplicitDefs; ++ImplicitDefs)
248 HandlePhysRegDef(*ImplicitDefs, MI);
250 // Process all explicit defs...
251 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
252 MachineOperand &MO = MI->getOperand(i);
253 if (MO.isDef() && MO.isRegister() && MO.getReg()) {
254 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
255 VarInfo &VRInfo = getVarInfo(MO.getReg());
257 assert(VRInfo.DefBlock == 0 && "Variable multiply defined!");
258 VRInfo.DefBlock = MBB; // Created here...
260 VRInfo.Kills.push_back(std::make_pair(MBB, MI)); // Defaults to dead
261 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
262 AllocatablePhysicalRegisters[MO.getReg()]) {
263 HandlePhysRegDef(MO.getReg(), MI);
269 // Handle any virtual assignments from PHI nodes which might be at the
270 // bottom of this basic block. We check all of our successor blocks to see
271 // if they have PHI nodes, and if so, we simulate an assignment at the end
272 // of the current block.
273 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB);
275 MachineBasicBlock *Succ = BBMap.find(*SI)->second.first;
277 // PHI nodes are guaranteed to be at the top of the block...
278 for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
279 MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
280 for (unsigned i = 1; ; i += 2)
281 if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
282 MachineOperand &MO = MI->getOperand(i);
283 if (!MO.getVRegValueOrNull()) {
284 VarInfo &VRInfo = getVarInfo(MO.getReg());
286 // Only mark it alive only in the block we are representing...
287 MarkVirtRegAliveInBlock(VRInfo, BB);
288 break; // Found the PHI entry for this block...
294 // Loop over PhysRegInfo, killing any registers that are available at the
295 // end of the basic block. This also resets the PhysRegInfo map.
296 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
298 HandlePhysRegDef(i, 0);
301 // Convert the information we have gathered into VirtRegInfo and transform it
302 // into a form usable by RegistersKilled.
304 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
305 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
306 if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
307 RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
308 i + MRegisterInfo::FirstVirtualRegister));
311 RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
312 i + MRegisterInfo::FirstVirtualRegister));
318 /// instructionChanged - When the address of an instruction changes, this
319 /// method should be called so that live variables can update its internal
320 /// data structures. This removes the records for OldMI, transfering them to
321 /// the records for NewMI.
322 void LiveVariables::instructionChanged(MachineInstr *OldMI,
323 MachineInstr *NewMI) {
324 // If the instruction defines any virtual registers, update the VarInfo for
326 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
327 MachineOperand &MO = NewMI->getOperand(i);
328 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
329 MRegisterInfo::isVirtualRegister(MO.getReg())) {
330 unsigned Reg = MO.getReg();
331 VarInfo &VI = getVarInfo(Reg);
332 if (VI.DefInst == OldMI)
337 // Move the killed information over...
338 killed_iterator I, E;
339 tie(I, E) = killed_range(OldMI);
340 std::vector<unsigned> Regs;
341 for (killed_iterator A = I; A != E; ++A)
342 Regs.push_back(A->second);
343 RegistersKilled.erase(I, E);
345 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
346 RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
350 // Move the dead information over...
351 tie(I, E) = dead_range(OldMI);
352 for (killed_iterator A = I; A != E; ++A)
353 Regs.push_back(A->second);
354 RegistersDead.erase(I, E);
356 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
357 RegistersDead.insert(std::make_pair(NewMI, Regs[i]));