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