Teach LiveVariables to handle <undef> operands.
[oota-llvm.git] / lib / CodeGen / LiveVariables.cpp
1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
15 // killed).
16 //
17 // This class computes live variables using a 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.
26 //
27 //===----------------------------------------------------------------------===//
28
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/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Support/ErrorHandling.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"
41 #include <algorithm>
42 using namespace llvm;
43
44 char LiveVariables::ID = 0;
45 char &llvm::LiveVariablesID = LiveVariables::ID;
46 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
47                 "Live Variable Analysis", false, false)
48 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
49 INITIALIZE_PASS_END(LiveVariables, "livevars",
50                 "Live Variable Analysis", false, false)
51
52
53 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
54   AU.addRequiredID(UnreachableMachineBlockElimID);
55   AU.setPreservesAll();
56   MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
59 MachineInstr *
60 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
61   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
62     if (Kills[i]->getParent() == MBB)
63       return Kills[i];
64   return NULL;
65 }
66
67 void LiveVariables::VarInfo::dump() const {
68   dbgs() << "  Alive in blocks: ";
69   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
70            E = AliveBlocks.end(); I != E; ++I)
71     dbgs() << *I << ", ";
72   dbgs() << "\n  Killed by:";
73   if (Kills.empty())
74     dbgs() << " No instructions.\n";
75   else {
76     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
77       dbgs() << "\n    #" << i << ": " << *Kills[i];
78     dbgs() << "\n";
79   }
80 }
81
82 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
83 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
84   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
85          "getVarInfo: not a virtual register!");
86   VirtRegInfo.grow(RegIdx);
87   return VirtRegInfo[RegIdx];
88 }
89
90 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
91                                             MachineBasicBlock *DefBlock,
92                                             MachineBasicBlock *MBB,
93                                     std::vector<MachineBasicBlock*> &WorkList) {
94   unsigned BBNum = MBB->getNumber();
95
96   // Check to see if this basic block is one of the killing blocks.  If so,
97   // remove it.
98   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
99     if (VRInfo.Kills[i]->getParent() == MBB) {
100       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
101       break;
102     }
103
104   if (MBB == DefBlock) return;  // Terminate recursion
105
106   if (VRInfo.AliveBlocks.test(BBNum))
107     return;  // We already know the block is live
108
109   // Mark the variable known alive in this bb
110   VRInfo.AliveBlocks.set(BBNum);
111
112   assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
113   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
114 }
115
116 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
117                                             MachineBasicBlock *DefBlock,
118                                             MachineBasicBlock *MBB) {
119   std::vector<MachineBasicBlock*> WorkList;
120   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
121
122   while (!WorkList.empty()) {
123     MachineBasicBlock *Pred = WorkList.back();
124     WorkList.pop_back();
125     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
126   }
127 }
128
129 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
130                                      MachineInstr *MI) {
131   assert(MRI->getVRegDef(reg) && "Register use before def!");
132
133   unsigned BBNum = MBB->getNumber();
134
135   VarInfo& VRInfo = getVarInfo(reg);
136
137   // Check to see if this basic block is already a kill block.
138   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
139     // Yes, this register is killed in this basic block already. Increase the
140     // live range by updating the kill instruction.
141     VRInfo.Kills.back() = MI;
142     return;
143   }
144
145 #ifndef NDEBUG
146   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
147     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
148 #endif
149
150   // This situation can occur:
151   //
152   //     ,------.
153   //     |      |
154   //     |      v
155   //     |   t2 = phi ... t1 ...
156   //     |      |
157   //     |      v
158   //     |   t1 = ...
159   //     |  ... = ... t1 ...
160   //     |      |
161   //     `------'
162   //
163   // where there is a use in a PHI node that's a predecessor to the defining
164   // block. We don't want to mark all predecessors as having the value "alive"
165   // in this case.
166   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
167
168   // Add a new kill entry for this basic block. If this virtual register is
169   // already marked as alive in this basic block, that means it is alive in at
170   // least one of the successor blocks, it's not a kill.
171   if (!VRInfo.AliveBlocks.test(BBNum))
172     VRInfo.Kills.push_back(MI);
173
174   // Update all dominating blocks to mark them as "known live".
175   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
176          E = MBB->pred_end(); PI != E; ++PI)
177     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
178 }
179
180 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
181   VarInfo &VRInfo = getVarInfo(Reg);
182
183   if (VRInfo.AliveBlocks.empty())
184     // If vr is not alive in any block, then defaults to dead.
185     VRInfo.Kills.push_back(MI);
186 }
187
188 /// FindLastPartialDef - Return the last partial def of the specified register.
189 /// Also returns the sub-registers that're defined by the instruction.
190 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
191                                             SmallSet<unsigned,4> &PartDefRegs) {
192   unsigned LastDefReg = 0;
193   unsigned LastDefDist = 0;
194   MachineInstr *LastDef = NULL;
195   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
196     unsigned SubReg = *SubRegs;
197     MachineInstr *Def = PhysRegDef[SubReg];
198     if (!Def)
199       continue;
200     unsigned Dist = DistanceMap[Def];
201     if (Dist > LastDefDist) {
202       LastDefReg  = SubReg;
203       LastDef     = Def;
204       LastDefDist = Dist;
205     }
206   }
207
208   if (!LastDef)
209     return 0;
210
211   PartDefRegs.insert(LastDefReg);
212   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
213     MachineOperand &MO = LastDef->getOperand(i);
214     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
215       continue;
216     unsigned DefReg = MO.getReg();
217     if (TRI->isSubRegister(Reg, DefReg)) {
218       PartDefRegs.insert(DefReg);
219       for (MCSubRegIterator SubRegs(DefReg, TRI); SubRegs.isValid(); ++SubRegs)
220         PartDefRegs.insert(*SubRegs);
221     }
222   }
223   return LastDef;
224 }
225
226 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
227 /// implicit defs to a machine instruction if there was an earlier def of its
228 /// super-register.
229 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
230   MachineInstr *LastDef = PhysRegDef[Reg];
231   // If there was a previous use or a "full" def all is well.
232   if (!LastDef && !PhysRegUse[Reg]) {
233     // Otherwise, the last sub-register def implicitly defines this register.
234     // e.g.
235     // AH =
236     // AL = ... <imp-def EAX>, <imp-kill AH>
237     //    = AH
238     // ...
239     //    = EAX
240     // All of the sub-registers must have been defined before the use of Reg!
241     SmallSet<unsigned, 4> PartDefRegs;
242     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
243     // If LastPartialDef is NULL, it must be using a livein register.
244     if (LastPartialDef) {
245       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
246                                                            true/*IsImp*/));
247       PhysRegDef[Reg] = LastPartialDef;
248       SmallSet<unsigned, 8> Processed;
249       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
250         unsigned SubReg = *SubRegs;
251         if (Processed.count(SubReg))
252           continue;
253         if (PartDefRegs.count(SubReg))
254           continue;
255         // This part of Reg was defined before the last partial def. It's killed
256         // here.
257         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
258                                                              false/*IsDef*/,
259                                                              true/*IsImp*/));
260         PhysRegDef[SubReg] = LastPartialDef;
261         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
262           Processed.insert(*SS);
263       }
264     }
265   } else if (LastDef && !PhysRegUse[Reg] &&
266              !LastDef->findRegisterDefOperand(Reg))
267     // Last def defines the super register, add an implicit def of reg.
268     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
269                                                   true/*IsImp*/));
270
271   // Remember this use.
272   PhysRegUse[Reg]  = MI;
273   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
274     PhysRegUse[*SubRegs] =  MI;
275 }
276
277 /// FindLastRefOrPartRef - Return the last reference or partial reference of
278 /// the specified register.
279 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
280   MachineInstr *LastDef = PhysRegDef[Reg];
281   MachineInstr *LastUse = PhysRegUse[Reg];
282   if (!LastDef && !LastUse)
283     return 0;
284
285   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
286   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
287   unsigned LastPartDefDist = 0;
288   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
289     unsigned SubReg = *SubRegs;
290     MachineInstr *Def = PhysRegDef[SubReg];
291     if (Def && Def != LastDef) {
292       // There was a def of this sub-register in between. This is a partial
293       // def, keep track of the last one.
294       unsigned Dist = DistanceMap[Def];
295       if (Dist > LastPartDefDist)
296         LastPartDefDist = Dist;
297     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
298       unsigned Dist = DistanceMap[Use];
299       if (Dist > LastRefOrPartRefDist) {
300         LastRefOrPartRefDist = Dist;
301         LastRefOrPartRef = Use;
302       }
303     }
304   }
305
306   return LastRefOrPartRef;
307 }
308
309 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
310   MachineInstr *LastDef = PhysRegDef[Reg];
311   MachineInstr *LastUse = PhysRegUse[Reg];
312   if (!LastDef && !LastUse)
313     return false;
314
315   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
316   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
317   // The whole register is used.
318   // AL =
319   // AH =
320   //
321   //    = AX
322   //    = AL, AX<imp-use, kill>
323   // AX =
324   //
325   // Or whole register is defined, but not used at all.
326   // AX<dead> =
327   // ...
328   // AX =
329   //
330   // Or whole register is defined, but only partly used.
331   // AX<dead> = AL<imp-def>
332   //    = AL<kill>
333   // AX =
334   MachineInstr *LastPartDef = 0;
335   unsigned LastPartDefDist = 0;
336   SmallSet<unsigned, 8> PartUses;
337   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
338     unsigned SubReg = *SubRegs;
339     MachineInstr *Def = PhysRegDef[SubReg];
340     if (Def && Def != LastDef) {
341       // There was a def of this sub-register in between. This is a partial
342       // def, keep track of the last one.
343       unsigned Dist = DistanceMap[Def];
344       if (Dist > LastPartDefDist) {
345         LastPartDefDist = Dist;
346         LastPartDef = Def;
347       }
348       continue;
349     }
350     if (MachineInstr *Use = PhysRegUse[SubReg]) {
351       PartUses.insert(SubReg);
352       for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
353         PartUses.insert(*SS);
354       unsigned Dist = DistanceMap[Use];
355       if (Dist > LastRefOrPartRefDist) {
356         LastRefOrPartRefDist = Dist;
357         LastRefOrPartRef = Use;
358       }
359     }
360   }
361
362   if (!PhysRegUse[Reg]) {
363     // Partial uses. Mark register def dead and add implicit def of
364     // sub-registers which are used.
365     // EAX<dead>  = op  AL<imp-def>
366     // That is, EAX def is dead but AL def extends pass it.
367     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
368     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
369       unsigned SubReg = *SubRegs;
370       if (!PartUses.count(SubReg))
371         continue;
372       bool NeedDef = true;
373       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
374         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
375         if (MO) {
376           NeedDef = false;
377           assert(!MO->isDead());
378         }
379       }
380       if (NeedDef)
381         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
382                                                  true/*IsDef*/, true/*IsImp*/));
383       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
384       if (LastSubRef)
385         LastSubRef->addRegisterKilled(SubReg, TRI, true);
386       else {
387         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
388         PhysRegUse[SubReg] = LastRefOrPartRef;
389         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
390           PhysRegUse[*SS] = LastRefOrPartRef;
391       }
392       for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
393         PartUses.erase(*SS);
394     }
395   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
396     if (LastPartDef)
397       // The last partial def kills the register.
398       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
399                                                 true/*IsImp*/, true/*IsKill*/));
400     else {
401       MachineOperand *MO =
402         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
403       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
404       // If the last reference is the last def, then it's not used at all.
405       // That is, unless we are currently processing the last reference itself.
406       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
407       if (NeedEC) {
408         // If we are adding a subreg def and the superreg def is marked early
409         // clobber, add an early clobber marker to the subreg def.
410         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
411         if (MO)
412           MO->setIsEarlyClobber();
413       }
414     }
415   } else
416     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
417   return true;
418 }
419
420 void LiveVariables::HandleRegMask(const MachineOperand &MO) {
421   // Call HandlePhysRegKill() for all live registers clobbered by Mask.
422   // Clobbered registers are always dead, sp there is no need to use
423   // HandlePhysRegDef().
424   for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
425     // Skip dead regs.
426     if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
427       continue;
428     // Skip mask-preserved regs.
429     if (!MO.clobbersPhysReg(Reg))
430       continue;
431     // Kill the largest clobbered super-register.
432     // This avoids needless implicit operands.
433     unsigned Super = Reg;
434     for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
435       if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
436         Super = *SR;
437     HandlePhysRegKill(Super, 0);
438   }
439 }
440
441 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
442                                      SmallVector<unsigned, 4> &Defs) {
443   // What parts of the register are previously defined?
444   SmallSet<unsigned, 32> Live;
445   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
446     Live.insert(Reg);
447     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
448       Live.insert(*SubRegs);
449   } else {
450     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
451       unsigned SubReg = *SubRegs;
452       // If a register isn't itself defined, but all parts that make up of it
453       // are defined, then consider it also defined.
454       // e.g.
455       // AL =
456       // AH =
457       //    = AX
458       if (Live.count(SubReg))
459         continue;
460       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
461         Live.insert(SubReg);
462         for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
463           Live.insert(*SS);
464       }
465     }
466   }
467
468   // Start from the largest piece, find the last time any part of the register
469   // is referenced.
470   HandlePhysRegKill(Reg, MI);
471   // Only some of the sub-registers are used.
472   for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
473     unsigned SubReg = *SubRegs;
474     if (!Live.count(SubReg))
475       // Skip if this sub-register isn't defined.
476       continue;
477     HandlePhysRegKill(SubReg, MI);
478   }
479
480   if (MI)
481     Defs.push_back(Reg);  // Remember this def.
482 }
483
484 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
485                                       SmallVector<unsigned, 4> &Defs) {
486   while (!Defs.empty()) {
487     unsigned Reg = Defs.back();
488     Defs.pop_back();
489     PhysRegDef[Reg]  = MI;
490     PhysRegUse[Reg]  = NULL;
491     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
492       unsigned SubReg = *SubRegs;
493       PhysRegDef[SubReg]  = MI;
494       PhysRegUse[SubReg]  = NULL;
495     }
496   }
497 }
498
499 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
500   MF = &mf;
501   MRI = &mf.getRegInfo();
502   TRI = MF->getTarget().getRegisterInfo();
503
504   ReservedRegisters = TRI->getReservedRegs(mf);
505
506   unsigned NumRegs = TRI->getNumRegs();
507   PhysRegDef  = new MachineInstr*[NumRegs];
508   PhysRegUse  = new MachineInstr*[NumRegs];
509   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
510   std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
511   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
512   PHIJoins.clear();
513
514   // FIXME: LiveIntervals will be updated to remove its dependence on
515   // LiveVariables to improve compilation time and eliminate bizarre pass
516   // dependencies. Until then, we can't change much in -O0.
517   if (!MRI->isSSA())
518     report_fatal_error("regalloc=... not currently supported with -O0");
519
520   analyzePHINodes(mf);
521
522   // Calculate live variable information in depth first order on the CFG of the
523   // function.  This guarantees that we will see the definition of a virtual
524   // register before its uses due to dominance properties of SSA (except for PHI
525   // nodes, which are treated as a special case).
526   MachineBasicBlock *Entry = MF->begin();
527   SmallPtrSet<MachineBasicBlock*,16> Visited;
528
529   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
530          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
531        DFI != E; ++DFI) {
532     MachineBasicBlock *MBB = *DFI;
533
534     // Mark live-in registers as live-in.
535     SmallVector<unsigned, 4> Defs;
536     for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
537            EE = MBB->livein_end(); II != EE; ++II) {
538       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
539              "Cannot have a live-in virtual register!");
540       HandlePhysRegDef(*II, 0, Defs);
541     }
542
543     // Loop over all of the instructions, processing them.
544     DistanceMap.clear();
545     unsigned Dist = 0;
546     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
547          I != E; ++I) {
548       MachineInstr *MI = I;
549       if (MI->isDebugValue())
550         continue;
551       DistanceMap.insert(std::make_pair(MI, Dist++));
552
553       // Process all of the operands of the instruction...
554       unsigned NumOperandsToProcess = MI->getNumOperands();
555
556       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
557       // of the uses.  They will be handled in other basic blocks.
558       if (MI->isPHI())
559         NumOperandsToProcess = 1;
560
561       // Clear kill and dead markers. LV will recompute them.
562       SmallVector<unsigned, 4> UseRegs;
563       SmallVector<unsigned, 4> DefRegs;
564       SmallVector<unsigned, 1> RegMasks;
565       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
566         MachineOperand &MO = MI->getOperand(i);
567         if (MO.isRegMask()) {
568           RegMasks.push_back(i);
569           continue;
570         }
571         if (!MO.isReg() || MO.getReg() == 0)
572           continue;
573         unsigned MOReg = MO.getReg();
574         if (MO.isUse()) {
575           MO.setIsKill(false);
576           if (MO.readsReg())
577             UseRegs.push_back(MOReg);
578         } else /*MO.isDef()*/ {
579           MO.setIsDead(false);
580           DefRegs.push_back(MOReg);
581         }
582       }
583
584       // Process all uses.
585       for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
586         unsigned MOReg = UseRegs[i];
587         if (TargetRegisterInfo::isVirtualRegister(MOReg))
588           HandleVirtRegUse(MOReg, MBB, MI);
589         else if (!ReservedRegisters[MOReg])
590           HandlePhysRegUse(MOReg, MI);
591       }
592
593       // Process all masked registers. (Call clobbers).
594       for (unsigned i = 0, e = RegMasks.size(); i != e; ++i)
595         HandleRegMask(MI->getOperand(RegMasks[i]));
596
597       // Process all defs.
598       for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
599         unsigned MOReg = DefRegs[i];
600         if (TargetRegisterInfo::isVirtualRegister(MOReg))
601           HandleVirtRegDef(MOReg, MI);
602         else if (!ReservedRegisters[MOReg])
603           HandlePhysRegDef(MOReg, MI, Defs);
604       }
605       UpdatePhysRegDefs(MI, Defs);
606     }
607
608     // Handle any virtual assignments from PHI nodes which might be at the
609     // bottom of this basic block.  We check all of our successor blocks to see
610     // if they have PHI nodes, and if so, we simulate an assignment at the end
611     // of the current block.
612     if (!PHIVarInfo[MBB->getNumber()].empty()) {
613       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
614
615       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
616              E = VarInfoVec.end(); I != E; ++I)
617         // Mark it alive only in the block we are representing.
618         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
619                                 MBB);
620     }
621
622     // Finally, if the last instruction in the block is a return, make sure to
623     // mark it as using all of the live-out values in the function.
624     // Things marked both call and return are tail calls; do not do this for
625     // them.  The tail callee need not take the same registers as input
626     // that it produces as output, and there are dependencies for its input
627     // registers elsewhere.
628     if (!MBB->empty() && MBB->back().isReturn()
629         && !MBB->back().isCall()) {
630       MachineInstr *Ret = &MBB->back();
631
632       for (MachineRegisterInfo::liveout_iterator
633            I = MF->getRegInfo().liveout_begin(),
634            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
635         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
636                "Cannot have a live-out virtual register!");
637         HandlePhysRegUse(*I, Ret);
638
639         // Add live-out registers as implicit uses.
640         if (!Ret->readsRegister(*I))
641           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
642       }
643     }
644
645     // MachineCSE may CSE instructions which write to non-allocatable physical
646     // registers across MBBs. Remember if any reserved register is liveout.
647     SmallSet<unsigned, 4> LiveOuts;
648     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
649            SE = MBB->succ_end(); SI != SE; ++SI) {
650       MachineBasicBlock *SuccMBB = *SI;
651       if (SuccMBB->isLandingPad())
652         continue;
653       for (MachineBasicBlock::livein_iterator LI = SuccMBB->livein_begin(),
654              LE = SuccMBB->livein_end(); LI != LE; ++LI) {
655         unsigned LReg = *LI;
656         if (!TRI->isInAllocatableClass(LReg))
657           // Ignore other live-ins, e.g. those that are live into landing pads.
658           LiveOuts.insert(LReg);
659       }
660     }
661
662     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
663     // available at the end of the basic block.
664     for (unsigned i = 0; i != NumRegs; ++i)
665       if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
666         HandlePhysRegDef(i, 0, Defs);
667
668     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
669     std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
670   }
671
672   // Convert and transfer the dead / killed information we have gathered into
673   // VirtRegInfo onto MI's.
674   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
675     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
676     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
677       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
678         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
679       else
680         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
681   }
682
683   // Check to make sure there are no unreachable blocks in the MC CFG for the
684   // function.  If so, it is due to a bug in the instruction selector or some
685   // other part of the code generator if this happens.
686 #ifndef NDEBUG
687   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
688     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
689 #endif
690
691   delete[] PhysRegDef;
692   delete[] PhysRegUse;
693   delete[] PHIVarInfo;
694
695   return false;
696 }
697
698 /// replaceKillInstruction - Update register kill info by replacing a kill
699 /// instruction with a new one.
700 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
701                                            MachineInstr *NewMI) {
702   VarInfo &VI = getVarInfo(Reg);
703   std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
704 }
705
706 /// removeVirtualRegistersKilled - Remove all killed info for the specified
707 /// instruction.
708 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
709   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
710     MachineOperand &MO = MI->getOperand(i);
711     if (MO.isReg() && MO.isKill()) {
712       MO.setIsKill(false);
713       unsigned Reg = MO.getReg();
714       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
715         bool removed = getVarInfo(Reg).removeKill(MI);
716         assert(removed && "kill not in register's VarInfo?");
717         (void)removed;
718       }
719     }
720   }
721 }
722
723 /// analyzePHINodes - Gather information about the PHI nodes in here. In
724 /// particular, we want to map the variable information of a virtual register
725 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
726 ///
727 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
728   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
729        I != E; ++I)
730     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
731          BBI != BBE && BBI->isPHI(); ++BBI)
732       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
733         if (BBI->getOperand(i).readsReg())
734           PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
735             .push_back(BBI->getOperand(i).getReg());
736 }
737
738 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
739                                       unsigned Reg,
740                                       MachineRegisterInfo &MRI) {
741   unsigned Num = MBB.getNumber();
742
743   // Reg is live-through.
744   if (AliveBlocks.test(Num))
745     return true;
746
747   // Registers defined in MBB cannot be live in.
748   const MachineInstr *Def = MRI.getVRegDef(Reg);
749   if (Def && Def->getParent() == &MBB)
750     return false;
751
752  // Reg was not defined in MBB, was it killed here?
753   return findKill(&MBB);
754 }
755
756 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
757   LiveVariables::VarInfo &VI = getVarInfo(Reg);
758
759   // Loop over all of the successors of the basic block, checking to see if
760   // the value is either live in the block, or if it is killed in the block.
761   SmallVector<MachineBasicBlock*, 8> OpSuccBlocks;
762   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
763          E = MBB.succ_end(); SI != E; ++SI) {
764     MachineBasicBlock *SuccMBB = *SI;
765
766     // Is it alive in this successor?
767     unsigned SuccIdx = SuccMBB->getNumber();
768     if (VI.AliveBlocks.test(SuccIdx))
769       return true;
770     OpSuccBlocks.push_back(SuccMBB);
771   }
772
773   // Check to see if this value is live because there is a use in a successor
774   // that kills it.
775   switch (OpSuccBlocks.size()) {
776   case 1: {
777     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
778     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
779       if (VI.Kills[i]->getParent() == SuccMBB)
780         return true;
781     break;
782   }
783   case 2: {
784     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
785     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
786       if (VI.Kills[i]->getParent() == SuccMBB1 ||
787           VI.Kills[i]->getParent() == SuccMBB2)
788         return true;
789     break;
790   }
791   default:
792     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
793     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
794       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
795                              VI.Kills[i]->getParent()))
796         return true;
797   }
798   return false;
799 }
800
801 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
802 /// variables that are live out of DomBB will be marked as passing live through
803 /// BB.
804 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
805                                 MachineBasicBlock *DomBB,
806                                 MachineBasicBlock *SuccBB) {
807   const unsigned NumNew = BB->getNumber();
808
809   // All registers used by PHI nodes in SuccBB must be live through BB.
810   for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
811          BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI)
812     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
813       if (BBI->getOperand(i+1).getMBB() == BB)
814         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
815
816   // Update info for all live variables
817   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
818     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
819     VarInfo &VI = getVarInfo(Reg);
820     if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI))
821       VI.AliveBlocks.set(NumNew);
822   }
823 }