MachineSink.cpp revision aad193a7e9f8eb4b558e16c2b54c31dee54f5f1e
1//===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "machine-sink"
15#include "llvm/CodeGen/Passes.h"
16#include "llvm/CodeGen/MachineRegisterInfo.h"
17#include "llvm/CodeGen/MachineDominators.h"
18#include "llvm/Target/MRegisterInfo.h"
19#include "llvm/Target/TargetInstrInfo.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25using namespace llvm;
26
27STATISTIC(NumSunk, "Number of machine instructions sunk");
28
29namespace {
30  class VISIBILITY_HIDDEN MachineSinking : public MachineFunctionPass {
31    const TargetMachine   *TM;
32    const TargetInstrInfo *TII;
33    MachineFunction       *CurMF; // Current MachineFunction
34    MachineRegisterInfo  *RegInfo; // Machine register information
35    MachineDominatorTree *DT;   // Machine dominator tree for the current Loop
36
37  public:
38    static char ID; // Pass identification
39    MachineSinking() : MachineFunctionPass((intptr_t)&ID) {}
40
41    virtual bool runOnMachineFunction(MachineFunction &MF);
42
43    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44      MachineFunctionPass::getAnalysisUsage(AU);
45      AU.addRequired<MachineDominatorTree>();
46      AU.addPreserved<MachineDominatorTree>();
47    }
48  private:
49    bool ProcessBlock(MachineBasicBlock &MBB);
50    bool SinkInstruction(MachineInstr *MI, bool &SawStore);
51    bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
52  };
53
54  char MachineSinking::ID = 0;
55  RegisterPass<MachineSinking> X("machine-sink", "Machine code sinking");
56} // end anonymous namespace
57
58FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
59
60/// AllUsesDominatedByBlock - Return true if all uses of the specified register
61/// occur in blocks dominated by the specified block.
62bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
63                                             MachineBasicBlock *MBB) const {
64  assert(MRegisterInfo::isVirtualRegister(Reg) && "Only makes sense for vregs");
65  for (MachineRegisterInfo::reg_iterator I = RegInfo->reg_begin(Reg),
66       E = RegInfo->reg_end(); I != E; ++I) {
67    if (I.getOperand().isDef()) continue;  // ignore def.
68
69    // Determine the block of the use.
70    MachineInstr *UseInst = &*I;
71    MachineBasicBlock *UseBlock = UseInst->getParent();
72    if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
73      // PHI nodes use the operand in the predecessor block, not the block with
74      // the PHI.
75      UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
76    }
77    // Check that it dominates.
78    if (!DT->dominates(MBB, UseBlock))
79      return false;
80  }
81  return true;
82}
83
84
85
86bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
87  DOUT << "******** Machine Sinking ********\n";
88
89  CurMF = &MF;
90  TM = &CurMF->getTarget();
91  TII = TM->getInstrInfo();
92  RegInfo = &CurMF->getRegInfo();
93  DT = &getAnalysis<MachineDominatorTree>();
94
95  bool EverMadeChange = false;
96
97  while (1) {
98    bool MadeChange = false;
99
100    // Process all basic blocks.
101    for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end();
102         I != E; ++I)
103      MadeChange |= ProcessBlock(*I);
104
105    // If this iteration over the code changed anything, keep iterating.
106    if (!MadeChange) break;
107    EverMadeChange = true;
108  }
109  return EverMadeChange;
110}
111
112bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
113  bool MadeChange = false;
114
115  // Can't sink anything out of a block that has less than two successors.
116  if (MBB.succ_size() <= 1) return false;
117
118  // Walk the basic block bottom-up.  Remember if we saw a store.
119  bool SawStore = false;
120  for (MachineBasicBlock::iterator I = MBB.end(); I != MBB.begin(); ){
121    MachineBasicBlock::iterator LastIt = I;
122    if (SinkInstruction(--I, SawStore)) {
123      I = LastIt;
124      ++NumSunk;
125    }
126  }
127
128  return MadeChange;
129}
130
131/// SinkInstruction - Determine whether it is safe to sink the specified machine
132/// instruction out of its current block into a successor.
133bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
134  const TargetInstrDesc &TID = MI->getDesc();
135
136  // Ignore stuff that we obviously can't sink.
137  if (TID.mayStore() || TID.isCall()) {
138    SawStore = true;
139    return false;
140  }
141  if (TID.isReturn() || TID.isBranch() || TID.hasUnmodeledSideEffects())
142    return false;
143
144  // See if this instruction does a load.  If so, we have to guarantee that the
145  // loaded value doesn't change between the load and the end of block.  The
146  // check for isInvariantLoad gives the targe the chance to classify the load
147  // as always returning a constant, e.g. a constant pool load.
148  if (TID.mayLoad() && !TII->isInvariantLoad(MI)) {
149    // Otherwise, this is a real load.  If there is a store between the load and
150    // end of block, we can't sink the load.
151    //
152    // FIXME: we can't do this transformation until we know that the load is
153    // not volatile, and machineinstrs don't keep this info. :(
154    //
155    //if (SawStore)
156    return false;
157  }
158
159  // FIXME: This should include support for sinking instructions within the
160  // block they are currently in to shorten the live ranges.  We often get
161  // instructions sunk into the top of a large block, but it would be better to
162  // also sink them down before their first use in the block.  This xform has to
163  // be careful not to *increase* register pressure though, e.g. sinking
164  // "x = y + z" down if it kills y and z would increase the live ranges of y
165  // and z only the shrink the live range of x.
166
167  // Loop over all the operands of the specified instruction.  If there is
168  // anything we can't handle, bail out.
169  MachineBasicBlock *ParentBlock = MI->getParent();
170
171  // SuccToSinkTo - This is the successor to sink this instruction to, once we
172  // decide.
173  MachineBasicBlock *SuccToSinkTo = 0;
174
175  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
176    const MachineOperand &MO = MI->getOperand(i);
177    if (!MO.isReg()) continue;  // Ignore non-register operands.
178
179    unsigned Reg = MO.getReg();
180    if (Reg == 0) continue;
181
182    if (MRegisterInfo::isPhysicalRegister(Reg)) {
183      // If this is a physical register use, we can't move it.  If it is a def,
184      // we can move it, but only if the def is dead.
185      if (MO.isUse() || !MO.isDead())
186        return false;
187    } else {
188      // Virtual register uses are always safe to sink.
189      if (MO.isUse()) continue;
190
191      // FIXME: This picks a successor to sink into based on having one
192      // successor that dominates all the uses.  However, there are cases where
193      // sinking can happen but where the sink point isn't a successor.  For
194      // example:
195      //   x = computation
196      //   if () {} else {}
197      //   use x
198      // the instruction could be sunk over the whole diamond for the
199      // if/then/else (or loop, etc), allowing it to be sunk into other blocks
200      // after that.
201
202      // Virtual register defs can only be sunk if all their uses are in blocks
203      // dominated by one of the successors.
204      if (SuccToSinkTo) {
205        // If a previous operand picked a block to sink to, then this operand
206        // must be sinkable to the same block.
207        if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
208          return false;
209        continue;
210      }
211
212      // Otherwise, we should look at all the successors and decide which one
213      // we should sink to.
214      for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
215           E = ParentBlock->succ_end(); SI != E; ++SI) {
216        if (AllUsesDominatedByBlock(Reg, *SI)) {
217          SuccToSinkTo = *SI;
218          break;
219        }
220      }
221
222      // If we couldn't find a block to sink to, ignore this instruction.
223      if (SuccToSinkTo == 0)
224        return false;
225    }
226  }
227
228  // If there are no outputs, it must have side-effects.
229  if (SuccToSinkTo == 0)
230    return false;
231
232  DEBUG(cerr << "Sink instr " << *MI);
233  DEBUG(cerr << "to block " << *SuccToSinkTo);
234
235  // If the block has multiple predecessors, this would introduce computation on
236  // a path that it doesn't already exist.  We could split the critical edge,
237  // but for now we just punt.
238  // FIXME: Split critical edges if not backedges.
239  if (SuccToSinkTo->pred_size() > 1) {
240    DEBUG(cerr << " *** PUNTING: Critical edge found\n");
241    return false;
242  }
243
244  // Determine where to insert into.  Skip phi nodes.
245  MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
246  while (InsertPos != SuccToSinkTo->end() &&
247         InsertPos->getOpcode() == TargetInstrInfo::PHI)
248    ++InsertPos;
249
250  // Move the instruction.
251  SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
252                       ++MachineBasicBlock::iterator(MI));
253  return true;
254}
255