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/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Config/alloca.h"
41 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
43 void LiveVariables::VarInfo::dump() const {
44 std::cerr << "Register Defined by: ";
46 std::cerr << *DefInst;
48 std::cerr << "<null>\n";
49 std::cerr << " Alive in blocks: ";
50 for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
51 if (AliveBlocks[i]) std::cerr << i << ", ";
52 std::cerr << "\n Killed by:";
54 std::cerr << " No instructions.\n";
56 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57 std::cerr << "\n #" << i << ": " << *Kills[i];
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];
75 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
76 std::map<MachineInstr*, std::vector<unsigned> >::const_iterator I =
77 RegistersKilled.find(MI);
78 if (I == RegistersKilled.end()) return false;
80 // Do a binary search, as these lists can grow pretty big, particularly for
81 // call instructions on targets with lots of call-clobbered registers.
82 return std::binary_search(I->second.begin(), I->second.end(), Reg);
85 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
86 std::map<MachineInstr*, std::vector<unsigned> >::const_iterator I =
87 RegistersDead.find(MI);
88 if (I == RegistersDead.end()) return false;
90 // Do a binary search, as these lists can grow pretty big, particularly for
91 // call instructions on targets with lots of call-clobbered registers.
92 return std::binary_search(I->second.begin(), I->second.end(), Reg);
95 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
96 MachineBasicBlock *MBB) {
97 unsigned BBNum = MBB->getNumber();
99 // Check to see if this basic block is one of the killing blocks. If so,
101 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
102 if (VRInfo.Kills[i]->getParent() == MBB) {
103 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
107 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
109 if (VRInfo.AliveBlocks.size() <= BBNum)
110 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
112 if (VRInfo.AliveBlocks[BBNum])
113 return; // We already know the block is live
115 // Mark the variable known alive in this bb
116 VRInfo.AliveBlocks[BBNum] = true;
118 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
119 E = MBB->pred_end(); PI != E; ++PI)
120 MarkVirtRegAliveInBlock(VRInfo, *PI);
123 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
125 assert(VRInfo.DefInst && "Register use before def!");
127 // Check to see if this basic block is already a kill block...
128 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
129 // Yes, this register is killed in this basic block already. Increase the
130 // live range by updating the kill instruction.
131 VRInfo.Kills.back() = MI;
136 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
137 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
140 assert(MBB != VRInfo.DefInst->getParent() &&
141 "Should have kill for defblock!");
143 // Add a new kill entry for this basic block.
144 VRInfo.Kills.push_back(MI);
146 // Update all dominating blocks to mark them known live.
147 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
148 E = MBB->pred_end(); PI != E; ++PI)
149 MarkVirtRegAliveInBlock(VRInfo, *PI);
152 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
153 PhysRegInfo[Reg] = MI;
154 PhysRegUsed[Reg] = true;
156 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
157 unsigned Alias = *AliasSet; ++AliasSet) {
158 PhysRegInfo[Alias] = MI;
159 PhysRegUsed[Alias] = true;
163 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
164 // Does this kill a previous version of this register?
165 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
166 if (PhysRegUsed[Reg])
167 RegistersKilled[LastUse].push_back(Reg);
169 RegistersDead[LastUse].push_back(Reg);
171 PhysRegInfo[Reg] = MI;
172 PhysRegUsed[Reg] = false;
174 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
175 unsigned Alias = *AliasSet; ++AliasSet) {
176 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
177 if (PhysRegUsed[Alias])
178 RegistersKilled[LastUse].push_back(Alias);
180 RegistersDead[LastUse].push_back(Alias);
182 PhysRegInfo[Alias] = MI;
183 PhysRegUsed[Alias] = false;
187 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
188 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
189 RegInfo = MF.getTarget().getRegisterInfo();
190 assert(RegInfo && "Target doesn't have register information?");
192 AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
194 // PhysRegInfo - Keep track of which instruction was the last use of a
195 // physical register. This is a purely local property, because all physical
196 // register references as presumed dead across basic blocks.
198 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
199 RegInfo->getNumRegs());
200 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
201 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
203 /// Get some space for a respectable number of registers...
204 VirtRegInfo.resize(64);
206 // Mark live-in registers as live-in.
207 for (MachineFunction::livein_iterator I = MF.livein_begin(),
208 E = MF.livein_end(); I != E; ++I) {
209 assert(MRegisterInfo::isPhysicalRegister(I->first) &&
210 "Cannot have a live-in virtual register!");
211 HandlePhysRegDef(I->first, 0);
216 // Calculate live variable information in depth first order on the CFG of the
217 // function. This guarantees that we will see the definition of a virtual
218 // register before its uses due to dominance properties of SSA (except for PHI
219 // nodes, which are treated as a special case).
221 MachineBasicBlock *Entry = MF.begin();
222 std::set<MachineBasicBlock*> Visited;
223 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
224 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
225 MachineBasicBlock *MBB = *DFI;
227 // Loop over all of the instructions, processing them.
228 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
230 MachineInstr *MI = I;
232 // Process all of the operands of the instruction...
233 unsigned NumOperandsToProcess = MI->getNumOperands();
235 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
236 // of the uses. They will be handled in other basic blocks.
237 if (MI->getOpcode() == TargetInstrInfo::PHI)
238 NumOperandsToProcess = 1;
240 // Process all uses...
241 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
242 MachineOperand &MO = MI->getOperand(i);
243 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
244 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
245 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
246 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
247 AllocatablePhysicalRegisters[MO.getReg()]) {
248 HandlePhysRegUse(MO.getReg(), MI);
253 // Process all defs...
254 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
255 MachineOperand &MO = MI->getOperand(i);
256 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
257 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
258 VarInfo &VRInfo = getVarInfo(MO.getReg());
260 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
263 VRInfo.Kills.push_back(MI);
264 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
265 AllocatablePhysicalRegisters[MO.getReg()]) {
266 HandlePhysRegDef(MO.getReg(), MI);
272 // Handle any virtual assignments from PHI nodes which might be at the
273 // bottom of this basic block. We check all of our successor blocks to see
274 // if they have PHI nodes, and if so, we simulate an assignment at the end
275 // of the current block.
276 if (!PHIVarInfo[MBB].empty()) {
277 std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
279 for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
280 E = VarInfoVec.end(); I != E; ++I) {
281 VarInfo& VRInfo = getVarInfo(*I);
282 assert(VRInfo.DefInst && "Register use before def (or no def)!");
284 // Only mark it alive only in the block we are representing.
285 MarkVirtRegAliveInBlock(VRInfo, MBB);
289 // Finally, if the last block in the function is a return, make sure to mark
290 // it as using all of the live-out values in the function.
291 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
292 MachineInstr *Ret = &MBB->back();
293 for (MachineFunction::liveout_iterator I = MF.liveout_begin(),
294 E = MF.liveout_end(); I != E; ++I) {
295 assert(MRegisterInfo::isPhysicalRegister(*I) &&
296 "Cannot have a live-in virtual register!");
297 HandlePhysRegUse(*I, Ret);
301 // Loop over PhysRegInfo, killing any registers that are available at the
302 // end of the basic block. This also resets the PhysRegInfo map.
303 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
305 HandlePhysRegDef(i, 0);
308 // Convert the information we have gathered into VirtRegInfo and transform it
309 // into a form usable by RegistersKilled.
311 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
312 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
313 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
314 RegistersDead[VirtRegInfo[i].Kills[j]].push_back(
315 i + MRegisterInfo::FirstVirtualRegister);
318 RegistersKilled[VirtRegInfo[i].Kills[j]].push_back(
319 i + MRegisterInfo::FirstVirtualRegister);
322 // Walk through the RegistersKilled/Dead sets, and sort the registers killed
323 // or dead. This allows us to use efficient binary search for membership
325 for (std::map<MachineInstr*, std::vector<unsigned> >::iterator
326 I = RegistersKilled.begin(), E = RegistersKilled.end(); I != E; ++I)
327 std::sort(I->second.begin(), I->second.end());
328 for (std::map<MachineInstr*, std::vector<unsigned> >::iterator
329 I = RegistersDead.begin(), E = RegistersDead.end(); I != E; ++I)
330 std::sort(I->second.begin(), I->second.end());
332 // Check to make sure there are no unreachable blocks in the MC CFG for the
333 // function. If so, it is due to a bug in the instruction selector or some
334 // other part of the code generator if this happens.
336 for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
337 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
344 /// instructionChanged - When the address of an instruction changes, this
345 /// method should be called so that live variables can update its internal
346 /// data structures. This removes the records for OldMI, transfering them to
347 /// the records for NewMI.
348 void LiveVariables::instructionChanged(MachineInstr *OldMI,
349 MachineInstr *NewMI) {
350 // If the instruction defines any virtual registers, update the VarInfo for
352 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
353 MachineOperand &MO = OldMI->getOperand(i);
354 if (MO.isRegister() && MO.getReg() &&
355 MRegisterInfo::isVirtualRegister(MO.getReg())) {
356 unsigned Reg = MO.getReg();
357 VarInfo &VI = getVarInfo(Reg);
359 // Update the defining instruction.
360 if (VI.DefInst == OldMI)
364 // If this is a kill of the value, update the VI kills list.
365 if (VI.removeKill(OldMI))
366 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
371 // Move the killed information over...
372 killed_iterator I, E;
373 tie(I, E) = killed_range(OldMI);
375 std::vector<unsigned> &V = RegistersKilled[NewMI];
376 bool WasEmpty = V.empty();
377 V.insert(V.end(), I, E);
379 std::sort(V.begin(), V.end()); // Keep the reg list sorted.
380 RegistersKilled.erase(OldMI);
383 // Move the dead information over...
384 tie(I, E) = dead_range(OldMI);
386 std::vector<unsigned> &V = RegistersDead[NewMI];
387 bool WasEmpty = V.empty();
388 V.insert(V.end(), I, E);
390 std::sort(V.begin(), V.end()); // Keep the reg list sorted.
391 RegistersDead.erase(OldMI);
395 /// removeVirtualRegistersKilled - Remove all killed info for the specified
397 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
398 std::map<MachineInstr*, std::vector<unsigned> >::iterator I =
399 RegistersKilled.find(MI);
400 if (I == RegistersKilled.end()) return;
402 std::vector<unsigned> &Regs = I->second;
403 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
404 if (MRegisterInfo::isVirtualRegister(Regs[i])) {
405 bool removed = getVarInfo(Regs[i]).removeKill(MI);
406 assert(removed && "kill not in register's VarInfo?");
409 RegistersKilled.erase(I);
412 /// removeVirtualRegistersDead - Remove all of the dead registers for the
413 /// specified instruction from the live variable information.
414 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
415 std::map<MachineInstr*, std::vector<unsigned> >::iterator I =
416 RegistersDead.find(MI);
417 if (I == RegistersDead.end()) return;
419 std::vector<unsigned> &Regs = I->second;
420 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
421 if (MRegisterInfo::isVirtualRegister(Regs[i])) {
422 bool removed = getVarInfo(Regs[i]).removeKill(MI);
423 assert(removed && "kill not in register's VarInfo?");
426 RegistersDead.erase(I);
429 /// analyzePHINodes - Gather information about the PHI nodes in here. In
430 /// particular, we want to map the variable information of a virtual
431 /// register which is used in a PHI node. We map that to the BB the vreg is
434 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
435 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
437 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
438 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
439 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
440 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
441 push_back(BBI->getOperand(i).getReg());