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 /// registerOverlap - Returns true if register 1 is equal to register 2
76 /// or if register 1 is equal to any of alias of register 2.
77 static bool registerOverlap(unsigned Reg1, unsigned Reg2,
78 const MRegisterInfo *RegInfo) {
79 bool isVirt1 = MRegisterInfo::isVirtualRegister(Reg1);
80 bool isVirt2 = MRegisterInfo::isVirtualRegister(Reg2);
81 if (isVirt1 != isVirt2)
87 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg2);
88 unsigned Alias = *AliasSet; ++AliasSet) {
95 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
96 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
97 MachineOperand &MO = MI->getOperand(i);
98 if (MO.isReg() && MO.isKill()) {
99 if (registerOverlap(Reg, MO.getReg(), RegInfo))
106 bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
107 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
108 MachineOperand &MO = MI->getOperand(i);
109 if (MO.isReg() && MO.isDead())
110 if (registerOverlap(Reg, MO.getReg(), RegInfo))
116 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
117 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
118 MachineOperand &MO = MI->getOperand(i);
119 if (MO.isReg() && MO.isDef()) {
120 if (registerOverlap(Reg, MO.getReg(), RegInfo))
127 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
128 MachineBasicBlock *MBB) {
129 unsigned BBNum = MBB->getNumber();
131 // Check to see if this basic block is one of the killing blocks. If so,
133 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
134 if (VRInfo.Kills[i]->getParent() == MBB) {
135 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
139 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
141 if (VRInfo.AliveBlocks.size() <= BBNum)
142 VRInfo.AliveBlocks.resize(BBNum+1); // Make space...
144 if (VRInfo.AliveBlocks[BBNum])
145 return; // We already know the block is live
147 // Mark the variable known alive in this bb
148 VRInfo.AliveBlocks[BBNum] = true;
150 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
151 E = MBB->pred_end(); PI != E; ++PI)
152 MarkVirtRegAliveInBlock(VRInfo, *PI);
155 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
157 assert(VRInfo.DefInst && "Register use before def!");
159 // Check to see if this basic block is already a kill block...
160 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
161 // Yes, this register is killed in this basic block already. Increase the
162 // live range by updating the kill instruction.
163 VRInfo.Kills.back() = MI;
168 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
169 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
172 assert(MBB != VRInfo.DefInst->getParent() &&
173 "Should have kill for defblock!");
175 // Add a new kill entry for this basic block.
176 VRInfo.Kills.push_back(MI);
178 // Update all dominating blocks to mark them known live.
179 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
180 E = MBB->pred_end(); PI != E; ++PI)
181 MarkVirtRegAliveInBlock(VRInfo, *PI);
184 void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
185 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
186 MachineOperand &MO = MI->getOperand(i);
187 if (MO.isReg() && MO.isUse() && MO.getReg() == IncomingReg) {
194 void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
195 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
196 MachineOperand &MO = MI->getOperand(i);
197 if (MO.isReg() && MO.isDef() && MO.getReg() == IncomingReg) {
204 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
205 PhysRegInfo[Reg] = MI;
206 PhysRegUsed[Reg] = true;
208 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
209 unsigned Alias = *AliasSet; ++AliasSet) {
210 PhysRegInfo[Alias] = MI;
211 PhysRegUsed[Alias] = true;
215 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
216 // Does this kill a previous version of this register?
217 if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
218 if (PhysRegUsed[Reg])
219 addRegisterKilled(Reg, LastUse);
221 addRegisterDead(Reg, LastUse);
223 PhysRegInfo[Reg] = MI;
224 PhysRegUsed[Reg] = false;
226 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
227 unsigned Alias = *AliasSet; ++AliasSet) {
228 if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
229 if (PhysRegUsed[Alias])
230 addRegisterKilled(Alias, LastUse);
232 addRegisterDead(Alias, LastUse);
234 PhysRegInfo[Alias] = MI;
235 PhysRegUsed[Alias] = false;
239 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
240 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
241 RegInfo = MF.getTarget().getRegisterInfo();
242 assert(RegInfo && "Target doesn't have register information?");
244 AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
246 // PhysRegInfo - Keep track of which instruction was the last use of a
247 // physical register. This is a purely local property, because all physical
248 // register references as presumed dead across basic blocks.
250 PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
251 RegInfo->getNumRegs());
252 PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
253 std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
255 /// Get some space for a respectable number of registers...
256 VirtRegInfo.resize(64);
258 // Mark live-in registers as live-in.
259 for (MachineFunction::livein_iterator I = MF.livein_begin(),
260 E = MF.livein_end(); I != E; ++I) {
261 assert(MRegisterInfo::isPhysicalRegister(I->first) &&
262 "Cannot have a live-in virtual register!");
263 HandlePhysRegDef(I->first, 0);
268 // Calculate live variable information in depth first order on the CFG of the
269 // function. This guarantees that we will see the definition of a virtual
270 // register before its uses due to dominance properties of SSA (except for PHI
271 // nodes, which are treated as a special case).
273 MachineBasicBlock *Entry = MF.begin();
274 std::set<MachineBasicBlock*> Visited;
275 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
276 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
277 MachineBasicBlock *MBB = *DFI;
279 // Loop over all of the instructions, processing them.
280 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
282 MachineInstr *MI = I;
284 // Process all of the operands of the instruction...
285 unsigned NumOperandsToProcess = MI->getNumOperands();
287 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
288 // of the uses. They will be handled in other basic blocks.
289 if (MI->getOpcode() == TargetInstrInfo::PHI)
290 NumOperandsToProcess = 1;
292 // Process all uses...
293 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
294 MachineOperand &MO = MI->getOperand(i);
295 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
296 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
297 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
298 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
299 AllocatablePhysicalRegisters[MO.getReg()]) {
300 HandlePhysRegUse(MO.getReg(), MI);
305 // Process all defs...
306 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
307 MachineOperand &MO = MI->getOperand(i);
308 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
309 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
310 VarInfo &VRInfo = getVarInfo(MO.getReg());
312 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
315 VRInfo.Kills.push_back(MI);
316 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
317 AllocatablePhysicalRegisters[MO.getReg()]) {
318 HandlePhysRegDef(MO.getReg(), MI);
324 // Handle any virtual assignments from PHI nodes which might be at the
325 // bottom of this basic block. We check all of our successor blocks to see
326 // if they have PHI nodes, and if so, we simulate an assignment at the end
327 // of the current block.
328 if (!PHIVarInfo[MBB].empty()) {
329 std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
331 for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
332 E = VarInfoVec.end(); I != E; ++I) {
333 VarInfo& VRInfo = getVarInfo(*I);
334 assert(VRInfo.DefInst && "Register use before def (or no def)!");
336 // Only mark it alive only in the block we are representing.
337 MarkVirtRegAliveInBlock(VRInfo, MBB);
341 // Finally, if the last instruction in the block is a return, make sure to mark
342 // it as using all of the live-out values in the function.
343 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
344 MachineInstr *Ret = &MBB->back();
345 for (MachineFunction::liveout_iterator I = MF.liveout_begin(),
346 E = MF.liveout_end(); I != E; ++I) {
347 assert(MRegisterInfo::isPhysicalRegister(*I) &&
348 "Cannot have a live-in virtual register!");
349 HandlePhysRegUse(*I, Ret);
350 // Add live-out registers as implicit uses.
351 Ret->addRegOperand(*I, false, true);
355 // Loop over PhysRegInfo, killing any registers that are available at the
356 // end of the basic block. This also resets the PhysRegInfo map.
357 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
359 HandlePhysRegDef(i, 0);
362 // Convert and transfer the dead / killed information we have gathered into
363 // VirtRegInfo onto MI's.
365 for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
366 for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
367 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
368 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
369 VirtRegInfo[i].Kills[j]);
371 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
372 VirtRegInfo[i].Kills[j]);
375 // Check to make sure there are no unreachable blocks in the MC CFG for the
376 // function. If so, it is due to a bug in the instruction selector or some
377 // other part of the code generator if this happens.
379 for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
380 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
387 /// instructionChanged - When the address of an instruction changes, this
388 /// method should be called so that live variables can update its internal
389 /// data structures. This removes the records for OldMI, transfering them to
390 /// the records for NewMI.
391 void LiveVariables::instructionChanged(MachineInstr *OldMI,
392 MachineInstr *NewMI) {
393 // If the instruction defines any virtual registers, update the VarInfo,
394 // kill and dead information for the instruction.
395 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
396 MachineOperand &MO = OldMI->getOperand(i);
397 if (MO.isRegister() && MO.getReg() &&
398 MRegisterInfo::isVirtualRegister(MO.getReg())) {
399 unsigned Reg = MO.getReg();
400 VarInfo &VI = getVarInfo(Reg);
404 addVirtualRegisterDead(Reg, NewMI);
406 // Update the defining instruction.
407 if (VI.DefInst == OldMI)
413 addVirtualRegisterKilled(Reg, NewMI);
415 // If this is a kill of the value, update the VI kills list.
416 if (VI.removeKill(OldMI))
417 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
423 /// removeVirtualRegistersKilled - Remove all killed info for the specified
425 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
426 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
427 MachineOperand &MO = MI->getOperand(i);
428 if (MO.isReg() && MO.isKill()) {
430 unsigned Reg = MO.getReg();
431 if (MRegisterInfo::isVirtualRegister(Reg)) {
432 bool removed = getVarInfo(Reg).removeKill(MI);
433 assert(removed && "kill not in register's VarInfo?");
439 /// removeVirtualRegistersDead - Remove all of the dead registers for the
440 /// specified instruction from the live variable information.
441 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
442 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
443 MachineOperand &MO = MI->getOperand(i);
444 if (MO.isReg() && MO.isDead()) {
446 unsigned Reg = MO.getReg();
447 if (MRegisterInfo::isVirtualRegister(Reg)) {
448 bool removed = getVarInfo(Reg).removeKill(MI);
449 assert(removed && "kill not in register's VarInfo?");
455 /// analyzePHINodes - Gather information about the PHI nodes in here. In
456 /// particular, we want to map the variable information of a virtual
457 /// register which is used in a PHI node. We map that to the BB the vreg is
460 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
461 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
463 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
464 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
465 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
466 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
467 push_back(BBI->getOperand(i).getReg());