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 const int LiveVariables::ID = 0;
41 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
43 void LiveVariables::VarInfo::dump() const {
44 cerr << "Register Defined by: ";
49 cerr << " Alive in blocks: ";
50 for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
51 if (AliveBlocks[i]) cerr << i << ", ";
52 cerr << "\n Killed by:";
54 cerr << " No instructions.\n";
56 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57 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 VarInfo &VI = VirtRegInfo[RegIdx];
73 VI.AliveBlocks.resize(MF->getNumBlockIDs());
77 bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
78 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79 MachineOperand &MO = MI->getOperand(i);
80 if (MO.isReg() && MO.isKill()) {
81 if ((MO.getReg() == Reg) ||
82 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
83 MRegisterInfo::isPhysicalRegister(Reg) &&
84 RegInfo->isSubRegister(MO.getReg(), Reg)))
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 ((MO.getReg() == Reg) ||
96 (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
97 MRegisterInfo::isPhysicalRegister(Reg) &&
98 RegInfo->isSubRegister(MO.getReg(), Reg)))
105 bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
106 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
107 MachineOperand &MO = MI->getOperand(i);
108 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
114 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
115 MachineBasicBlock *MBB) {
116 unsigned BBNum = MBB->getNumber();
118 // Check to see if this basic block is one of the killing blocks. If so,
120 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
121 if (VRInfo.Kills[i]->getParent() == MBB) {
122 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
126 if (MBB == VRInfo.DefInst->getParent()) return; // Terminate recursion
128 if (VRInfo.AliveBlocks[BBNum])
129 return; // We already know the block is live
131 // Mark the variable known alive in this bb
132 VRInfo.AliveBlocks[BBNum] = true;
134 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
135 E = MBB->pred_end(); PI != E; ++PI)
136 MarkVirtRegAliveInBlock(VRInfo, *PI);
139 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
141 assert(VRInfo.DefInst && "Register use before def!");
145 // Check to see if this basic block is already a kill block...
146 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
147 // Yes, this register is killed in this basic block already. Increase the
148 // live range by updating the kill instruction.
149 VRInfo.Kills.back() = MI;
154 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
155 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
158 assert(MBB != VRInfo.DefInst->getParent() &&
159 "Should have kill for defblock!");
161 // Add a new kill entry for this basic block.
162 // If this virtual register is already marked as alive in this basic block,
163 // that means it is alive in at least one of the successor block, it's not
165 if (!VRInfo.AliveBlocks[MBB->getNumber()])
166 VRInfo.Kills.push_back(MI);
168 // Update all dominating blocks to mark them known live.
169 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
170 E = MBB->pred_end(); PI != E; ++PI)
171 MarkVirtRegAliveInBlock(VRInfo, *PI);
174 bool LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI,
175 bool AddIfNotFound) {
177 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
178 MachineOperand &MO = MI->getOperand(i);
179 if (MO.isReg() && MO.isUse()) {
180 unsigned Reg = MO.getReg();
183 if (Reg == IncomingReg) {
187 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
188 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
189 RegInfo->isSuperRegister(IncomingReg, Reg) &&
191 // A super-register kill already exists.
196 // If not found, this means an alias of one of the operand is killed. Add a
197 // new implicit operand if required.
198 if (!Found && AddIfNotFound) {
199 MI->addRegOperand(IncomingReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
205 bool LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI,
206 bool AddIfNotFound) {
208 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
209 MachineOperand &MO = MI->getOperand(i);
210 if (MO.isReg() && MO.isDef()) {
211 unsigned Reg = MO.getReg();
214 if (Reg == IncomingReg) {
218 } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
219 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
220 RegInfo->isSuperRegister(IncomingReg, Reg) &&
222 // There exists a super-register that's marked dead.
227 // If not found, this means an alias of one of the operand is dead. Add a
228 // new implicit operand.
229 if (!Found && AddIfNotFound) {
230 MI->addRegOperand(IncomingReg, true/*IsDef*/,true/*IsImp*/,false/*IsKill*/,
237 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
238 // There is a now a proper use, forget about the last partial use.
239 PhysRegPartUse[Reg] = NULL;
241 // Turn previous partial def's into read/mod/write.
242 for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
243 MachineInstr *Def = PhysRegPartDef[Reg][i];
244 // First one is just a def. This means the use is reading some undef bits.
246 Def->addRegOperand(Reg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
247 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
249 PhysRegPartDef[Reg].clear();
251 // There was an earlier def of a super-register. Add implicit def to that MI.
254 // Add implicit def to A.
255 if (PhysRegInfo[Reg] && !PhysRegUsed[Reg]) {
256 MachineInstr *Def = PhysRegInfo[Reg];
257 if (!Def->findRegisterDefOperand(Reg))
258 Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
261 PhysRegInfo[Reg] = MI;
262 PhysRegUsed[Reg] = true;
264 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
265 unsigned SubReg = *SubRegs; ++SubRegs) {
266 PhysRegInfo[SubReg] = MI;
267 PhysRegUsed[SubReg] = true;
270 // Remember the partial uses.
271 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
272 unsigned SuperReg = *SuperRegs; ++SuperRegs)
273 PhysRegPartUse[SuperReg] = MI;
276 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
277 // Does this kill a previous version of this register?
278 if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
279 if (PhysRegUsed[Reg])
280 addRegisterKilled(Reg, LastRef);
281 else if (PhysRegPartUse[Reg])
282 // Add implicit use / kill to last use of a sub-register.
283 addRegisterKilled(Reg, PhysRegPartUse[Reg], true);
285 addRegisterDead(Reg, LastRef);
287 PhysRegInfo[Reg] = MI;
288 PhysRegUsed[Reg] = false;
289 PhysRegPartUse[Reg] = NULL;
291 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
292 unsigned SubReg = *SubRegs; ++SubRegs) {
293 if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
294 if (PhysRegUsed[SubReg])
295 addRegisterKilled(SubReg, LastRef);
296 else if (PhysRegPartUse[SubReg])
297 // Add implicit use / kill to last use of a sub-register.
298 addRegisterKilled(SubReg, PhysRegPartUse[SubReg], true);
300 addRegisterDead(SubReg, LastRef);
302 PhysRegInfo[SubReg] = MI;
303 PhysRegUsed[SubReg] = false;
307 for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
308 unsigned SuperReg = *SuperRegs; ++SuperRegs) {
309 if (PhysRegInfo[SuperReg]) {
310 // The larger register is previously defined. Now a smaller part is
311 // being re-defined. Treat it as read/mod/write.
313 // AX = EAX<imp-use,kill>, EAX<imp-def>
314 MI->addRegOperand(SuperReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
315 MI->addRegOperand(SuperReg, true/*IsDef*/,true/*IsImp*/);
316 PhysRegInfo[SuperReg] = MI;
317 PhysRegUsed[SuperReg] = false;
319 // Remember this partial def.
320 PhysRegPartDef[SuperReg].push_back(MI);
325 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
327 const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
328 RegInfo = MF->getTarget().getRegisterInfo();
329 assert(RegInfo && "Target doesn't have register information?");
331 ReservedRegisters = RegInfo->getReservedRegs(mf);
333 unsigned NumRegs = RegInfo->getNumRegs();
334 PhysRegInfo = new MachineInstr*[NumRegs];
335 PhysRegUsed = new bool[NumRegs];
336 PhysRegPartUse = new MachineInstr*[NumRegs];
337 PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
338 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
339 std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
340 std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
341 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
343 /// Get some space for a respectable number of registers...
344 VirtRegInfo.resize(64);
348 // Calculate live variable information in depth first order on the CFG of the
349 // function. This guarantees that we will see the definition of a virtual
350 // register before its uses due to dominance properties of SSA (except for PHI
351 // nodes, which are treated as a special case).
353 MachineBasicBlock *Entry = MF->begin();
354 std::set<MachineBasicBlock*> Visited;
355 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
356 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
357 MachineBasicBlock *MBB = *DFI;
359 // Mark live-in registers as live-in.
360 for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
361 EE = MBB->livein_end(); II != EE; ++II) {
362 assert(MRegisterInfo::isPhysicalRegister(*II) &&
363 "Cannot have a live-in virtual register!");
364 HandlePhysRegDef(*II, 0);
367 // Loop over all of the instructions, processing them.
368 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
370 MachineInstr *MI = I;
372 // Process all of the operands of the instruction...
373 unsigned NumOperandsToProcess = MI->getNumOperands();
375 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
376 // of the uses. They will be handled in other basic blocks.
377 if (MI->getOpcode() == TargetInstrInfo::PHI)
378 NumOperandsToProcess = 1;
380 // Process all uses...
381 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
382 MachineOperand &MO = MI->getOperand(i);
383 if (MO.isRegister() && MO.isUse() && MO.getReg()) {
384 if (MRegisterInfo::isVirtualRegister(MO.getReg())){
385 HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
386 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
387 !ReservedRegisters[MO.getReg()]) {
388 HandlePhysRegUse(MO.getReg(), MI);
393 // Process all defs...
394 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
395 MachineOperand &MO = MI->getOperand(i);
396 if (MO.isRegister() && MO.isDef() && MO.getReg()) {
397 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
398 VarInfo &VRInfo = getVarInfo(MO.getReg());
400 assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
403 VRInfo.Kills.push_back(MI);
404 } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
405 !ReservedRegisters[MO.getReg()]) {
406 HandlePhysRegDef(MO.getReg(), MI);
412 // Handle any virtual assignments from PHI nodes which might be at the
413 // bottom of this basic block. We check all of our successor blocks to see
414 // if they have PHI nodes, and if so, we simulate an assignment at the end
415 // of the current block.
416 if (!PHIVarInfo[MBB->getNumber()].empty()) {
417 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
419 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
420 E = VarInfoVec.end(); I != E; ++I) {
421 VarInfo& VRInfo = getVarInfo(*I);
422 assert(VRInfo.DefInst && "Register use before def (or no def)!");
424 // Only mark it alive only in the block we are representing.
425 MarkVirtRegAliveInBlock(VRInfo, MBB);
429 // Finally, if the last instruction in the block is a return, make sure to mark
430 // it as using all of the live-out values in the function.
431 if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
432 MachineInstr *Ret = &MBB->back();
433 for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
434 E = MF->liveout_end(); I != E; ++I) {
435 assert(MRegisterInfo::isPhysicalRegister(*I) &&
436 "Cannot have a live-in virtual register!");
437 HandlePhysRegUse(*I, Ret);
438 // Add live-out registers as implicit uses.
439 if (Ret->findRegisterUseOperandIdx(*I) == -1)
440 Ret->addRegOperand(*I, false, true);
444 // Loop over PhysRegInfo, killing any registers that are available at the
445 // end of the basic block. This also resets the PhysRegInfo map.
446 for (unsigned i = 0; i != NumRegs; ++i)
448 HandlePhysRegDef(i, 0);
450 // Clear some states between BB's. These are purely local information.
451 for (unsigned i = 0; i != NumRegs; ++i)
452 PhysRegPartDef[i].clear();
453 std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
456 // Convert and transfer the dead / killed information we have gathered into
457 // VirtRegInfo onto MI's.
459 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
460 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
461 if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
462 addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
463 VirtRegInfo[i].Kills[j]);
465 addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
466 VirtRegInfo[i].Kills[j]);
469 // Check to make sure there are no unreachable blocks in the MC CFG for the
470 // function. If so, it is due to a bug in the instruction selector or some
471 // other part of the code generator if this happens.
473 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
474 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
477 delete[] PhysRegInfo;
478 delete[] PhysRegUsed;
479 delete[] PhysRegPartUse;
480 delete[] PhysRegPartDef;
486 /// instructionChanged - When the address of an instruction changes, this
487 /// method should be called so that live variables can update its internal
488 /// data structures. This removes the records for OldMI, transfering them to
489 /// the records for NewMI.
490 void LiveVariables::instructionChanged(MachineInstr *OldMI,
491 MachineInstr *NewMI) {
492 // If the instruction defines any virtual registers, update the VarInfo,
493 // kill and dead information for the instruction.
494 for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
495 MachineOperand &MO = OldMI->getOperand(i);
496 if (MO.isRegister() && MO.getReg() &&
497 MRegisterInfo::isVirtualRegister(MO.getReg())) {
498 unsigned Reg = MO.getReg();
499 VarInfo &VI = getVarInfo(Reg);
503 addVirtualRegisterDead(Reg, NewMI);
505 // Update the defining instruction.
506 if (VI.DefInst == OldMI)
512 addVirtualRegisterKilled(Reg, NewMI);
514 // If this is a kill of the value, update the VI kills list.
515 if (VI.removeKill(OldMI))
516 VI.Kills.push_back(NewMI); // Yes, there was a kill of it
522 /// removeVirtualRegistersKilled - Remove all killed info for the specified
524 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
525 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
526 MachineOperand &MO = MI->getOperand(i);
527 if (MO.isReg() && MO.isKill()) {
529 unsigned Reg = MO.getReg();
530 if (MRegisterInfo::isVirtualRegister(Reg)) {
531 bool removed = getVarInfo(Reg).removeKill(MI);
532 assert(removed && "kill not in register's VarInfo?");
538 /// removeVirtualRegistersDead - Remove all of the dead registers for the
539 /// specified instruction from the live variable information.
540 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
541 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542 MachineOperand &MO = MI->getOperand(i);
543 if (MO.isReg() && MO.isDead()) {
545 unsigned Reg = MO.getReg();
546 if (MRegisterInfo::isVirtualRegister(Reg)) {
547 bool removed = getVarInfo(Reg).removeKill(MI);
548 assert(removed && "kill not in register's VarInfo?");
554 /// analyzePHINodes - Gather information about the PHI nodes in here. In
555 /// particular, we want to map the variable information of a virtual
556 /// register which is used in a PHI node. We map that to the BB the vreg is
559 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
560 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
562 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
563 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
564 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
565 PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()->getNumber()].
566 push_back(BBI->getOperand(i).getReg());