PHIElimination.cpp revision a5c9c245bc37529d3e58c4a2557dc570dc981bbc
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 "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/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Compiler.h"
29#include <algorithm>
30#include <map>
31using namespace llvm;
32
33STATISTIC(NumAtomic, "Number of atomic phis lowered");
34STATISTIC(NumEH,     "Number of EH try blocks skipped");
35
36namespace {
37  class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
38    MachineRegisterInfo  *MRI; // Machine register information
39
40  public:
41    static char ID; // Pass identification, replacement for typeid
42    PNE() : MachineFunctionPass(&ID) {}
43
44    virtual bool runOnMachineFunction(MachineFunction &Fn);
45
46    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47      AU.addPreserved<LiveVariables>();
48      AU.addPreservedID(MachineLoopInfoID);
49      AU.addPreservedID(MachineDominatorsID);
50      MachineFunctionPass::getAnalysisUsage(AU);
51    }
52
53  private:
54    /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
55    /// in predecessor basic blocks.
56    ///
57    bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
58    void LowerAtomicPHINode(MachineBasicBlock &MBB,
59                            MachineBasicBlock::iterator AfterPHIsIt);
60
61    /// analyzePHINodes - Gather information about the PHI nodes in
62    /// here. In particular, we want to map the number of uses of a virtual
63    /// register which is used in a PHI node. We map that to the BB the
64    /// vreg is coming from. This is used later to determine when the vreg
65    /// is killed in the BB.
66    ///
67    void analyzePHINodes(const MachineFunction& Fn);
68
69    void WalkPassEHTryRange(MachineBasicBlock &MBB,
70                            MachineBasicBlock::iterator &I, unsigned SrcReg);
71
72    typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
73    typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
74
75    VRegPHIUse VRegPHIUseCount;
76
77    // Defs of PHI sources which are implicit_def.
78    SmallPtrSet<MachineInstr*, 4> ImpDefs;
79  };
80}
81
82char PNE::ID = 0;
83static RegisterPass<PNE>
84X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
85
86const PassInfo *const llvm::PHIEliminationID = &X;
87
88bool PNE::runOnMachineFunction(MachineFunction &Fn) {
89  MRI = &Fn.getRegInfo();
90
91  analyzePHINodes(Fn);
92
93  bool Changed = false;
94
95  // Eliminate PHI instructions by inserting copies into predecessor blocks.
96  for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
97    Changed |= EliminatePHINodes(Fn, *I);
98
99  // Remove dead IMPLICIT_DEF instructions.
100  for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
101         E = ImpDefs.end(); I != E; ++I) {
102    MachineInstr *DefMI = *I;
103    unsigned DefReg = DefMI->getOperand(0).getReg();
104    if (MRI->use_empty(DefReg))
105      DefMI->eraseFromParent();
106  }
107
108  ImpDefs.clear();
109  VRegPHIUseCount.clear();
110  return Changed;
111}
112
113
114/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
115/// predecessor basic blocks.
116///
117bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
118  if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
119    return false;   // Quick exit for basic blocks without PHIs.
120
121  // Get an iterator to the first instruction after the last PHI node (this may
122  // also be the end of the basic block).
123  MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
124  while (AfterPHIsIt != MBB.end() &&
125         AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
126    ++AfterPHIsIt;    // Skip over all of the PHI nodes...
127
128  while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
129    LowerAtomicPHINode(MBB, AfterPHIsIt);
130
131  return true;
132}
133
134/// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
135/// are implicit_def's.
136static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
137                                         const MachineRegisterInfo *MRI) {
138  for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
139    unsigned SrcReg = MPhi->getOperand(i).getReg();
140    const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
141    if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
142      return false;
143  }
144  return true;
145}
146
147void PNE::WalkPassEHTryRange(MachineBasicBlock &MBB,
148                             MachineBasicBlock::iterator &I, unsigned SrcReg) {
149  if (I == MBB.begin())
150    return;
151  MachineBasicBlock::iterator PI = prior(I);
152  if (PI->getOpcode() != TargetInstrInfo::EH_LABEL)
153    return;
154
155  // Trying to walk pass the EH try range. If we run into a use instruction,
156  // we want to insert the copy there.
157  SmallPtrSet<MachineInstr*, 4> UsesInMBB;
158  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
159         UE = MRI->use_end(); UI != UE; ++UI) {
160    MachineInstr *UseMI = &*UI;
161    if (UseMI->getParent() == &MBB)
162      UsesInMBB.insert(UseMI);
163  }
164
165  while (PI != MBB.begin()) {
166    --PI;
167    if (PI->getOpcode() == TargetInstrInfo::EH_LABEL) {
168      ++NumEH;
169      I = PI;
170      return;
171    } else if (UsesInMBB.count(&*PI)) {
172      ++NumEH;
173      I = next(PI);
174      return;
175    }
176  }
177  return;
178}
179
180/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
181/// under the assuption that it needs to be lowered in a way that supports
182/// atomic execution of PHIs.  This lowering method is always correct all of the
183/// time.
184///
185void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
186                             MachineBasicBlock::iterator AfterPHIsIt) {
187  // Unlink the PHI node from the basic block, but don't delete the PHI yet.
188  MachineInstr *MPhi = MBB.remove(MBB.begin());
189
190  unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
191  unsigned DestReg = MPhi->getOperand(0).getReg();
192  bool isDead = MPhi->getOperand(0).isDead();
193
194  // Create a new register for the incoming PHI arguments.
195  MachineFunction &MF = *MBB.getParent();
196  const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
197  unsigned IncomingReg = 0;
198
199  // Insert a register to register copy at the top of the current block (but
200  // after any remaining phi nodes) which copies the new incoming register
201  // into the phi node destination.
202  const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
203  if (isSourceDefinedByImplicitDef(MPhi, MRI))
204    // If all sources of a PHI node are implicit_def, just emit an
205    // implicit_def instead of a copy.
206    BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
207            TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
208  else {
209    IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
210    TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
211  }
212
213  // Update live variable information if there is any.
214  LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
215  if (LV) {
216    MachineInstr *PHICopy = prior(AfterPHIsIt);
217
218    if (IncomingReg) {
219      // Increment use count of the newly created virtual register.
220      LV->getVarInfo(IncomingReg).NumUses++;
221
222      // Add information to LiveVariables to know that the incoming value is
223      // killed.  Note that because the value is defined in several places (once
224      // each for each incoming block), the "def" block and instruction fields
225      // for the VarInfo is not filled in.
226      LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
227
228      LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
229    }
230
231    // Since we are going to be deleting the PHI node, if it is the last use of
232    // any registers, or if the value itself is dead, we need to move this
233    // information over to the new copy we just inserted.
234    LV->removeVirtualRegistersKilled(MPhi);
235
236    // If the result is dead, update LV.
237    if (isDead) {
238      LV->addVirtualRegisterDead(DestReg, PHICopy);
239      LV->removeVirtualRegisterDead(DestReg, MPhi);
240    }
241  }
242
243  // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
244  for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
245    --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
246                                 MPhi->getOperand(i).getReg())];
247
248  // Now loop over all of the incoming arguments, changing them to copy into the
249  // IncomingReg register in the corresponding predecessor basic block.
250  SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
251  for (int i = NumSrcs - 1; i >= 0; --i) {
252    unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
253    assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
254           "Machine PHI Operands must all be virtual registers!");
255
256    // If source is defined by an implicit def, there is no need to insert a
257    // copy.
258    MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
259    if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
260      ImpDefs.insert(DefMI);
261      continue;
262    }
263
264    // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
265    // path the PHI.
266    MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
267
268    // Check to make sure we haven't already emitted the copy for this block.
269    // This can happen because PHI nodes may have multiple entries for the same
270    // basic block.
271    if (!MBBsInsertedInto.insert(&opBlock))
272      continue;  // If the copy has already been emitted, we're done.
273
274    // Find a safe location to insert the copy, this may be the first terminator
275    // in the block (or end()).
276    MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator();
277
278    // Walk pass EH try range if needed.
279    WalkPassEHTryRange(opBlock, InsertPos, SrcReg);
280
281    // Insert the copy.
282    TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
283
284    // Now update live variable information if we have it.  Otherwise we're done
285    if (!LV) continue;
286
287    // We want to be able to insert a kill of the register if this PHI (aka, the
288    // copy we just inserted) is the last use of the source value.  Live
289    // variable analysis conservatively handles this by saying that the value is
290    // live until the end of the block the PHI entry lives in.  If the value
291    // really is dead at the PHI copy, there will be no successor blocks which
292    // have the value live-in.
293    //
294    // Check to see if the copy is the last use, and if so, update the live
295    // variables information so that it knows the copy source instruction kills
296    // the incoming value.
297    LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
298    InRegVI.UsedBlocks[opBlock.getNumber()] = true;
299
300    // Loop over all of the successors of the basic block, checking to see if
301    // the value is either live in the block, or if it is killed in the block.
302    // Also check to see if this register is in use by another PHI node which
303    // has not yet been eliminated.  If so, it will be killed at an appropriate
304    // point later.
305
306    // Is it used by any PHI instructions in this block?
307    bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
308
309    std::vector<MachineBasicBlock*> OpSuccBlocks;
310
311    // Otherwise, scan successors, including the BB the PHI node lives in.
312    for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
313           E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
314      MachineBasicBlock *SuccMBB = *SI;
315
316      // Is it alive in this successor?
317      unsigned SuccIdx = SuccMBB->getNumber();
318      if (SuccIdx < InRegVI.AliveBlocks.size() &&
319          InRegVI.AliveBlocks[SuccIdx]) {
320        ValueIsLive = true;
321        break;
322      }
323
324      OpSuccBlocks.push_back(SuccMBB);
325    }
326
327    // Check to see if this value is live because there is a use in a successor
328    // that kills it.
329    if (!ValueIsLive) {
330      switch (OpSuccBlocks.size()) {
331      case 1: {
332        MachineBasicBlock *MBB = OpSuccBlocks[0];
333        for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
334          if (InRegVI.Kills[i]->getParent() == MBB) {
335            ValueIsLive = true;
336            break;
337          }
338        break;
339      }
340      case 2: {
341        MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
342        for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
343          if (InRegVI.Kills[i]->getParent() == MBB1 ||
344              InRegVI.Kills[i]->getParent() == MBB2) {
345            ValueIsLive = true;
346            break;
347          }
348        break;
349      }
350      default:
351        std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
352        for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
353          if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
354                                 InRegVI.Kills[i]->getParent())) {
355            ValueIsLive = true;
356            break;
357          }
358      }
359    }
360
361    // Okay, if we now know that the value is not live out of the block, we can
362    // add a kill marker in this block saying that it kills the incoming value!
363    if (!ValueIsLive) {
364      // In our final twist, we have to decide which instruction kills the
365      // register.  In most cases this is the copy, however, the first
366      // terminator instruction at the end of the block may also use the value.
367      // In this case, we should mark *it* as being the killing block, not the
368      // copy.
369      MachineBasicBlock::iterator KillInst = prior(InsertPos);
370      MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
371      if (Term != opBlock.end()) {
372        if (Term->readsRegister(SrcReg))
373          KillInst = Term;
374
375        // Check that no other terminators use values.
376#ifndef NDEBUG
377        for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
378             ++TI) {
379          assert(!TI->readsRegister(SrcReg) &&
380                 "Terminator instructions cannot use virtual registers unless"
381                 "they are the first terminator in a block!");
382        }
383#endif
384      }
385
386      // Finally, mark it killed.
387      LV->addVirtualRegisterKilled(SrcReg, KillInst);
388
389      // This vreg no longer lives all of the way through opBlock.
390      unsigned opBlockNum = opBlock.getNumber();
391      if (opBlockNum < InRegVI.AliveBlocks.size())
392        InRegVI.AliveBlocks[opBlockNum] = false;
393    }
394  }
395
396  // Really delete the PHI instruction now!
397  MF.DeleteMachineInstr(MPhi);
398  ++NumAtomic;
399}
400
401/// analyzePHINodes - Gather information about the PHI nodes in here. In
402/// particular, we want to map the number of uses of a virtual register which is
403/// used in a PHI node. We map that to the BB the vreg is coming from. This is
404/// used later to determine when the vreg is killed in the BB.
405///
406void PNE::analyzePHINodes(const MachineFunction& Fn) {
407  for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
408       I != E; ++I)
409    for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
410         BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
411      for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
412        ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
413                                     BBI->getOperand(i).getReg())];
414}
415