1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/ADT/DepthFirstIterator.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/STLExtras.h"
44 char LiveVariables::ID = 0;
45 INITIALIZE_PASS(LiveVariables, "livevars",
46 "Live Variable Analysis", false, false);
49 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
50 AU.addRequiredID(UnreachableMachineBlockElimID);
52 MachineFunctionPass::getAnalysisUsage(AU);
56 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
57 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
58 if (Kills[i]->getParent() == MBB)
63 void LiveVariables::VarInfo::dump() const {
64 dbgs() << " Alive in blocks: ";
65 for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
66 E = AliveBlocks.end(); I != E; ++I)
68 dbgs() << "\n Killed by:";
70 dbgs() << " No instructions.\n";
72 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
73 dbgs() << "\n #" << i << ": " << *Kills[i];
78 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
79 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
80 assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
81 "getVarInfo: not a virtual register!");
82 RegIdx -= TargetRegisterInfo::FirstVirtualRegister;
83 if (RegIdx >= VirtRegInfo.size()) {
84 if (RegIdx >= 2*VirtRegInfo.size())
85 VirtRegInfo.resize(RegIdx*2);
87 VirtRegInfo.resize(2*VirtRegInfo.size());
89 return VirtRegInfo[RegIdx];
92 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
93 MachineBasicBlock *DefBlock,
94 MachineBasicBlock *MBB,
95 std::vector<MachineBasicBlock*> &WorkList) {
96 unsigned BBNum = MBB->getNumber();
98 // Check to see if this basic block is one of the killing blocks. If so,
100 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
101 if (VRInfo.Kills[i]->getParent() == MBB) {
102 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
106 if (MBB == DefBlock) return; // Terminate recursion
108 if (VRInfo.AliveBlocks.test(BBNum))
109 return; // We already know the block is live
111 // Mark the variable known alive in this bb
112 VRInfo.AliveBlocks.set(BBNum);
114 for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
115 E = MBB->pred_rend(); PI != E; ++PI)
116 WorkList.push_back(*PI);
119 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
120 MachineBasicBlock *DefBlock,
121 MachineBasicBlock *MBB) {
122 std::vector<MachineBasicBlock*> WorkList;
123 MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
125 while (!WorkList.empty()) {
126 MachineBasicBlock *Pred = WorkList.back();
128 MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
132 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
134 assert(MRI->getVRegDef(reg) && "Register use before def!");
136 unsigned BBNum = MBB->getNumber();
138 VarInfo& VRInfo = getVarInfo(reg);
141 // Check to see if this basic block is already a kill block.
142 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
143 // Yes, this register is killed in this basic block already. Increase the
144 // live range by updating the kill instruction.
145 VRInfo.Kills.back() = MI;
150 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
151 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
154 // This situation can occur:
159 // | t2 = phi ... t1 ...
163 // | ... = ... t1 ...
167 // where there is a use in a PHI node that's a predecessor to the defining
168 // block. We don't want to mark all predecessors as having the value "alive"
170 if (MBB == MRI->getVRegDef(reg)->getParent()) return;
172 // Add a new kill entry for this basic block. If this virtual register is
173 // already marked as alive in this basic block, that means it is alive in at
174 // least one of the successor blocks, it's not a kill.
175 if (!VRInfo.AliveBlocks.test(BBNum))
176 VRInfo.Kills.push_back(MI);
178 // Update all dominating blocks to mark them as "known live".
179 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
180 E = MBB->pred_end(); PI != E; ++PI)
181 MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
184 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
185 VarInfo &VRInfo = getVarInfo(Reg);
187 if (VRInfo.AliveBlocks.empty())
188 // If vr is not alive in any block, then defaults to dead.
189 VRInfo.Kills.push_back(MI);
192 /// FindLastPartialDef - Return the last partial def of the specified register.
193 /// Also returns the sub-registers that're defined by the instruction.
194 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
195 SmallSet<unsigned,4> &PartDefRegs) {
196 unsigned LastDefReg = 0;
197 unsigned LastDefDist = 0;
198 MachineInstr *LastDef = NULL;
199 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
200 unsigned SubReg = *SubRegs; ++SubRegs) {
201 MachineInstr *Def = PhysRegDef[SubReg];
204 unsigned Dist = DistanceMap[Def];
205 if (Dist > LastDefDist) {
215 PartDefRegs.insert(LastDefReg);
216 for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
217 MachineOperand &MO = LastDef->getOperand(i);
218 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
220 unsigned DefReg = MO.getReg();
221 if (TRI->isSubRegister(Reg, DefReg)) {
222 PartDefRegs.insert(DefReg);
223 for (const unsigned *SubRegs = TRI->getSubRegisters(DefReg);
224 unsigned SubReg = *SubRegs; ++SubRegs)
225 PartDefRegs.insert(SubReg);
231 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
232 /// implicit defs to a machine instruction if there was an earlier def of its
234 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
235 MachineInstr *LastDef = PhysRegDef[Reg];
236 // If there was a previous use or a "full" def all is well.
237 if (!LastDef && !PhysRegUse[Reg]) {
238 // Otherwise, the last sub-register def implicitly defines this register.
241 // AL = ... <imp-def EAX>, <imp-kill AH>
245 // All of the sub-registers must have been defined before the use of Reg!
246 SmallSet<unsigned, 4> PartDefRegs;
247 MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
248 // If LastPartialDef is NULL, it must be using a livein register.
249 if (LastPartialDef) {
250 LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
252 PhysRegDef[Reg] = LastPartialDef;
253 SmallSet<unsigned, 8> Processed;
254 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
255 unsigned SubReg = *SubRegs; ++SubRegs) {
256 if (Processed.count(SubReg))
258 if (PartDefRegs.count(SubReg))
260 // This part of Reg was defined before the last partial def. It's killed
262 LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
265 PhysRegDef[SubReg] = LastPartialDef;
266 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
267 Processed.insert(*SS);
271 else if (LastDef && !PhysRegUse[Reg] &&
272 !LastDef->findRegisterDefOperand(Reg))
273 // Last def defines the super register, add an implicit def of reg.
274 LastDef->addOperand(MachineOperand::CreateReg(Reg,
275 true/*IsDef*/, true/*IsImp*/));
277 // Remember this use.
278 PhysRegUse[Reg] = MI;
279 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
280 unsigned SubReg = *SubRegs; ++SubRegs)
281 PhysRegUse[SubReg] = MI;
284 /// FindLastRefOrPartRef - Return the last reference or partial reference of
285 /// the specified register.
286 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
287 MachineInstr *LastDef = PhysRegDef[Reg];
288 MachineInstr *LastUse = PhysRegUse[Reg];
289 if (!LastDef && !LastUse)
292 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
293 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
294 unsigned LastPartDefDist = 0;
295 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
296 unsigned SubReg = *SubRegs; ++SubRegs) {
297 MachineInstr *Def = PhysRegDef[SubReg];
298 if (Def && Def != LastDef) {
299 // There was a def of this sub-register in between. This is a partial
300 // def, keep track of the last one.
301 unsigned Dist = DistanceMap[Def];
302 if (Dist > LastPartDefDist)
303 LastPartDefDist = Dist;
304 } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
305 unsigned Dist = DistanceMap[Use];
306 if (Dist > LastRefOrPartRefDist) {
307 LastRefOrPartRefDist = Dist;
308 LastRefOrPartRef = Use;
313 return LastRefOrPartRef;
316 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
317 MachineInstr *LastDef = PhysRegDef[Reg];
318 MachineInstr *LastUse = PhysRegUse[Reg];
319 if (!LastDef && !LastUse)
322 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
323 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
324 // The whole register is used.
329 // = AL, AX<imp-use, kill>
332 // Or whole register is defined, but not used at all.
337 // Or whole register is defined, but only partly used.
338 // AX<dead> = AL<imp-def>
341 MachineInstr *LastPartDef = 0;
342 unsigned LastPartDefDist = 0;
343 SmallSet<unsigned, 8> PartUses;
344 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
345 unsigned SubReg = *SubRegs; ++SubRegs) {
346 MachineInstr *Def = PhysRegDef[SubReg];
347 if (Def && Def != LastDef) {
348 // There was a def of this sub-register in between. This is a partial
349 // def, keep track of the last one.
350 unsigned Dist = DistanceMap[Def];
351 if (Dist > LastPartDefDist) {
352 LastPartDefDist = Dist;
357 if (MachineInstr *Use = PhysRegUse[SubReg]) {
358 PartUses.insert(SubReg);
359 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
360 PartUses.insert(*SS);
361 unsigned Dist = DistanceMap[Use];
362 if (Dist > LastRefOrPartRefDist) {
363 LastRefOrPartRefDist = Dist;
364 LastRefOrPartRef = Use;
369 if (!PhysRegUse[Reg]) {
370 // Partial uses. Mark register def dead and add implicit def of
371 // sub-registers which are used.
372 // EAX<dead> = op AL<imp-def>
373 // That is, EAX def is dead but AL def extends pass it.
374 PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
375 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
376 unsigned SubReg = *SubRegs; ++SubRegs) {
377 if (!PartUses.count(SubReg))
380 if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
381 MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
384 assert(!MO->isDead());
388 PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
389 true/*IsDef*/, true/*IsImp*/));
390 MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
392 LastSubRef->addRegisterKilled(SubReg, TRI, true);
394 LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
395 PhysRegUse[SubReg] = LastRefOrPartRef;
396 for (const unsigned *SSRegs = TRI->getSubRegisters(SubReg);
397 unsigned SSReg = *SSRegs; ++SSRegs)
398 PhysRegUse[SSReg] = LastRefOrPartRef;
400 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
403 } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
405 // The last partial def kills the register.
406 LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
407 true/*IsImp*/, true/*IsKill*/));
410 LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
411 bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
412 // If the last reference is the last def, then it's not used at all.
413 // That is, unless we are currently processing the last reference itself.
414 LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
416 // If we are adding a subreg def and the superreg def is marked early
417 // clobber, add an early clobber marker to the subreg def.
418 MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
420 MO->setIsEarlyClobber();
424 LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
428 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
429 SmallVector<unsigned, 4> &Defs) {
430 // What parts of the register are previously defined?
431 SmallSet<unsigned, 32> Live;
432 if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
434 for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
437 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
438 unsigned SubReg = *SubRegs; ++SubRegs) {
439 // If a register isn't itself defined, but all parts that make up of it
440 // are defined, then consider it also defined.
445 if (Live.count(SubReg))
447 if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
449 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
455 // Start from the largest piece, find the last time any part of the register
457 HandlePhysRegKill(Reg, MI);
458 // Only some of the sub-registers are used.
459 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
460 unsigned SubReg = *SubRegs; ++SubRegs) {
461 if (!Live.count(SubReg))
462 // Skip if this sub-register isn't defined.
464 HandlePhysRegKill(SubReg, MI);
468 Defs.push_back(Reg); // Remember this def.
471 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
472 SmallVector<unsigned, 4> &Defs) {
473 while (!Defs.empty()) {
474 unsigned Reg = Defs.back();
476 PhysRegDef[Reg] = MI;
477 PhysRegUse[Reg] = NULL;
478 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
479 unsigned SubReg = *SubRegs; ++SubRegs) {
480 PhysRegDef[SubReg] = MI;
481 PhysRegUse[SubReg] = NULL;
486 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
488 MRI = &mf.getRegInfo();
489 TRI = MF->getTarget().getRegisterInfo();
491 ReservedRegisters = TRI->getReservedRegs(mf);
493 unsigned NumRegs = TRI->getNumRegs();
494 PhysRegDef = new MachineInstr*[NumRegs];
495 PhysRegUse = new MachineInstr*[NumRegs];
496 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
497 std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0);
498 std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0);
501 /// Get some space for a respectable number of registers.
502 VirtRegInfo.resize(64);
506 // Calculate live variable information in depth first order on the CFG of the
507 // function. This guarantees that we will see the definition of a virtual
508 // register before its uses due to dominance properties of SSA (except for PHI
509 // nodes, which are treated as a special case).
510 MachineBasicBlock *Entry = MF->begin();
511 SmallPtrSet<MachineBasicBlock*,16> Visited;
513 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
514 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
516 MachineBasicBlock *MBB = *DFI;
518 // Mark live-in registers as live-in.
519 SmallVector<unsigned, 4> Defs;
520 for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
521 EE = MBB->livein_end(); II != EE; ++II) {
522 assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
523 "Cannot have a live-in virtual register!");
524 HandlePhysRegDef(*II, 0, Defs);
527 // Loop over all of the instructions, processing them.
530 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
532 MachineInstr *MI = I;
533 if (MI->isDebugValue())
535 DistanceMap.insert(std::make_pair(MI, Dist++));
537 // Process all of the operands of the instruction...
538 unsigned NumOperandsToProcess = MI->getNumOperands();
540 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
541 // of the uses. They will be handled in other basic blocks.
543 NumOperandsToProcess = 1;
545 // Clear kill and dead markers. LV will recompute them.
546 SmallVector<unsigned, 4> UseRegs;
547 SmallVector<unsigned, 4> DefRegs;
548 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
549 MachineOperand &MO = MI->getOperand(i);
550 if (!MO.isReg() || MO.getReg() == 0)
552 unsigned MOReg = MO.getReg();
555 UseRegs.push_back(MOReg);
556 } else /*MO.isDef()*/ {
558 DefRegs.push_back(MOReg);
563 for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
564 unsigned MOReg = UseRegs[i];
565 if (TargetRegisterInfo::isVirtualRegister(MOReg))
566 HandleVirtRegUse(MOReg, MBB, MI);
567 else if (!ReservedRegisters[MOReg])
568 HandlePhysRegUse(MOReg, MI);
572 for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
573 unsigned MOReg = DefRegs[i];
574 if (TargetRegisterInfo::isVirtualRegister(MOReg))
575 HandleVirtRegDef(MOReg, MI);
576 else if (!ReservedRegisters[MOReg])
577 HandlePhysRegDef(MOReg, MI, Defs);
579 UpdatePhysRegDefs(MI, Defs);
582 // Handle any virtual assignments from PHI nodes which might be at the
583 // bottom of this basic block. We check all of our successor blocks to see
584 // if they have PHI nodes, and if so, we simulate an assignment at the end
585 // of the current block.
586 if (!PHIVarInfo[MBB->getNumber()].empty()) {
587 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
589 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
590 E = VarInfoVec.end(); I != E; ++I)
591 // Mark it alive only in the block we are representing.
592 MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
596 // Finally, if the last instruction in the block is a return, make sure to
597 // mark it as using all of the live-out values in the function.
598 // Things marked both call and return are tail calls; do not do this for
599 // them. The tail callee need not take the same registers as input
600 // that it produces as output, and there are dependencies for its input
601 // registers elsewhere.
602 if (!MBB->empty() && MBB->back().getDesc().isReturn()
603 && !MBB->back().getDesc().isCall()) {
604 MachineInstr *Ret = &MBB->back();
606 for (MachineRegisterInfo::liveout_iterator
607 I = MF->getRegInfo().liveout_begin(),
608 E = MF->getRegInfo().liveout_end(); I != E; ++I) {
609 assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
610 "Cannot have a live-out virtual register!");
611 HandlePhysRegUse(*I, Ret);
613 // Add live-out registers as implicit uses.
614 if (!Ret->readsRegister(*I))
615 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
619 // Loop over PhysRegDef / PhysRegUse, killing any registers that are
620 // available at the end of the basic block.
621 for (unsigned i = 0; i != NumRegs; ++i)
622 if (PhysRegDef[i] || PhysRegUse[i])
623 HandlePhysRegDef(i, 0, Defs);
625 std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0);
626 std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0);
629 // Convert and transfer the dead / killed information we have gathered into
630 // VirtRegInfo onto MI's.
631 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
632 for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
633 if (VirtRegInfo[i].Kills[j] ==
634 MRI->getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
636 .Kills[j]->addRegisterDead(i +
637 TargetRegisterInfo::FirstVirtualRegister,
641 .Kills[j]->addRegisterKilled(i +
642 TargetRegisterInfo::FirstVirtualRegister,
645 // Check to make sure there are no unreachable blocks in the MC CFG for the
646 // function. If so, it is due to a bug in the instruction selector or some
647 // other part of the code generator if this happens.
649 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
650 assert(Visited.count(&*i) != 0 && "unreachable basic block found");
660 /// replaceKillInstruction - Update register kill info by replacing a kill
661 /// instruction with a new one.
662 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
663 MachineInstr *NewMI) {
664 VarInfo &VI = getVarInfo(Reg);
665 std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
668 /// removeVirtualRegistersKilled - Remove all killed info for the specified
670 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
671 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
672 MachineOperand &MO = MI->getOperand(i);
673 if (MO.isReg() && MO.isKill()) {
675 unsigned Reg = MO.getReg();
676 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
677 bool removed = getVarInfo(Reg).removeKill(MI);
678 assert(removed && "kill not in register's VarInfo?");
685 /// analyzePHINodes - Gather information about the PHI nodes in here. In
686 /// particular, we want to map the variable information of a virtual register
687 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
689 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
690 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
692 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
693 BBI != BBE && BBI->isPHI(); ++BBI)
694 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
695 PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
696 .push_back(BBI->getOperand(i).getReg());
699 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
701 MachineRegisterInfo &MRI) {
702 unsigned Num = MBB.getNumber();
704 // Reg is live-through.
705 if (AliveBlocks.test(Num))
708 // Registers defined in MBB cannot be live in.
709 const MachineInstr *Def = MRI.getVRegDef(Reg);
710 if (Def && Def->getParent() == &MBB)
713 // Reg was not defined in MBB, was it killed here?
714 return findKill(&MBB);
717 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
718 LiveVariables::VarInfo &VI = getVarInfo(Reg);
720 // Loop over all of the successors of the basic block, checking to see if
721 // the value is either live in the block, or if it is killed in the block.
722 std::vector<MachineBasicBlock*> OpSuccBlocks;
723 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
724 E = MBB.succ_end(); SI != E; ++SI) {
725 MachineBasicBlock *SuccMBB = *SI;
727 // Is it alive in this successor?
728 unsigned SuccIdx = SuccMBB->getNumber();
729 if (VI.AliveBlocks.test(SuccIdx))
731 OpSuccBlocks.push_back(SuccMBB);
734 // Check to see if this value is live because there is a use in a successor
736 switch (OpSuccBlocks.size()) {
738 MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
739 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
740 if (VI.Kills[i]->getParent() == SuccMBB)
745 MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
746 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
747 if (VI.Kills[i]->getParent() == SuccMBB1 ||
748 VI.Kills[i]->getParent() == SuccMBB2)
753 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
754 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
755 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
756 VI.Kills[i]->getParent()))
762 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
763 /// variables that are live out of DomBB will be marked as passing live through
765 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
766 MachineBasicBlock *DomBB,
767 MachineBasicBlock *SuccBB) {
768 const unsigned NumNew = BB->getNumber();
770 // All registers used by PHI nodes in SuccBB must be live through BB.
771 for (MachineBasicBlock::const_iterator BBI = SuccBB->begin(),
772 BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI)
773 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
774 if (BBI->getOperand(i+1).getMBB() == BB)
775 getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
777 // Update info for all live variables
778 for (unsigned Reg = TargetRegisterInfo::FirstVirtualRegister,
779 E = MRI->getLastVirtReg()+1; Reg != E; ++Reg) {
780 VarInfo &VI = getVarInfo(Reg);
781 if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI))
782 VI.AliveBlocks.set(NumNew);