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