Be conservative if getresult operand is neither call nor invoke.
[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/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/ADT/DepthFirstIterator.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Config/alloca.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 char LiveVariables::ID = 0;
43 static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
44
45 void LiveVariables::VarInfo::dump() const {
46   cerr << "  Alive in blocks: ";
47   for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
48     if (AliveBlocks[i]) cerr << i << ", ";
49   cerr << "  Used in blocks: ";
50   for (unsigned i = 0, e = UsedBlocks.size(); i != e; ++i)
51     if (UsedBlocks[i]) cerr << i << ", ";
52   cerr << "\n  Killed by:";
53   if (Kills.empty())
54     cerr << " No instructions.\n";
55   else {
56     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57       cerr << "\n    #" << i << ": " << *Kills[i];
58     cerr << "\n";
59   }
60 }
61
62 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
63 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
64   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
65          "getVarInfo: not a virtual register!");
66   RegIdx -= TargetRegisterInfo::FirstVirtualRegister;
67   if (RegIdx >= VirtRegInfo.size()) {
68     if (RegIdx >= 2*VirtRegInfo.size())
69       VirtRegInfo.resize(RegIdx*2);
70     else
71       VirtRegInfo.resize(2*VirtRegInfo.size());
72   }
73   VarInfo &VI = VirtRegInfo[RegIdx];
74   VI.AliveBlocks.resize(MF->getNumBlockIDs());
75   VI.UsedBlocks.resize(MF->getNumBlockIDs());
76   return VI;
77 }
78
79 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
80                                             MachineBasicBlock *DefBlock,
81                                             MachineBasicBlock *MBB,
82                                     std::vector<MachineBasicBlock*> &WorkList) {
83   unsigned BBNum = MBB->getNumber();
84   
85   // Check to see if this basic block is one of the killing blocks.  If so,
86   // remove it.
87   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
88     if (VRInfo.Kills[i]->getParent() == MBB) {
89       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
90       break;
91     }
92   
93   if (MBB == DefBlock) return;  // Terminate recursion
94
95   if (VRInfo.AliveBlocks[BBNum])
96     return;  // We already know the block is live
97
98   // Mark the variable known alive in this bb
99   VRInfo.AliveBlocks[BBNum] = true;
100
101   for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
102          E = MBB->pred_rend(); PI != E; ++PI)
103     WorkList.push_back(*PI);
104 }
105
106 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
107                                             MachineBasicBlock *DefBlock,
108                                             MachineBasicBlock *MBB) {
109   std::vector<MachineBasicBlock*> WorkList;
110   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
111
112   while (!WorkList.empty()) {
113     MachineBasicBlock *Pred = WorkList.back();
114     WorkList.pop_back();
115     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
116   }
117 }
118
119 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
120                                      MachineInstr *MI) {
121   assert(MRI->getVRegDef(reg) && "Register use before def!");
122
123   unsigned BBNum = MBB->getNumber();
124
125   VarInfo& VRInfo = getVarInfo(reg);
126   VRInfo.UsedBlocks[BBNum] = true;
127   VRInfo.NumUses++;
128
129   // Check to see if this basic block is already a kill block.
130   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
131     // Yes, this register is killed in this basic block already. Increase the
132     // live range by updating the kill instruction.
133     VRInfo.Kills.back() = MI;
134     return;
135   }
136
137 #ifndef NDEBUG
138   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
139     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
140 #endif
141
142   assert(MBB != MRI->getVRegDef(reg)->getParent() &&
143          "Should have kill for defblock!");
144
145   // Add a new kill entry for this basic block. If this virtual register is
146   // already marked as alive in this basic block, that means it is alive in at
147   // least one of the successor blocks, it's not a kill.
148   if (!VRInfo.AliveBlocks[BBNum])
149     VRInfo.Kills.push_back(MI);
150
151   // Update all dominating blocks to mark them as "known live".
152   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
153          E = MBB->pred_end(); PI != E; ++PI)
154     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
155 }
156
157 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
158 /// implicit defs to a machine instruction if there was an earlier def of its
159 /// super-register.
160 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
161   // Turn previous partial def's into read/mod/write.
162   for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
163     MachineInstr *Def = PhysRegPartDef[Reg][i];
164
165     // First one is just a def. This means the use is reading some undef bits.
166     if (i != 0)
167       Def->addOperand(MachineOperand::CreateReg(Reg,
168                                                 false /*IsDef*/,
169                                                 true  /*IsImp*/,
170                                                 true  /*IsKill*/));
171
172     Def->addOperand(MachineOperand::CreateReg(Reg,
173                                               true  /*IsDef*/,
174                                               true  /*IsImp*/));
175   }
176
177   PhysRegPartDef[Reg].clear();
178
179   // There was an earlier def of a super-register. Add implicit def to that MI.
180   //
181   //   A: EAX = ...
182   //   B: ... = AX
183   //
184   // Add implicit def to A.
185   if (PhysRegInfo[Reg] && PhysRegInfo[Reg] != PhysRegPartUse[Reg] &&
186       !PhysRegUsed[Reg]) {
187     MachineInstr *Def = PhysRegInfo[Reg];
188
189     if (!Def->modifiesRegister(Reg))
190       Def->addOperand(MachineOperand::CreateReg(Reg,
191                                                 true  /*IsDef*/,
192                                                 true  /*IsImp*/));
193   }
194
195   // There is a now a proper use, forget about the last partial use.
196   PhysRegPartUse[Reg] = NULL;
197   PhysRegInfo[Reg] = MI;
198   PhysRegUsed[Reg] = true;
199
200   // Now reset the use information for the sub-registers.
201   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
202        unsigned SubReg = *SubRegs; ++SubRegs) {
203     PhysRegPartUse[SubReg] = NULL;
204     PhysRegInfo[SubReg] = MI;
205     PhysRegUsed[SubReg] = true;
206   }
207
208   for (const unsigned *SuperRegs = TRI->getSuperRegisters(Reg);
209        unsigned SuperReg = *SuperRegs; ++SuperRegs) {
210     // Remember the partial use of this super-register if it was previously
211     // defined.
212     bool HasPrevDef = PhysRegInfo[SuperReg] != NULL;
213
214     if (!HasPrevDef)
215       // No need to go up more levels. A def of a register also sets its sub-
216       // registers. So if PhysRegInfo[SuperReg] is NULL, it means SuperReg's
217       // super-registers are not previously defined.
218       for (const unsigned *SSRegs = TRI->getSuperRegisters(SuperReg);
219            unsigned SSReg = *SSRegs; ++SSRegs)
220         if (PhysRegInfo[SSReg] != NULL) {
221           HasPrevDef = true;
222           break;
223         }
224
225     if (HasPrevDef) {
226       PhysRegInfo[SuperReg] = MI;
227       PhysRegPartUse[SuperReg] = MI;
228     }
229   }
230 }
231
232 /// addRegisterKills - For all of a register's sub-registers that are killed in
233 /// at this machine instruction, mark them as "killed". (If the machine operand
234 /// isn't found, add it first.)
235 void LiveVariables::addRegisterKills(unsigned Reg, MachineInstr *MI,
236                                      SmallSet<unsigned, 4> &SubKills) {
237   if (SubKills.count(Reg) == 0) {
238     MI->addRegisterKilled(Reg, TRI, true);
239     return;
240   }
241
242   for (const unsigned *SubRegs = TRI->getImmediateSubRegisters(Reg);
243        unsigned SubReg = *SubRegs; ++SubRegs)
244     addRegisterKills(SubReg, MI, SubKills);
245 }
246
247 /// HandlePhysRegKill - The recursive version of HandlePhysRegKill. Returns true
248 /// if:
249 ///
250 ///   - The register has no sub-registers and the machine instruction is the
251 ///     last def/use of the register, or
252 ///   - The register has sub-registers and none of them are killed elsewhere.
253 ///
254 /// SubKills is filled with the set of sub-registers that are killed elsewhere.
255 bool LiveVariables::HandlePhysRegKill(unsigned Reg, const MachineInstr *RefMI,
256                                       SmallSet<unsigned, 4> &SubKills) {
257   const unsigned *SubRegs = TRI->getImmediateSubRegisters(Reg);
258
259   for (; unsigned SubReg = *SubRegs; ++SubRegs) {
260     const MachineInstr *LastRef = PhysRegInfo[SubReg];
261
262     if (LastRef != RefMI ||
263         !HandlePhysRegKill(SubReg, RefMI, SubKills))
264       SubKills.insert(SubReg);
265   }
266
267   if (*SubRegs == 0) {
268     // No sub-registers, just check if reg is killed by RefMI.
269     if (PhysRegInfo[Reg] == RefMI && PhysRegInfo[Reg]->readsRegister(Reg)) {
270       return true;
271     }
272   } else if (SubKills.empty()) {
273     // None of the sub-registers are killed elsewhere.
274     return true;
275   }
276
277   return false;
278 }
279
280 /// HandlePhysRegKill - Returns true if the whole register is killed in the
281 /// machine instruction. If only some of its sub-registers are killed in this
282 /// machine instruction, then mark those as killed and return false.
283 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *RefMI) {
284   SmallSet<unsigned, 4> SubKills;
285
286   if (HandlePhysRegKill(Reg, RefMI, SubKills)) {
287     // This machine instruction kills this register.
288     RefMI->addRegisterKilled(Reg, TRI, true);
289     return true;
290   }
291
292   // Some sub-registers are killed by another machine instruction.
293   for (const unsigned *SubRegs = TRI->getImmediateSubRegisters(Reg);
294        unsigned SubReg = *SubRegs; ++SubRegs)
295     addRegisterKills(SubReg, RefMI, SubKills);
296
297   return false;
298 }
299
300 /// hasRegisterUseBelow - Return true if the specified register is used after
301 /// the current instruction and before it's next definition.
302 bool LiveVariables::hasRegisterUseBelow(unsigned Reg,
303                                         MachineBasicBlock::iterator I,
304                                         MachineBasicBlock *MBB) {
305   if (I == MBB->end())
306     return false;
307
308   // First find out if there are any uses / defs below.
309   bool hasDistInfo = true;
310   unsigned CurDist = DistanceMap[I];
311   SmallVector<MachineInstr*, 4> Uses;
312   SmallVector<MachineInstr*, 4> Defs;
313   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
314          RE = MRI->reg_end(); RI != RE; ++RI) {
315     MachineOperand &UDO = RI.getOperand();
316     MachineInstr *UDMI = &*RI;
317     if (UDMI->getParent() != MBB)
318       continue;
319     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
320     bool isBelow = false;
321     if (DI == DistanceMap.end()) {
322       // Must be below if it hasn't been assigned a distance yet.
323       isBelow = true;
324       hasDistInfo = false;
325     } else if (DI->second > CurDist)
326       isBelow = true;
327     if (isBelow) {
328       if (UDO.isUse())
329         Uses.push_back(UDMI);
330       if (UDO.isDef())
331         Defs.push_back(UDMI);
332     }
333   }
334
335   if (Uses.empty())
336     // No uses below.
337     return false;
338   else if (!Uses.empty() && Defs.empty())
339     // There are uses below but no defs below.
340     return true;
341   // There are both uses and defs below. We need to know which comes first.
342   if (!hasDistInfo) {
343     // Complete DistanceMap for this MBB. This information is computed only
344     // once per MBB.
345     ++I;
346     ++CurDist;
347     for (MachineBasicBlock::iterator E = MBB->end(); I != E; ++I, ++CurDist)
348       DistanceMap.insert(std::make_pair(I, CurDist));
349   }
350
351   unsigned EarliestUse = CurDist;
352   for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
353     unsigned Dist = DistanceMap[Uses[i]];
354     if (Dist < EarliestUse)
355       EarliestUse = Dist;
356   }
357   for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
358     unsigned Dist = DistanceMap[Defs[i]];
359     if (Dist < EarliestUse)
360       // The register is defined before its first use below.
361       return false;
362   }
363   return true;
364 }
365
366 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
367   // Does this kill a previous version of this register?
368   if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
369     if (PhysRegUsed[Reg]) {
370       if (!HandlePhysRegKill(Reg, LastRef)) {
371         if (PhysRegPartUse[Reg])
372           PhysRegPartUse[Reg]->addRegisterKilled(Reg, TRI, true);
373       }
374     } else if (PhysRegPartUse[Reg]) {
375       // Add implicit use / kill to last partial use.
376       PhysRegPartUse[Reg]->addRegisterKilled(Reg, TRI, true);
377     } else if (LastRef != MI) {
378       // Defined, but not used. However, watch out for cases where a super-reg
379       // is also defined on the same MI.
380       LastRef->addRegisterDead(Reg, TRI);
381     }
382   }
383
384   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
385        unsigned SubReg = *SubRegs; ++SubRegs) {
386     if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
387       if (PhysRegUsed[SubReg]) {
388         if (!HandlePhysRegKill(SubReg, LastRef)) {
389           if (PhysRegPartUse[SubReg])
390             PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, TRI, true);
391         }
392       } else if (PhysRegPartUse[SubReg]) {
393         // Add implicit use / kill to last use of a sub-register.
394         PhysRegPartUse[SubReg]->addRegisterKilled(SubReg, TRI, true);
395       } else if (LastRef != MI) {
396         // This must be a def of the subreg on the same MI.
397         LastRef->addRegisterDead(SubReg, TRI);
398       }
399     }
400   }
401
402   if (MI) {
403     for (const unsigned *SuperRegs = TRI->getSuperRegisters(Reg);
404          unsigned SuperReg = *SuperRegs; ++SuperRegs) {
405       if (PhysRegInfo[SuperReg] && PhysRegInfo[SuperReg] != MI) {
406         // The larger register is previously defined. Now a smaller part is
407         // being re-defined. Treat it as read/mod/write if there are uses
408         // below.
409         // EAX =
410         // AX  =        EAX<imp-use,kill>, EAX<imp-def>
411         // ...
412         ///    =  EAX
413         if (MI && hasRegisterUseBelow(SuperReg, MI, MI->getParent())) {
414           MI->addOperand(MachineOperand::CreateReg(SuperReg, false/*IsDef*/,
415                                                  true/*IsImp*/,true/*IsKill*/));
416           MI->addOperand(MachineOperand::CreateReg(SuperReg, true/*IsDef*/,
417                                                    true/*IsImp*/));
418           PhysRegInfo[SuperReg] = MI;
419         } else {
420           PhysRegInfo[SuperReg]->addRegisterKilled(SuperReg, TRI, true);
421           PhysRegInfo[SuperReg] = NULL;
422         }
423         PhysRegUsed[SuperReg] = false;
424         PhysRegPartUse[SuperReg] = NULL;
425       } else {
426         // Remember this partial def.
427         PhysRegPartDef[SuperReg].push_back(MI);
428       }
429     }
430
431     PhysRegInfo[Reg] = MI;
432     PhysRegUsed[Reg] = false;
433     PhysRegPartDef[Reg].clear();
434     PhysRegPartUse[Reg] = NULL;
435
436     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
437          unsigned SubReg = *SubRegs; ++SubRegs) {
438       PhysRegInfo[SubReg] = MI;
439       PhysRegUsed[SubReg] = false;
440       PhysRegPartDef[SubReg].clear();
441       PhysRegPartUse[SubReg] = NULL;
442     }
443   }
444 }
445
446 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
447   MF = &mf;
448   MRI = &mf.getRegInfo();
449   TRI = MF->getTarget().getRegisterInfo();
450
451   ReservedRegisters = TRI->getReservedRegs(mf);
452
453   unsigned NumRegs = TRI->getNumRegs();
454   PhysRegInfo = new MachineInstr*[NumRegs];
455   PhysRegUsed = new bool[NumRegs];
456   PhysRegPartUse = new MachineInstr*[NumRegs];
457   PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
458   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
459   std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
460   std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
461   std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
462
463   /// Get some space for a respectable number of registers.
464   VirtRegInfo.resize(64);
465
466   analyzePHINodes(mf);
467
468   // Calculate live variable information in depth first order on the CFG of the
469   // function.  This guarantees that we will see the definition of a virtual
470   // register before its uses due to dominance properties of SSA (except for PHI
471   // nodes, which are treated as a special case).
472   MachineBasicBlock *Entry = MF->begin();
473   SmallPtrSet<MachineBasicBlock*,16> Visited;
474
475   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
476          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
477        DFI != E; ++DFI) {
478     MachineBasicBlock *MBB = *DFI;
479
480     // Mark live-in registers as live-in.
481     for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
482            EE = MBB->livein_end(); II != EE; ++II) {
483       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
484              "Cannot have a live-in virtual register!");
485       HandlePhysRegDef(*II, 0);
486     }
487
488     // Loop over all of the instructions, processing them.
489     DistanceMap.clear();
490     unsigned Dist = 0;
491     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
492          I != E; ++I) {
493       MachineInstr *MI = I;
494       DistanceMap.insert(std::make_pair(MI, Dist++));
495
496       // Process all of the operands of the instruction...
497       unsigned NumOperandsToProcess = MI->getNumOperands();
498
499       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
500       // of the uses.  They will be handled in other basic blocks.
501       if (MI->getOpcode() == TargetInstrInfo::PHI)
502         NumOperandsToProcess = 1;
503
504       // Process all uses.
505       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
506         const MachineOperand &MO = MI->getOperand(i);
507
508         if (MO.isRegister() && MO.isUse() && MO.getReg()) {
509           unsigned MOReg = MO.getReg();
510
511           if (TargetRegisterInfo::isVirtualRegister(MOReg))
512             HandleVirtRegUse(MOReg, MBB, MI);
513           else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
514                    !ReservedRegisters[MOReg])
515             HandlePhysRegUse(MOReg, MI);
516         }
517       }
518
519       // Process all defs.
520       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
521         const MachineOperand &MO = MI->getOperand(i);
522
523         if (MO.isRegister() && MO.isDef() && MO.getReg()) {
524           unsigned MOReg = MO.getReg();
525
526           if (TargetRegisterInfo::isVirtualRegister(MOReg)) {
527             VarInfo &VRInfo = getVarInfo(MOReg);
528
529             if (VRInfo.AliveBlocks.none())
530               // If vr is not alive in any block, then defaults to dead.
531               VRInfo.Kills.push_back(MI);
532           } else if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
533                      !ReservedRegisters[MOReg]) {
534             HandlePhysRegDef(MOReg, MI);
535           }
536         }
537       }
538     }
539
540     // Handle any virtual assignments from PHI nodes which might be at the
541     // bottom of this basic block.  We check all of our successor blocks to see
542     // if they have PHI nodes, and if so, we simulate an assignment at the end
543     // of the current block.
544     if (!PHIVarInfo[MBB->getNumber()].empty()) {
545       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
546
547       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
548              E = VarInfoVec.end(); I != E; ++I)
549         // Mark it alive only in the block we are representing.
550         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
551                                 MBB);
552     }
553
554     // Finally, if the last instruction in the block is a return, make sure to
555     // mark it as using all of the live-out values in the function.
556     if (!MBB->empty() && MBB->back().getDesc().isReturn()) {
557       MachineInstr *Ret = &MBB->back();
558
559       for (MachineRegisterInfo::liveout_iterator
560            I = MF->getRegInfo().liveout_begin(),
561            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
562         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
563                "Cannot have a live-in virtual register!");
564         HandlePhysRegUse(*I, Ret);
565
566         // Add live-out registers as implicit uses.
567         if (!Ret->readsRegister(*I))
568           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
569       }
570     }
571
572     // Loop over PhysRegInfo, killing any registers that are available at the
573     // end of the basic block. This also resets the PhysRegInfo map.
574     for (unsigned i = 0; i != NumRegs; ++i)
575       if (PhysRegInfo[i])
576         HandlePhysRegDef(i, 0);
577
578     // Clear some states between BB's. These are purely local information.
579     for (unsigned i = 0; i != NumRegs; ++i)
580       PhysRegPartDef[i].clear();
581
582     std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
583     std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
584     std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
585   }
586
587   // Convert and transfer the dead / killed information we have gathered into
588   // VirtRegInfo onto MI's.
589   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
590     for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
591       if (VirtRegInfo[i].Kills[j] ==
592           MRI->getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
593         VirtRegInfo[i]
594           .Kills[j]->addRegisterDead(i +
595                                      TargetRegisterInfo::FirstVirtualRegister,
596                                      TRI);
597       else
598         VirtRegInfo[i]
599           .Kills[j]->addRegisterKilled(i +
600                                        TargetRegisterInfo::FirstVirtualRegister,
601                                        TRI);
602
603   // Check to make sure there are no unreachable blocks in the MC CFG for the
604   // function.  If so, it is due to a bug in the instruction selector or some
605   // other part of the code generator if this happens.
606 #ifndef NDEBUG
607   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
608     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
609 #endif
610
611   delete[] PhysRegInfo;
612   delete[] PhysRegUsed;
613   delete[] PhysRegPartUse;
614   delete[] PhysRegPartDef;
615   delete[] PHIVarInfo;
616
617   return false;
618 }
619
620 /// instructionChanged - When the address of an instruction changes, this method
621 /// should be called so that live variables can update its internal data
622 /// structures.  This removes the records for OldMI, transfering them to the
623 /// records for NewMI.
624 void LiveVariables::instructionChanged(MachineInstr *OldMI,
625                                        MachineInstr *NewMI) {
626   // If the instruction defines any virtual registers, update the VarInfo,
627   // kill and dead information for the instruction.
628   for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
629     MachineOperand &MO = OldMI->getOperand(i);
630     if (MO.isRegister() && MO.getReg() &&
631         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
632       unsigned Reg = MO.getReg();
633       VarInfo &VI = getVarInfo(Reg);
634       if (MO.isDef()) {
635         if (MO.isDead()) {
636           MO.setIsDead(false);
637           addVirtualRegisterDead(Reg, NewMI);
638         }
639       }
640       if (MO.isKill()) {
641         MO.setIsKill(false);
642         addVirtualRegisterKilled(Reg, NewMI);
643       }
644       // If this is a kill of the value, update the VI kills list.
645       if (VI.removeKill(OldMI))
646         VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
647     }
648   }
649 }
650
651 /// removeVirtualRegistersKilled - Remove all killed info for the specified
652 /// instruction.
653 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
654   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
655     MachineOperand &MO = MI->getOperand(i);
656     if (MO.isRegister() && MO.isKill()) {
657       MO.setIsKill(false);
658       unsigned Reg = MO.getReg();
659       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
660         bool removed = getVarInfo(Reg).removeKill(MI);
661         assert(removed && "kill not in register's VarInfo?");
662       }
663     }
664   }
665 }
666
667 /// removeVirtualRegistersDead - Remove all of the dead registers for the
668 /// specified instruction from the live variable information.
669 void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
670   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
671     MachineOperand &MO = MI->getOperand(i);
672     if (MO.isRegister() && MO.isDead()) {
673       MO.setIsDead(false);
674       unsigned Reg = MO.getReg();
675       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
676         bool removed = getVarInfo(Reg).removeKill(MI);
677         assert(removed && "kill not in register's VarInfo?");
678       }
679     }
680   }
681 }
682
683 /// analyzePHINodes - Gather information about the PHI nodes in here. In
684 /// particular, we want to map the variable information of a virtual register
685 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
686 ///
687 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
688   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
689        I != E; ++I)
690     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
691          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
692       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
693         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
694           .push_back(BBI->getOperand(i).getReg());
695 }