adjust to new live variables interface
[oota-llvm.git] / lib / CodeGen / PHIElimination.cpp
1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass eliminates machine instruction PHI nodes by inserting copy
11 // instructions.  This destroys SSA information, but is the desired input for
12 // some register allocators.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/LiveVariables.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 using namespace llvm;
26
27 namespace {
28   struct PNE : public MachineFunctionPass {
29     bool runOnMachineFunction(MachineFunction &Fn) {
30       bool Changed = false;
31
32       // Eliminate PHI instructions by inserting copies into predecessor blocks.
33       for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
34         Changed |= EliminatePHINodes(Fn, *I);
35
36       return Changed;
37     }
38
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.addPreserved<LiveVariables>();
41       MachineFunctionPass::getAnalysisUsage(AU);
42     }
43
44   private:
45     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
46     /// in predecessor basic blocks.
47     ///
48     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
49   };
50
51   RegisterPass<PNE> X("phi-node-elimination",
52                       "Eliminate PHI nodes for register allocation");
53 }
54
55
56 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
57
58 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
59 /// predecessor basic blocks.
60 ///
61 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
62   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
63     return false;   // Quick exit for normal case...
64
65   LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
66   const TargetInstrInfo &MII = *MF.getTarget().getInstrInfo();
67   const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
68
69   // VRegPHIUseCount - Keep track of the number of times each virtual register
70   // is used by PHI nodes in successors of this block.
71   DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
72   VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
73
74   unsigned BBIsSuccOfPreds = 0;  // Number of times MBB is a succ of preds
75   for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
76          E = MBB.pred_end(); PI != E; ++PI)
77     for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
78            E = (*PI)->succ_end(); SI != E; ++SI) {
79     BBIsSuccOfPreds += *SI == &MBB;
80     for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() &&
81            BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
82       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
83         VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
84   }
85
86   // Get an iterator to the first instruction after the last PHI node (this may
87   // also be the end of the basic block).  While we are scanning the PHIs,
88   // populate the VRegPHIUseCount map.
89   MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
90   while (AfterPHIsIt != MBB.end() &&
91          AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
92     ++AfterPHIsIt;    // Skip over all of the PHI nodes...
93
94   while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
95     // Unlink the PHI node from the basic block, but don't delete the PHI yet.
96     MachineInstr *MPhi = MBB.remove(MBB.begin());
97
98     assert(MRegisterInfo::isVirtualRegister(MPhi->getOperand(0).getReg()) &&
99            "PHI node doesn't write virt reg?");
100
101     unsigned DestReg = MPhi->getOperand(0).getReg();
102
103     // Create a new register for the incoming PHI arguments
104     const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
105     unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
106
107     // Insert a register to register copy in the top of the current block (but
108     // after any remaining phi nodes) which copies the new incoming register
109     // into the phi node destination.
110     //
111     RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
112
113     // Update live variable information if there is any...
114     if (LV) {
115       MachineInstr *PHICopy = prior(AfterPHIsIt);
116
117       // Add information to LiveVariables to know that the incoming value is
118       // killed.  Note that because the value is defined in several places (once
119       // each for each incoming block), the "def" block and instruction fields
120       // for the VarInfo is not filled in.
121       //
122       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
123
124       // Since we are going to be deleting the PHI node, if it is the last use
125       // of any registers, or if the value itself is dead, we need to move this
126       // information over to the new copy we just inserted.
127       //
128       LV->removeVirtualRegistersKilled(MPhi);
129
130       std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
131         RKs = LV->dead_range(MPhi);
132       if (RKs.first != RKs.second) {
133         for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)
134           LV->addVirtualRegisterDead(*I, PHICopy);
135         LV->removeVirtualRegistersDead(MPhi);
136       }
137     }
138
139     // Adjust the VRegPHIUseCount map to account for the removal of this PHI
140     // node.
141     for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
142       VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= BBIsSuccOfPreds;
143
144     // Now loop over all of the incoming arguments, changing them to copy into
145     // the IncomingReg register in the corresponding predecessor basic block.
146     //
147     for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
148       MachineOperand &opVal = MPhi->getOperand(i-1);
149
150       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
151       // source path the PHI.
152       MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
153
154       MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
155
156       // Check to make sure we haven't already emitted the copy for this block.
157       // This can happen because PHI nodes may have multiple entries for the
158       // same basic block.  It doesn't matter which entry we use though, because
159       // all incoming values are guaranteed to be the same for a particular bb.
160       //
161       // If we emitted a copy for this basic block already, it will be right
162       // where we want to insert one now.  Just check for a definition of the
163       // register we are interested in!
164       //
165       bool HaveNotEmitted = true;
166
167       if (I != opBlock.begin()) {
168         MachineBasicBlock::iterator PrevInst = prior(I);
169         for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
170           MachineOperand &MO = PrevInst->getOperand(i);
171           if (MO.isRegister() && MO.getReg() == IncomingReg)
172             if (MO.isDef()) {
173               HaveNotEmitted = false;
174               break;
175             }
176         }
177       }
178
179       if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
180         assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&
181                "Machine PHI Operands must all be virtual registers!");
182         unsigned SrcReg = opVal.getReg();
183         RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
184
185         // Now update live variable information if we have it.
186         if (LV) {
187           // We want to be able to insert a kill of the register if this PHI
188           // (aka, the copy we just inserted) is the last use of the source
189           // value.  Live variable analysis conservatively handles this by
190           // saying that the value is live until the end of the block the PHI
191           // entry lives in.  If the value really is dead at the PHI copy, there
192           // will be no successor blocks which have the value live-in.
193           //
194           // Check to see if the copy is the last use, and if so, update the
195           // live variables information so that it knows the copy source
196           // instruction kills the incoming value.
197           //
198           LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
199
200           // Loop over all of the successors of the basic block, checking to see
201           // if the value is either live in the block, or if it is killed in the
202           // block.  Also check to see if this register is in use by another PHI
203           // node which has not yet been eliminated.  If so, it will be killed
204           // at an appropriate point later.
205           //
206           bool ValueIsLive = false;
207           for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
208                  E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
209             MachineBasicBlock *SuccMBB = *SI;
210
211             // Is it alive in this successor?
212             unsigned SuccIdx = SuccMBB->getNumber();
213             if (SuccIdx < InRegVI.AliveBlocks.size() &&
214                 InRegVI.AliveBlocks[SuccIdx]) {
215               ValueIsLive = true;
216               break;
217             }
218
219             // Is it killed in this successor?
220             for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
221               if (InRegVI.Kills[i]->getParent() == SuccMBB) {
222                 ValueIsLive = true;
223                 break;
224               }
225
226             // Is it used by any PHI instructions in this block?
227             if (!ValueIsLive)
228               ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
229           }
230
231           // Okay, if we now know that the value is not live out of the block,
232           // we can add a kill marker to the copy we inserted saying that it
233           // kills the incoming value!
234           //
235           if (!ValueIsLive) {
236             MachineBasicBlock::iterator Prev = prior(I);
237             LV->addVirtualRegisterKilled(SrcReg, Prev);
238
239             // This vreg no longer lives all of the way through opBlock.
240             unsigned opBlockNum = opBlock.getNumber();
241             if (opBlockNum < InRegVI.AliveBlocks.size())
242               InRegVI.AliveBlocks[opBlockNum] = false;
243           }
244         }
245       }
246     }
247
248     // Really delete the PHI instruction now!
249     delete MPhi;
250   }
251   return true;
252 }