Move the FindCopyInsertPoint method of PHIElimination to a new standalone
[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 is distributed under the University of Illinois Open Source
6 // 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 "PHIElimination.h"
18 #include "PHIEliminationUtils.h"
19 #include "llvm/CodeGen/LiveVariables.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Function.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include <algorithm>
35 #include <map>
36 using namespace llvm;
37
38 STATISTIC(NumAtomic, "Number of atomic phis lowered");
39 STATISTIC(NumReused, "Number of reused lowered phis");
40
41 char PHIElimination::ID = 0;
42 INITIALIZE_PASS(PHIElimination, "phi-node-elimination",
43                 "Eliminate PHI nodes for register allocation", false, false)
44
45 char &llvm::PHIEliminationID = PHIElimination::ID;
46
47 void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
48   AU.addPreserved<LiveVariables>();
49   AU.addPreserved<MachineDominatorTree>();
50   AU.addPreserved<MachineLoopInfo>();
51   MachineFunctionPass::getAnalysisUsage(AU);
52 }
53
54 bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &MF) {
55   MRI = &MF.getRegInfo();
56
57   bool Changed = false;
58
59   // Split critical edges to help the coalescer
60   if (LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>()) {
61     MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
62     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
63       Changed |= SplitPHIEdges(MF, *I, *LV, MLI);
64   }
65
66   // Populate VRegPHIUseCount
67   analyzePHINodes(MF);
68
69   // Eliminate PHI instructions by inserting copies into predecessor blocks.
70   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
71     Changed |= EliminatePHINodes(MF, *I);
72
73   // Remove dead IMPLICIT_DEF instructions.
74   for (SmallPtrSet<MachineInstr*, 4>::iterator I = ImpDefs.begin(),
75          E = ImpDefs.end(); I != E; ++I) {
76     MachineInstr *DefMI = *I;
77     unsigned DefReg = DefMI->getOperand(0).getReg();
78     if (MRI->use_nodbg_empty(DefReg))
79       DefMI->eraseFromParent();
80   }
81
82   // Clean up the lowered PHI instructions.
83   for (LoweredPHIMap::iterator I = LoweredPHIs.begin(), E = LoweredPHIs.end();
84        I != E; ++I)
85     MF.DeleteMachineInstr(I->first);
86
87   LoweredPHIs.clear();
88   ImpDefs.clear();
89   VRegPHIUseCount.clear();
90
91   return Changed;
92 }
93
94 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
95 /// predecessor basic blocks.
96 ///
97 bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
98                                              MachineBasicBlock &MBB) {
99   if (MBB.empty() || !MBB.front().isPHI())
100     return false;   // Quick exit for basic blocks without PHIs.
101
102   // Get an iterator to the first instruction after the last PHI node (this may
103   // also be the end of the basic block).
104   MachineBasicBlock::iterator AfterPHIsIt = MBB.SkipPHIsAndLabels(MBB.begin());
105
106   while (MBB.front().isPHI())
107     LowerAtomicPHINode(MBB, AfterPHIsIt);
108
109   return true;
110 }
111
112 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
113 /// are implicit_def's.
114 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
115                                          const MachineRegisterInfo *MRI) {
116   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
117     unsigned SrcReg = MPhi->getOperand(i).getReg();
118     const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
119     if (!DefMI || !DefMI->isImplicitDef())
120       return false;
121   }
122   return true;
123 }
124
125
126
127 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
128 /// under the assuption that it needs to be lowered in a way that supports
129 /// atomic execution of PHIs.  This lowering method is always correct all of the
130 /// time.
131 ///
132 void llvm::PHIElimination::LowerAtomicPHINode(
133                                       MachineBasicBlock &MBB,
134                                       MachineBasicBlock::iterator AfterPHIsIt) {
135   ++NumAtomic;
136   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
137   MachineInstr *MPhi = MBB.remove(MBB.begin());
138
139   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
140   unsigned DestReg = MPhi->getOperand(0).getReg();
141   assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
142   bool isDead = MPhi->getOperand(0).isDead();
143
144   // Create a new register for the incoming PHI arguments.
145   MachineFunction &MF = *MBB.getParent();
146   unsigned IncomingReg = 0;
147   bool reusedIncoming = false;  // Is IncomingReg reused from an earlier PHI?
148
149   // Insert a register to register copy at the top of the current block (but
150   // after any remaining phi nodes) which copies the new incoming register
151   // into the phi node destination.
152   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
153   if (isSourceDefinedByImplicitDef(MPhi, MRI))
154     // If all sources of a PHI node are implicit_def, just emit an
155     // implicit_def instead of a copy.
156     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
157             TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
158   else {
159     // Can we reuse an earlier PHI node? This only happens for critical edges,
160     // typically those created by tail duplication.
161     unsigned &entry = LoweredPHIs[MPhi];
162     if (entry) {
163       // An identical PHI node was already lowered. Reuse the incoming register.
164       IncomingReg = entry;
165       reusedIncoming = true;
166       ++NumReused;
167       DEBUG(dbgs() << "Reusing %reg" << IncomingReg << " for " << *MPhi);
168     } else {
169       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
170       entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
171     }
172     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
173             TII->get(TargetOpcode::COPY), DestReg)
174       .addReg(IncomingReg);
175   }
176
177   // Update live variable information if there is any.
178   LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
179   if (LV) {
180     MachineInstr *PHICopy = prior(AfterPHIsIt);
181
182     if (IncomingReg) {
183       LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
184
185       // Increment use count of the newly created virtual register.
186       VI.NumUses++;
187       LV->setPHIJoin(IncomingReg);
188
189       // When we are reusing the incoming register, it may already have been
190       // killed in this block. The old kill will also have been inserted at
191       // AfterPHIsIt, so it appears before the current PHICopy.
192       if (reusedIncoming)
193         if (MachineInstr *OldKill = VI.findKill(&MBB)) {
194           DEBUG(dbgs() << "Remove old kill from " << *OldKill);
195           LV->removeVirtualRegisterKilled(IncomingReg, OldKill);
196           DEBUG(MBB.dump());
197         }
198
199       // Add information to LiveVariables to know that the incoming value is
200       // killed.  Note that because the value is defined in several places (once
201       // each for each incoming block), the "def" block and instruction fields
202       // for the VarInfo is not filled in.
203       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
204     }
205
206     // Since we are going to be deleting the PHI node, if it is the last use of
207     // any registers, or if the value itself is dead, we need to move this
208     // information over to the new copy we just inserted.
209     LV->removeVirtualRegistersKilled(MPhi);
210
211     // If the result is dead, update LV.
212     if (isDead) {
213       LV->addVirtualRegisterDead(DestReg, PHICopy);
214       LV->removeVirtualRegisterDead(DestReg, MPhi);
215     }
216   }
217
218   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
219   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
220     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
221                                  MPhi->getOperand(i).getReg())];
222
223   // Now loop over all of the incoming arguments, changing them to copy into the
224   // IncomingReg register in the corresponding predecessor basic block.
225   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
226   for (int i = NumSrcs - 1; i >= 0; --i) {
227     unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
228     unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
229
230     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
231            "Machine PHI Operands must all be virtual registers!");
232
233     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
234     // path the PHI.
235     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
236
237     // If source is defined by an implicit def, there is no need to insert a
238     // copy.
239     MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
240     if (DefMI->isImplicitDef()) {
241       ImpDefs.insert(DefMI);
242       continue;
243     }
244
245     // Check to make sure we haven't already emitted the copy for this block.
246     // This can happen because PHI nodes may have multiple entries for the same
247     // basic block.
248     if (!MBBsInsertedInto.insert(&opBlock))
249       continue;  // If the copy has already been emitted, we're done.
250
251     // Find a safe location to insert the copy, this may be the first terminator
252     // in the block (or end()).
253     MachineBasicBlock::iterator InsertPos =
254       findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
255
256     // Insert the copy.
257     if (!reusedIncoming && IncomingReg)
258       BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
259               TII->get(TargetOpcode::COPY), IncomingReg).addReg(SrcReg, 0, SrcSubReg);
260
261     // Now update live variable information if we have it.  Otherwise we're done
262     if (!LV) continue;
263
264     // We want to be able to insert a kill of the register if this PHI (aka, the
265     // copy we just inserted) is the last use of the source value.  Live
266     // variable analysis conservatively handles this by saying that the value is
267     // live until the end of the block the PHI entry lives in.  If the value
268     // really is dead at the PHI copy, there will be no successor blocks which
269     // have the value live-in.
270
271     // Also check to see if this register is in use by another PHI node which
272     // has not yet been eliminated.  If so, it will be killed at an appropriate
273     // point later.
274
275     // Is it used by any PHI instructions in this block?
276     bool ValueIsUsed = VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)];
277
278     // Okay, if we now know that the value is not live out of the block, we can
279     // add a kill marker in this block saying that it kills the incoming value!
280     if (!ValueIsUsed && !LV->isLiveOut(SrcReg, opBlock)) {
281       // In our final twist, we have to decide which instruction kills the
282       // register.  In most cases this is the copy, however, the first
283       // terminator instruction at the end of the block may also use the value.
284       // In this case, we should mark *it* as being the killing block, not the
285       // copy.
286       MachineBasicBlock::iterator KillInst;
287       MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
288       if (Term != opBlock.end() && Term->readsRegister(SrcReg)) {
289         KillInst = Term;
290
291         // Check that no other terminators use values.
292 #ifndef NDEBUG
293         for (MachineBasicBlock::iterator TI = llvm::next(Term);
294              TI != opBlock.end(); ++TI) {
295           assert(!TI->readsRegister(SrcReg) &&
296                  "Terminator instructions cannot use virtual registers unless"
297                  "they are the first terminator in a block!");
298         }
299 #endif
300       } else if (reusedIncoming || !IncomingReg) {
301         // We may have to rewind a bit if we didn't insert a copy this time.
302         KillInst = Term;
303         while (KillInst != opBlock.begin())
304           if ((--KillInst)->readsRegister(SrcReg))
305             break;
306       } else {
307         // We just inserted this copy.
308         KillInst = prior(InsertPos);
309       }
310       assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
311
312       // Finally, mark it killed.
313       LV->addVirtualRegisterKilled(SrcReg, KillInst);
314
315       // This vreg no longer lives all of the way through opBlock.
316       unsigned opBlockNum = opBlock.getNumber();
317       LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
318     }
319   }
320
321   // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
322   if (reusedIncoming || !IncomingReg)
323     MF.DeleteMachineInstr(MPhi);
324 }
325
326 /// analyzePHINodes - Gather information about the PHI nodes in here. In
327 /// particular, we want to map the number of uses of a virtual register which is
328 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
329 /// used later to determine when the vreg is killed in the BB.
330 ///
331 void llvm::PHIElimination::analyzePHINodes(const MachineFunction& MF) {
332   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
333        I != E; ++I)
334     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
335          BBI != BBE && BBI->isPHI(); ++BBI)
336       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
337         ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i+1).getMBB()->getNumber(),
338                                      BBI->getOperand(i).getReg())];
339 }
340
341 bool llvm::PHIElimination::SplitPHIEdges(MachineFunction &MF,
342                                          MachineBasicBlock &MBB,
343                                          LiveVariables &LV,
344                                          MachineLoopInfo *MLI) {
345   if (MBB.empty() || !MBB.front().isPHI() || MBB.isLandingPad())
346     return false;   // Quick exit for basic blocks without PHIs.
347
348   bool Changed = false;
349   for (MachineBasicBlock::const_iterator BBI = MBB.begin(), BBE = MBB.end();
350        BBI != BBE && BBI->isPHI(); ++BBI) {
351     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
352       unsigned Reg = BBI->getOperand(i).getReg();
353       MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
354       // We break edges when registers are live out from the predecessor block
355       // (not considering PHI nodes). If the register is live in to this block
356       // anyway, we would gain nothing from splitting.
357       // Avoid splitting backedges of loops. It would introduce small
358       // out-of-line blocks into the loop which is very bad for code placement.
359       if (PreMBB != &MBB &&
360           !LV.isLiveIn(Reg, MBB) && LV.isLiveOut(Reg, *PreMBB)) {
361         if (!MLI ||
362             !(MLI->getLoopFor(PreMBB) == MLI->getLoopFor(&MBB) &&
363               MLI->isLoopHeader(&MBB)))
364           Changed |= PreMBB->SplitCriticalEdge(&MBB, this) != 0;
365       }
366     }
367   }
368   return true;
369 }