Fix CodeGen/Generic/2007-04-08-MultipleFrameIndices.ll and PR1308:
[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 #define DEBUG_TYPE "phielim"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Compiler.h"
27 #include <set>
28 #include <algorithm>
29 using namespace llvm;
30
31 STATISTIC(NumAtomic, "Number of atomic phis lowered");
32 //STATISTIC(NumSimple, "Number of simple phis lowered");
33
34 namespace {
35   struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
36     bool runOnMachineFunction(MachineFunction &Fn) {
37       analyzePHINodes(Fn);
38
39       bool Changed = false;
40
41       // Eliminate PHI instructions by inserting copies into predecessor blocks.
42       for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
43         Changed |= EliminatePHINodes(Fn, *I);
44
45       VRegPHIUseCount.clear();
46       return Changed;
47     }
48
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.addPreserved<LiveVariables>();
51       MachineFunctionPass::getAnalysisUsage(AU);
52     }
53
54   private:
55     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
56     /// in predecessor basic blocks.
57     ///
58     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
59     void LowerAtomicPHINode(MachineBasicBlock &MBB,
60                             MachineBasicBlock::iterator AfterPHIsIt);
61
62     /// analyzePHINodes - Gather information about the PHI nodes in
63     /// here. In particular, we want to map the number of uses of a virtual
64     /// register which is used in a PHI node. We map that to the BB the
65     /// vreg is coming from. This is used later to determine when the vreg
66     /// is killed in the BB.
67     ///
68     void analyzePHINodes(const MachineFunction& Fn);
69
70     typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
71     typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
72
73     VRegPHIUse VRegPHIUseCount;
74   };
75
76   RegisterPass<PNE> X("phi-node-elimination",
77                       "Eliminate PHI nodes for register allocation");
78 }
79
80 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
81
82 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
83 /// predecessor basic blocks.
84 ///
85 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
86   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
87     return false;   // Quick exit for basic blocks without PHIs.
88
89   // Get an iterator to the first instruction after the last PHI node (this may
90   // also be the end of the basic block).
91   MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
92   while (AfterPHIsIt != MBB.end() &&
93          AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
94     ++AfterPHIsIt;    // Skip over all of the PHI nodes...
95
96   while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
97     LowerAtomicPHINode(MBB, AfterPHIsIt);
98
99   return true;
100 }
101
102 /// InstructionUsesRegister - Return true if the specified machine instr has a
103 /// use of the specified register.
104 static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
105   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
106     if (MI->getOperand(i).isRegister() &&
107         MI->getOperand(i).getReg() == SrcReg &&
108         MI->getOperand(i).isUse())
109       return true;
110   return false;
111 }
112
113 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
114 /// under the assuption that it needs to be lowered in a way that supports
115 /// atomic execution of PHIs.  This lowering method is always correct all of the
116 /// time.
117 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
118                              MachineBasicBlock::iterator AfterPHIsIt) {
119   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
120   MachineInstr *MPhi = MBB.remove(MBB.begin());
121
122   unsigned DestReg = MPhi->getOperand(0).getReg();
123
124   // Create a new register for the incoming PHI arguments.
125   MachineFunction &MF = *MBB.getParent();
126   const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
127   unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
128
129   // Insert a register to register copy in the top of the current block (but
130   // after any remaining phi nodes) which copies the new incoming register
131   // into the phi node destination.
132   //
133   const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
134   RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
135
136   // Update live variable information if there is any...
137   LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
138   if (LV) {
139     MachineInstr *PHICopy = prior(AfterPHIsIt);
140
141     // Add information to LiveVariables to know that the incoming value is
142     // killed.  Note that because the value is defined in several places (once
143     // each for each incoming block), the "def" block and instruction fields
144     // for the VarInfo is not filled in.
145     //
146     LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
147
148     // Since we are going to be deleting the PHI node, if it is the last use
149     // of any registers, or if the value itself is dead, we need to move this
150     // information over to the new copy we just inserted.
151     //
152     LV->removeVirtualRegistersKilled(MPhi);
153
154     // If the result is dead, update LV.
155     if (LV->RegisterDefIsDead(MPhi, DestReg)) {
156       LV->addVirtualRegisterDead(DestReg, PHICopy);
157       LV->removeVirtualRegistersDead(MPhi);
158     }
159     
160     // Realize that the destination register is defined by the PHI copy now, not
161     // the PHI itself.
162     LV->getVarInfo(DestReg).DefInst = PHICopy;
163
164     LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
165   }
166
167   // Adjust the VRegPHIUseCount map to account for the removal of this PHI
168   // node.
169   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
170     --VRegPHIUseCount[BBVRegPair(
171                         MPhi->getOperand(i + 1).getMachineBasicBlock(),
172                         MPhi->getOperand(i).getReg())];
173
174   // Now loop over all of the incoming arguments, changing them to copy into
175   // the IncomingReg register in the corresponding predecessor basic block.
176   //
177   std::set<MachineBasicBlock*> MBBsInsertedInto;
178   for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
179     unsigned SrcReg = MPhi->getOperand(i-1).getReg();
180     assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
181            "Machine PHI Operands must all be virtual registers!");
182
183     // Get the MachineBasicBlock equivalent of the BasicBlock that is the
184     // source path the PHI.
185     MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
186
187     // Check to make sure we haven't already emitted the copy for this block.
188     // This can happen because PHI nodes may have multiple entries for the
189     // same basic block.
190     if (!MBBsInsertedInto.insert(&opBlock).second)
191       continue;  // If the copy has already been emitted, we're done.
192  
193     // Get an iterator pointing to the first terminator in the block (or end()).
194     // This is the point where we can insert a copy if we'd like to.
195     MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
196     
197     // Insert the copy.
198     RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
199
200     // Now update live variable information if we have it.  Otherwise we're done
201     if (!LV) continue;
202     
203     // We want to be able to insert a kill of the register if this PHI
204     // (aka, the copy we just inserted) is the last use of the source
205     // value.  Live variable analysis conservatively handles this by
206     // saying that the value is live until the end of the block the PHI
207     // entry lives in.  If the value really is dead at the PHI copy, there
208     // will be no successor blocks which have the value live-in.
209     //
210     // Check to see if the copy is the last use, and if so, update the
211     // live variables information so that it knows the copy source
212     // instruction kills the incoming value.
213     //
214     LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
215     InRegVI.UsedBlocks[opBlock.getNumber()] = true;
216
217     // Loop over all of the successors of the basic block, checking to see
218     // if the value is either live in the block, or if it is killed in the
219     // block.  Also check to see if this register is in use by another PHI
220     // node which has not yet been eliminated.  If so, it will be killed
221     // at an appropriate point later.
222     //
223
224     // Is it used by any PHI instructions in this block?
225     bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
226
227     std::vector<MachineBasicBlock*> OpSuccBlocks;
228     
229     // Otherwise, scan successors, including the BB the PHI node lives in.
230     for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
231            E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
232       MachineBasicBlock *SuccMBB = *SI;
233
234       // Is it alive in this successor?
235       unsigned SuccIdx = SuccMBB->getNumber();
236       if (SuccIdx < InRegVI.AliveBlocks.size() &&
237           InRegVI.AliveBlocks[SuccIdx]) {
238         ValueIsLive = true;
239         break;
240       }
241
242       OpSuccBlocks.push_back(SuccMBB);
243     }
244
245     // Check to see if this value is live because there is a use in a successor
246     // that kills it.
247     if (!ValueIsLive) {
248       switch (OpSuccBlocks.size()) {
249       case 1: {
250         MachineBasicBlock *MBB = OpSuccBlocks[0];
251         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
252           if (InRegVI.Kills[i]->getParent() == MBB) {
253             ValueIsLive = true;
254             break;
255           }
256         break;
257       }
258       case 2: {
259         MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
260         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
261           if (InRegVI.Kills[i]->getParent() == MBB1 || 
262               InRegVI.Kills[i]->getParent() == MBB2) {
263             ValueIsLive = true;
264             break;
265           }
266         break;        
267       }
268       default:
269         std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
270         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
271           if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
272                                  InRegVI.Kills[i]->getParent())) {
273             ValueIsLive = true;
274             break;
275           }
276       }
277     }        
278
279     // Okay, if we now know that the value is not live out of the block,
280     // we can add a kill marker in this block saying that it kills the incoming
281     // value!
282     if (!ValueIsLive) {
283       // In our final twist, we have to decide which instruction kills the
284       // register.  In most cases this is the copy, however, the first 
285       // terminator instruction at the end of the block may also use the value.
286       // In this case, we should mark *it* as being the killing block, not the
287       // copy.
288       bool FirstTerminatorUsesValue = false;
289       if (I != opBlock.end()) {
290         FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
291       
292         // Check that no other terminators use values.
293 #ifndef NDEBUG
294         for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
295              ++TI) {
296           assert(!InstructionUsesRegister(TI, SrcReg) &&
297                  "Terminator instructions cannot use virtual registers unless"
298                  "they are the first terminator in a block!");
299         }
300 #endif
301       }
302       
303       MachineBasicBlock::iterator KillInst;
304       if (!FirstTerminatorUsesValue) 
305         KillInst = prior(I);
306       else
307         KillInst = I;
308       
309       // Finally, mark it killed.
310       LV->addVirtualRegisterKilled(SrcReg, KillInst);
311
312       // This vreg no longer lives all of the way through opBlock.
313       unsigned opBlockNum = opBlock.getNumber();
314       if (opBlockNum < InRegVI.AliveBlocks.size())
315         InRegVI.AliveBlocks[opBlockNum] = false;
316     }
317   }
318     
319   // Really delete the PHI instruction now!
320   delete MPhi;
321   ++NumAtomic;
322 }
323
324 /// analyzePHINodes - Gather information about the PHI nodes in here. In
325 /// particular, we want to map the number of uses of a virtual register which is
326 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
327 /// used later to determine when the vreg is killed in the BB.
328 ///
329 void PNE::analyzePHINodes(const MachineFunction& Fn) {
330   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
331        I != E; ++I)
332     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
333          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
334       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
335         ++VRegPHIUseCount[BBVRegPair(
336                             BBI->getOperand(i + 1).getMachineBasicBlock(),
337                             BBI->getOperand(i).getReg())];
338 }