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"
40 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
42 void LiveVariables::VarInfo::dump() const {
43 cerr << "Register Defined by: ";
48 cerr << " Alive in blocks: ";
49 for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
50 if (AliveBlocks[i]) cerr << i << ", ";
51 cerr << " Used in blocks: ";
52 for (unsigned i = 0, e = UsedBlocks.size(); i != e; ++i)
53 if (UsedBlocks[i]) cerr << i << ", ";
54 cerr << "\n Killed by:";
56 cerr << " No instructions.\n";
58 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
59 cerr << "\n #" << i << ": " << *Kills[i];
64 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
65 assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
66 "getVarInfo: not a virtual register!");
67 RegIdx -= MRegisterInfo::FirstVirtualRegister;
68 if (RegIdx >= VirtRegInfo.size()) {
69 if (RegIdx >= 2*VirtRegInfo.size())
70 VirtRegInfo.resize(RegIdx*2);
72 VirtRegInfo.resize(2*VirtRegInfo.size());
74 VarInfo &VI = VirtRegInfo[RegIdx];
75 VI.AliveBlocks.resize(MF->getNumBlockIDs());
76 VI.UsedBlocks.resize(MF->getNumBlockIDs());
80 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
81 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
82 MachineOperand &MO = MI->getOperand(i);
83 if (MO.isReg() && MO.isKill()) {
84 if (RegInfo->regsOverlap(Reg, MO.getReg()))
91 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
92 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
93 MachineOperand &MO = MI->getOperand(i);
94 if (MO.isReg() && MO.isDead())
95 if (RegInfo->regsOverlap(Reg, MO.getReg()))
101 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
102 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
103 MachineOperand &MO = MI->getOperand(i);
104 if (MO.isReg() && MO.isDef()) {
105 if (RegInfo->regsOverlap(Reg, MO.getReg()))
112 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
113 MachineBasicBlock *MBB) {
114 unsigned BBNum = MBB->getNumber();
116 // Check to see if this basic block is one of the killing blocks. If so,
118 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
119 if (VRInfo.Kills[i]->getParent() == MBB) {
120 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
124 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
126 if (VRInfo.AliveBlocks[BBNum])
127 return; // We already know the block is live
129 // Mark the variable known alive in this bb
130 VRInfo.AliveBlocks[BBNum] = true;
132 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
133 E = MBB->pred_end(); PI != E; ++PI)
134 MarkVirtRegAliveInBlock(VRInfo, *PI);
137 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
139 assert(VRInfo.DefInst && "Register use before def!");
141 unsigned BBNum = MBB->getNumber();
143 VRInfo.UsedBlocks[BBNum] = true;
146 // Check to see if this basic block is already a kill block...
147 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
148 // Yes, this register is killed in this basic block already. Increase the
149 // live range by updating the kill instruction.
150 VRInfo.Kills.back() = MI;
155 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
156 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
159 assert(MBB != VRInfo.DefInst->getParent() &&
160 "Should have kill for defblock!");
162 // Add a new kill entry for this basic block.
163 // If this virtual register is already marked as alive in this basic block,
164 // that means it is alive in at least one of the successor block, it's not
166 if (!VRInfo.AliveBlocks[BBNum])
167 VRInfo.Kills.push_back(MI);
169 // Update all dominating blocks to mark them known live.
170 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
171 E = MBB->pred_end(); PI != E; ++PI)
172 MarkVirtRegAliveInBlock(VRInfo, *PI);
175 void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
176 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
177 MachineOperand &MO = MI->getOperand(i);
178 if (MO.isReg() && MO.isUse() && MO.getReg() == IncomingReg) {
185 void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
186 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
187 MachineOperand &MO = MI->getOperand(i);
188 if (MO.isReg() && MO.isDef() && MO.getReg() == IncomingReg) {
195 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
196 PhysRegInfo[Reg] = MI;
197 PhysRegUsed[Reg] = true;
199 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
200 unsigned Alias = *AliasSet; ++AliasSet) {
201 PhysRegInfo[Alias] = MI;
202 PhysRegUsed[Alias] = true;
206 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
207 // Does this kill a previous version of this register?
208 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
209 if (PhysRegUsed[Reg])
210 addRegisterKilled(Reg, LastUse);
212 addRegisterDead(Reg, LastUse);
214 PhysRegInfo[Reg] = MI;
215 PhysRegUsed[Reg] = false;
217 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
218 unsigned Alias = *AliasSet; ++AliasSet) {
219 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
220 if (PhysRegUsed[Alias])
221 addRegisterKilled(Alias, LastUse);
223 addRegisterDead(Alias, LastUse);
225 PhysRegInfo[Alias] = MI;
226 PhysRegUsed[Alias] = false;
230 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
232 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
233 RegInfo = MF->getTarget().getRegisterInfo();
234 assert(RegInfo && "Target doesn't have register information?");
236 ReservedRegisters = RegInfo->getReservedRegs(mf);
238 // PhysRegInfo - Keep track of which instruction was the last use of a
239 // physical register. This is a purely local property, because all physical
240 // register references as presumed dead across basic blocks.
242 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
243 RegInfo->getNumRegs());
244 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
245 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
247 /// Get some space for a respectable number of registers...
248 VirtRegInfo.resize(64);
252 // Calculate live variable information in depth first order on the CFG of the
253 // function. This guarantees that we will see the definition of a virtual
254 // register before its uses due to dominance properties of SSA (except for PHI
255 // nodes, which are treated as a special case).
257 MachineBasicBlock *Entry = MF->begin();
258 std::set<MachineBasicBlock*> Visited;
259 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
260 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
261 MachineBasicBlock *MBB = *DFI;
263 // Mark live-in registers as live-in.
264 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
265 EE = MBB->livein_end(); II != EE; ++II) {
266 assert(MRegisterInfo::isPhysicalRegister(*II) &&
267 "Cannot have a live-in virtual register!");
268 HandlePhysRegDef(*II, 0);
271 // Loop over all of the instructions, processing them.
272 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
274 MachineInstr *MI = I;
276 // Process all of the operands of the instruction...
277 unsigned NumOperandsToProcess = MI->getNumOperands();
279 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
280 // of the uses. They will be handled in other basic blocks.
281 if (MI->getOpcode() == TargetInstrInfo::PHI)
282 NumOperandsToProcess = 1;
284 // Process all uses...
285 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
286 MachineOperand &MO = MI->getOperand(i);
287 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
288 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
289 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
290 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
291 !ReservedRegisters[MO.getReg()]) {
292 HandlePhysRegUse(MO.getReg(), MI);
297 // Process all defs...
298 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
299 MachineOperand &MO = MI->getOperand(i);
300 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
301 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
302 VarInfo &VRInfo = getVarInfo(MO.getReg());
304 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
307 VRInfo.Kills.push_back(MI);
308 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
309 !ReservedRegisters[MO.getReg()]) {
310 HandlePhysRegDef(MO.getReg(), MI);
316 // Handle any virtual assignments from PHI nodes which might be at the
317 // bottom of this basic block. We check all of our successor blocks to see
318 // if they have PHI nodes, and if so, we simulate an assignment at the end
319 // of the current block.
320 if (!PHIVarInfo[MBB].empty()) {
321 std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
323 for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
324 E = VarInfoVec.end(); I != E; ++I) {
325 VarInfo& VRInfo = getVarInfo(*I);
326 assert(VRInfo.DefInst && "Register use before def (or no def)!");
328 // Only mark it alive only in the block we are representing.
329 MarkVirtRegAliveInBlock(VRInfo, MBB);
333 // Finally, if the last instruction in the block is a return, make sure to mark
334 // it as using all of the live-out values in the function.
335 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
336 MachineInstr *Ret = &MBB->back();
337 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
338 E = MF->liveout_end(); I != E; ++I) {
339 assert(MRegisterInfo::isPhysicalRegister(*I) &&
340 "Cannot have a live-in virtual register!");
341 HandlePhysRegUse(*I, Ret);
342 // Add live-out registers as implicit uses.
343 Ret->addRegOperand(*I, false, true);
347 // Loop over PhysRegInfo, killing any registers that are available at the
348 // end of the basic block. This also resets the PhysRegInfo map.
349 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
351 HandlePhysRegDef(i, 0);
354 // Convert and transfer the dead / killed information we have gathered into
355 // VirtRegInfo onto MI's.
357 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
358 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
359 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
360 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
361 VirtRegInfo[i].Kills[j]);
363 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
364 VirtRegInfo[i].Kills[j]);
367 // Check to make sure there are no unreachable blocks in the MC CFG for the
368 // function. If so, it is due to a bug in the instruction selector or some
369 // other part of the code generator if this happens.
371 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
372 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
379 /// instructionChanged - When the address of an instruction changes, this
380 /// method should be called so that live variables can update its internal
381 /// data structures. This removes the records for OldMI, transfering them to
382 /// the records for NewMI.
383 void LiveVariables::instructionChanged(MachineInstr *OldMI,
384 MachineInstr *NewMI) {
385 // If the instruction defines any virtual registers, update the VarInfo,
386 // kill and dead information for the instruction.
387 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
388 MachineOperand &MO = OldMI->getOperand(i);
389 if (MO.isRegister() && MO.getReg() &&
390 MRegisterInfo::isVirtualRegister(MO.getReg())) {
391 unsigned Reg = MO.getReg();
392 VarInfo &VI = getVarInfo(Reg);
396 addVirtualRegisterDead(Reg, NewMI);
398 // Update the defining instruction.
399 if (VI.DefInst == OldMI)
405 addVirtualRegisterKilled(Reg, NewMI);
407 // If this is a kill of the value, update the VI kills list.
408 if (VI.removeKill(OldMI))
409 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
415 /// removeVirtualRegistersKilled - Remove all killed info for the specified
417 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
418 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
419 MachineOperand &MO = MI->getOperand(i);
420 if (MO.isReg() && MO.isKill()) {
422 unsigned Reg = MO.getReg();
423 if (MRegisterInfo::isVirtualRegister(Reg)) {
424 bool removed = getVarInfo(Reg).removeKill(MI);
425 assert(removed && "kill not in register's VarInfo?");
431 /// removeVirtualRegistersDead - Remove all of the dead registers for the
432 /// specified instruction from the live variable information.
433 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
434 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
435 MachineOperand &MO = MI->getOperand(i);
436 if (MO.isReg() && MO.isDead()) {
438 unsigned Reg = MO.getReg();
439 if (MRegisterInfo::isVirtualRegister(Reg)) {
440 bool removed = getVarInfo(Reg).removeKill(MI);
441 assert(removed && "kill not in register's VarInfo?");
447 /// analyzePHINodes - Gather information about the PHI nodes in here. In
448 /// particular, we want to map the variable information of a virtual
449 /// register which is used in a PHI node. We map that to the BB the vreg is
452 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
453 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
455 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
456 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
457 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
458 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
459 push_back(BBI->getOperand(i).getReg());