Fix batch of converting RegisterPass<> to INTIALIZE_PASS().
[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 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.
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/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"
41 #include <algorithm>
42 using namespace llvm;
43
44 char LiveVariables::ID = 0;
45 INITIALIZE_PASS(LiveVariables, "livevars",
46                 "Live Variable Analysis", false, false);
47
48
49 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
50   AU.addRequiredID(UnreachableMachineBlockElimID);
51   AU.setPreservesAll();
52   MachineFunctionPass::getAnalysisUsage(AU);
53 }
54
55 MachineInstr *
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)
59       return Kills[i];
60   return NULL;
61 }
62
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)
67     dbgs() << *I << ", ";
68   dbgs() << "\n  Killed by:";
69   if (Kills.empty())
70     dbgs() << " No instructions.\n";
71   else {
72     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
73       dbgs() << "\n    #" << i << ": " << *Kills[i];
74     dbgs() << "\n";
75   }
76 }
77
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);
86     else
87       VirtRegInfo.resize(2*VirtRegInfo.size());
88   }
89   return VirtRegInfo[RegIdx];
90 }
91
92 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
93                                             MachineBasicBlock *DefBlock,
94                                             MachineBasicBlock *MBB,
95                                     std::vector<MachineBasicBlock*> &WorkList) {
96   unsigned BBNum = MBB->getNumber();
97   
98   // Check to see if this basic block is one of the killing blocks.  If so,
99   // remove it.
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
103       break;
104     }
105   
106   if (MBB == DefBlock) return;  // Terminate recursion
107
108   if (VRInfo.AliveBlocks.test(BBNum))
109     return;  // We already know the block is live
110
111   // Mark the variable known alive in this bb
112   VRInfo.AliveBlocks.set(BBNum);
113
114   for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
115          E = MBB->pred_rend(); PI != E; ++PI)
116     WorkList.push_back(*PI);
117 }
118
119 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
120                                             MachineBasicBlock *DefBlock,
121                                             MachineBasicBlock *MBB) {
122   std::vector<MachineBasicBlock*> WorkList;
123   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
124
125   while (!WorkList.empty()) {
126     MachineBasicBlock *Pred = WorkList.back();
127     WorkList.pop_back();
128     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
129   }
130 }
131
132 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
133                                      MachineInstr *MI) {
134   assert(MRI->getVRegDef(reg) && "Register use before def!");
135
136   unsigned BBNum = MBB->getNumber();
137
138   VarInfo& VRInfo = getVarInfo(reg);
139   VRInfo.NumUses++;
140
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;
146     return;
147   }
148
149 #ifndef NDEBUG
150   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
151     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
152 #endif
153
154   // This situation can occur:
155   //
156   //     ,------.
157   //     |      |
158   //     |      v
159   //     |   t2 = phi ... t1 ...
160   //     |      |
161   //     |      v
162   //     |   t1 = ...
163   //     |  ... = ... t1 ...
164   //     |      |
165   //     `------'
166   //
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"
169   // in this case.
170   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
171
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);
177
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);
182 }
183
184 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
185   VarInfo &VRInfo = getVarInfo(Reg);
186
187   if (VRInfo.AliveBlocks.empty())
188     // If vr is not alive in any block, then defaults to dead.
189     VRInfo.Kills.push_back(MI);
190 }
191
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];
202     if (!Def)
203       continue;
204     unsigned Dist = DistanceMap[Def];
205     if (Dist > LastDefDist) {
206       LastDefReg  = SubReg;
207       LastDef     = Def;
208       LastDefDist = Dist;
209     }
210   }
211
212   if (!LastDef)
213     return 0;
214
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)
219       continue;
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);
226     }
227   }
228   return LastDef;
229 }
230
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
233 /// super-register.
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.
239     // e.g.
240     // AH =
241     // AL = ... <imp-def EAX>, <imp-kill AH>
242     //    = AH
243     // ...
244     //    = EAX
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*/,
251                                                            true/*IsImp*/));
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))
257           continue;
258         if (PartDefRegs.count(SubReg))
259           continue;
260         // This part of Reg was defined before the last partial def. It's killed
261         // here.
262         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
263                                                              false/*IsDef*/,
264                                                              true/*IsImp*/));
265         PhysRegDef[SubReg] = LastPartialDef;
266         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
267           Processed.insert(*SS);
268       }
269     }
270   }
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*/));
276
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;
282 }
283
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)
290     return 0;
291
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;
309       }
310     }
311   }
312
313   return LastRefOrPartRef;
314 }
315
316 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
317   MachineInstr *LastDef = PhysRegDef[Reg];
318   MachineInstr *LastUse = PhysRegUse[Reg];
319   if (!LastDef && !LastUse)
320     return false;
321
322   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
323   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
324   // The whole register is used.
325   // AL =
326   // AH =
327   //
328   //    = AX
329   //    = AL, AX<imp-use, kill>
330   // AX =
331   //
332   // Or whole register is defined, but not used at all.
333   // AX<dead> =
334   // ...
335   // AX =
336   //
337   // Or whole register is defined, but only partly used.
338   // AX<dead> = AL<imp-def>
339   //    = AL<kill>
340   // AX = 
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;
353         LastPartDef = Def;
354       }
355       continue;
356     }
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;
365       }
366     }
367   }
368
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))
378         continue;
379       bool NeedDef = true;
380       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
381         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
382         if (MO) {
383           NeedDef = false;
384           assert(!MO->isDead());
385         }
386       }
387       if (NeedDef)
388         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
389                                                  true/*IsDef*/, true/*IsImp*/));
390       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
391       if (LastSubRef)
392         LastSubRef->addRegisterKilled(SubReg, TRI, true);
393       else {
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;
399       }
400       for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
401         PartUses.erase(*SS);
402     }
403   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
404     if (LastPartDef)
405       // The last partial def kills the register.
406       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
407                                                 true/*IsImp*/, true/*IsKill*/));
408     else {
409       MachineOperand *MO =
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);
415       if (NeedEC) {
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);
419         if (MO)
420           MO->setIsEarlyClobber();
421       }
422     }
423   } else
424     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
425   return true;
426 }
427
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]) {
433     Live.insert(Reg);
434     for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
435       Live.insert(*SS);
436   } else {
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.
441       // e.g.
442       // AL =
443       // AH =
444       //    = AX
445       if (Live.count(SubReg))
446         continue;
447       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
448         Live.insert(SubReg);
449         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
450           Live.insert(*SS);
451       }
452     }
453   }
454
455   // Start from the largest piece, find the last time any part of the register
456   // is referenced.
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.
463       continue;
464     HandlePhysRegKill(SubReg, MI);
465   }
466
467   if (MI)
468     Defs.push_back(Reg);  // Remember this def.
469 }
470
471 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
472                                       SmallVector<unsigned, 4> &Defs) {
473   while (!Defs.empty()) {
474     unsigned Reg = Defs.back();
475     Defs.pop_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;
482     }
483   }
484 }
485
486 namespace {
487   struct RegSorter {
488     const TargetRegisterInfo *TRI;
489
490     RegSorter(const TargetRegisterInfo *tri) : TRI(tri) { }
491     bool operator()(unsigned A, unsigned B) {
492       if (TRI->isSubRegister(A, B))
493         return true;
494       else if (TRI->isSubRegister(B, A))
495         return false;
496       return A < B;
497     }
498   };
499 }
500
501 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
502   MF = &mf;
503   MRI = &mf.getRegInfo();
504   TRI = MF->getTarget().getRegisterInfo();
505
506   ReservedRegisters = TRI->getReservedRegs(mf);
507
508   unsigned NumRegs = TRI->getNumRegs();
509   PhysRegDef  = new MachineInstr*[NumRegs];
510   PhysRegUse  = new MachineInstr*[NumRegs];
511   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
512   std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
513   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
514   PHIJoins.clear();
515
516   /// Get some space for a respectable number of registers.
517   VirtRegInfo.resize(64);
518
519   analyzePHINodes(mf);
520
521   // Calculate live variable information in depth first order on the CFG of the
522   // function.  This guarantees that we will see the definition of a virtual
523   // register before its uses due to dominance properties of SSA (except for PHI
524   // nodes, which are treated as a special case).
525   MachineBasicBlock *Entry = MF->begin();
526   SmallPtrSet<MachineBasicBlock*,16> Visited;
527
528   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
529          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
530        DFI != E; ++DFI) {
531     MachineBasicBlock *MBB = *DFI;
532
533     // Mark live-in registers as live-in.
534     SmallVector<unsigned, 4> Defs;
535     for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
536            EE = MBB->livein_end(); II != EE; ++II) {
537       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
538              "Cannot have a live-in virtual register!");
539       HandlePhysRegDef(*II, 0, Defs);
540     }
541
542     // Loop over all of the instructions, processing them.
543     DistanceMap.clear();
544     unsigned Dist = 0;
545     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
546          I != E; ++I) {
547       MachineInstr *MI = I;
548       if (MI->isDebugValue())
549         continue;
550       DistanceMap.insert(std::make_pair(MI, Dist++));
551
552       // Process all of the operands of the instruction...
553       unsigned NumOperandsToProcess = MI->getNumOperands();
554
555       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
556       // of the uses.  They will be handled in other basic blocks.
557       if (MI->isPHI())
558         NumOperandsToProcess = 1;
559
560       // Clear kill and dead markers. LV will recompute them.
561       SmallVector<unsigned, 4> UseRegs;
562       SmallVector<unsigned, 4> DefRegs;
563       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
564         MachineOperand &MO = MI->getOperand(i);
565         if (!MO.isReg() || MO.getReg() == 0)
566           continue;
567         unsigned MOReg = MO.getReg();
568         if (MO.isUse()) {
569           MO.setIsKill(false);
570           UseRegs.push_back(MOReg);
571         } else /*MO.isDef()*/ {
572           MO.setIsDead(false);
573           DefRegs.push_back(MOReg);
574         }
575       }
576
577       // Process all uses.
578       for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
579         unsigned MOReg = UseRegs[i];
580         if (TargetRegisterInfo::isVirtualRegister(MOReg))
581           HandleVirtRegUse(MOReg, MBB, MI);
582         else if (!ReservedRegisters[MOReg])
583           HandlePhysRegUse(MOReg, MI);
584       }
585
586       // Process all defs.
587       for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
588         unsigned MOReg = DefRegs[i];
589         if (TargetRegisterInfo::isVirtualRegister(MOReg))
590           HandleVirtRegDef(MOReg, MI);
591         else if (!ReservedRegisters[MOReg])
592           HandlePhysRegDef(MOReg, MI, Defs);
593       }
594       UpdatePhysRegDefs(MI, Defs);
595     }
596
597     // Handle any virtual assignments from PHI nodes which might be at the
598     // bottom of this basic block.  We check all of our successor blocks to see
599     // if they have PHI nodes, and if so, we simulate an assignment at the end
600     // of the current block.
601     if (!PHIVarInfo[MBB->getNumber()].empty()) {
602       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
603
604       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
605              E = VarInfoVec.end(); I != E; ++I)
606         // Mark it alive only in the block we are representing.
607         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
608                                 MBB);
609     }
610
611     // Finally, if the last instruction in the block is a return, make sure to
612     // mark it as using all of the live-out values in the function.
613     // Things marked both call and return are tail calls; do not do this for
614     // them.  The tail callee need not take the same registers as input
615     // that it produces as output, and there are dependencies for its input
616     // registers elsewhere.
617     if (!MBB->empty() && MBB->back().getDesc().isReturn()
618         && !MBB->back().getDesc().isCall()) {
619       MachineInstr *Ret = &MBB->back();
620
621       for (MachineRegisterInfo::liveout_iterator
622            I = MF->getRegInfo().liveout_begin(),
623            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
624         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
625                "Cannot have a live-out virtual register!");
626         HandlePhysRegUse(*I, Ret);
627
628         // Add live-out registers as implicit uses.
629         if (!Ret->readsRegister(*I))
630           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
631       }
632     }
633
634     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
635     // available at the end of the basic block.
636     for (unsigned i = 0; i != NumRegs; ++i)
637       if (PhysRegDef[i] || PhysRegUse[i])
638         HandlePhysRegDef(i, 0, Defs);
639
640     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
641     std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
642   }
643
644   // Convert and transfer the dead / killed information we have gathered into
645   // VirtRegInfo onto MI's.
646   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
647     for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
648       if (VirtRegInfo[i].Kills[j] ==
649           MRI->getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
650         VirtRegInfo[i]
651           .Kills[j]->addRegisterDead(i +
652                                      TargetRegisterInfo::FirstVirtualRegister,
653                                      TRI);
654       else
655         VirtRegInfo[i]
656           .Kills[j]->addRegisterKilled(i +
657                                        TargetRegisterInfo::FirstVirtualRegister,
658                                        TRI);
659
660   // Check to make sure there are no unreachable blocks in the MC CFG for the
661   // function.  If so, it is due to a bug in the instruction selector or some
662   // other part of the code generator if this happens.
663 #ifndef NDEBUG
664   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
665     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
666 #endif
667
668   delete[] PhysRegDef;
669   delete[] PhysRegUse;
670   delete[] PHIVarInfo;
671
672   return false;
673 }
674
675 /// replaceKillInstruction - Update register kill info by replacing a kill
676 /// instruction with a new one.
677 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
678                                            MachineInstr *NewMI) {
679   VarInfo &VI = getVarInfo(Reg);
680   std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
681 }
682
683 /// removeVirtualRegistersKilled - Remove all killed info for the specified
684 /// instruction.
685 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
686   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
687     MachineOperand &MO = MI->getOperand(i);
688     if (MO.isReg() && MO.isKill()) {
689       MO.setIsKill(false);
690       unsigned Reg = MO.getReg();
691       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
692         bool removed = getVarInfo(Reg).removeKill(MI);
693         assert(removed && "kill not in register's VarInfo?");
694         removed = true;
695       }
696     }
697   }
698 }
699
700 /// analyzePHINodes - Gather information about the PHI nodes in here. In
701 /// particular, we want to map the variable information of a virtual register
702 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
703 ///
704 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
705   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
706        I != E; ++I)
707     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
708          BBI != BBE && BBI->isPHI(); ++BBI)
709       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
710         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
711           .push_back(BBI->getOperand(i).getReg());
712 }
713
714 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
715                                       unsigned Reg,
716                                       MachineRegisterInfo &MRI) {
717   unsigned Num = MBB.getNumber();
718
719   // Reg is live-through.
720   if (AliveBlocks.test(Num))
721     return true;
722
723   // Registers defined in MBB cannot be live in.
724   const MachineInstr *Def = MRI.getVRegDef(Reg);
725   if (Def && Def->getParent() == &MBB)
726     return false;
727
728  // Reg was not defined in MBB, was it killed here?
729   return findKill(&MBB);
730 }
731
732 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
733   LiveVariables::VarInfo &VI = getVarInfo(Reg);
734
735   // Loop over all of the successors of the basic block, checking to see if
736   // the value is either live in the block, or if it is killed in the block.
737   std::vector<MachineBasicBlock*> OpSuccBlocks;
738   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
739          E = MBB.succ_end(); SI != E; ++SI) {
740     MachineBasicBlock *SuccMBB = *SI;
741
742     // Is it alive in this successor?
743     unsigned SuccIdx = SuccMBB->getNumber();
744     if (VI.AliveBlocks.test(SuccIdx))
745       return true;
746     OpSuccBlocks.push_back(SuccMBB);
747   }
748
749   // Check to see if this value is live because there is a use in a successor
750   // that kills it.
751   switch (OpSuccBlocks.size()) {
752   case 1: {
753     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
754     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
755       if (VI.Kills[i]->getParent() == SuccMBB)
756         return true;
757     break;
758   }
759   case 2: {
760     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
761     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
762       if (VI.Kills[i]->getParent() == SuccMBB1 ||
763           VI.Kills[i]->getParent() == SuccMBB2)
764         return true;
765     break;
766   }
767   default:
768     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
769     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
770       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
771                              VI.Kills[i]->getParent()))
772         return true;
773   }
774   return false;
775 }
776
777 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
778 /// variables that are live out of DomBB will be marked as passing live through
779 /// BB.
780 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
781                                 MachineBasicBlock *DomBB,
782                                 MachineBasicBlock *SuccBB) {
783   const unsigned NumNew = BB->getNumber();
784
785   // All registers used by PHI nodes in SuccBB must be live through BB.
786   for (MachineBasicBlock::const_iterator BBI = SuccBB->begin(),
787          BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI)
788     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
789       if (BBI->getOperand(i+1).getMBB() == BB)
790         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
791
792   // Update info for all live variables
793   for (unsigned Reg = TargetRegisterInfo::FirstVirtualRegister,
794          E = MRI->getLastVirtReg()+1; Reg != E; ++Reg) {
795     VarInfo &VI = getVarInfo(Reg);
796     if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI))
797       VI.AliveBlocks.set(NumNew);
798   }
799 }