MachineLICM.cpp revision b43ca19cacd0bee7aa506ac6db7bde56abc67c9f
1//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
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 performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "machine-licm"
16#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineDominators.h"
18#include "llvm/CodeGen/MachineLoopInfo.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/Target/MRegisterInfo.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
28
29using namespace llvm;
30
31namespace {
32  // Hidden options to help debugging
33  cl::opt<bool>
34  PerformLICM("machine-licm",
35              cl::init(false), cl::Hidden,
36              cl::desc("Perform loop-invariant code motion on machine code"));
37}
38
39STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
40
41namespace {
42  class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
43    const TargetMachine   *TM;
44    const TargetInstrInfo *TII;
45    MachineFunction       *CurMF; // Current MachineFunction
46
47    // Various analyses that we use...
48    MachineLoopInfo      *LI;   // Current MachineLoopInfo
49    MachineDominatorTree *DT;   // Machine dominator tree for the current Loop
50    MachineRegisterInfo  *RegInfo; // Machine register information
51
52    // State that is updated as we process loops
53    bool         Changed;       // True if a loop is changed.
54    MachineLoop *CurLoop;       // The current loop we are working on.
55  public:
56    static char ID; // Pass identification, replacement for typeid
57    MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
58
59    virtual bool runOnMachineFunction(MachineFunction &MF);
60
61    /// FIXME: Loop preheaders?
62    ///
63    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64      MachineFunctionPass::getAnalysisUsage(AU);
65      AU.setPreservesCFG();
66      AU.addRequired<MachineLoopInfo>();
67      AU.addRequired<MachineDominatorTree>();
68    }
69  private:
70    /// VisitAllLoops - Visit all of the loops in depth first order and try to
71    /// hoist invariant instructions from them.
72    ///
73    void VisitAllLoops(MachineLoop *L) {
74      const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
75
76      for (MachineLoop::iterator
77             I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
78        MachineLoop *ML = *I;
79
80        // Traverse the body of the loop in depth first order on the dominator
81        // tree so that we are guaranteed to see definitions before we see uses.
82        VisitAllLoops(ML);
83        HoistRegion(DT->getNode(ML->getHeader()));
84      }
85
86      HoistRegion(DT->getNode(L->getHeader()));
87    }
88
89    /// IsInSubLoop - A little predicate that returns true if the specified
90    /// basic block is in a subloop of the current one, not the current one
91    /// itself.
92    ///
93    bool IsInSubLoop(MachineBasicBlock *BB) {
94      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
95      return LI->getLoopFor(BB) != CurLoop;
96    }
97
98    /// IsLoopInvariantInst - Returns true if the instruction is loop
99    /// invariant. I.e., all virtual register operands are defined outside of
100    /// the loop, physical registers aren't accessed (explicitly or implicitly),
101    /// and the instruction is hoistable.
102    ///
103    bool IsLoopInvariantInst(MachineInstr &I);
104
105    /// FindPredecessors - Get all of the predecessors of the loop that are not
106    /// back-edges.
107    ///
108    void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
109      const MachineBasicBlock *Header = CurLoop->getHeader();
110
111      for (MachineBasicBlock::const_pred_iterator
112             I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
113        if (!CurLoop->contains(*I))
114          Preds.push_back(*I);
115    }
116
117    /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
118    /// the predecessor basic block (but before the terminator instructions).
119    ///
120    void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
121                              MachineBasicBlock *FromMBB,
122                              MachineInstr *MI) {
123      DEBUG({
124          DOUT << "Hoisting " << *MI;
125          if (ToMBB->getBasicBlock())
126            DOUT << " to MachineBasicBlock "
127                 << ToMBB->getBasicBlock()->getName();
128          DOUT << "\n";
129        });
130
131      MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
132      MachineBasicBlock::iterator To, From = FromMBB->begin();
133
134      while (&*From != MI)
135        ++From;
136
137      assert(From != FromMBB->end() && "Didn't find instr in BB!");
138
139      To = From;
140      ToMBB->splice(WhereIter, FromMBB, From, ++To);
141      ++NumHoisted;
142    }
143
144    /// HoistRegion - Walk the specified region of the CFG (defined by all
145    /// blocks dominated by the specified block, and that are in the current
146    /// loop) in depth first order w.r.t the DominatorTree. This allows us to
147    /// visit definitions before uses, allowing us to hoist a loop body in one
148    /// pass without iteration.
149    ///
150    void HoistRegion(MachineDomTreeNode *N);
151
152    /// Hoist - When an instruction is found to only use loop invariant operands
153    /// that is safe to hoist, this instruction is called to do the dirty work.
154    ///
155    void Hoist(MachineInstr &MI);
156  };
157
158  char MachineLICM::ID = 0;
159  RegisterPass<MachineLICM> X("machine-licm",
160                              "Machine Loop Invariant Code Motion");
161} // end anonymous namespace
162
163FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
164
165/// Hoist expressions out of the specified loop. Note, alias info for inner loop
166/// is not preserved so it is not a good idea to run LICM multiple times on one
167/// loop.
168///
169bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
170  if (!PerformLICM) return false; // For debugging.
171
172  DOUT << "******** Machine LICM ********\n";
173
174  Changed = false;
175  CurMF = &MF;
176  TM = &CurMF->getTarget();
177  TII = TM->getInstrInfo();
178  RegInfo = &CurMF->getRegInfo();
179
180  // Get our Loop information...
181  LI = &getAnalysis<MachineLoopInfo>();
182  DT = &getAnalysis<MachineDominatorTree>();
183
184  for (MachineLoopInfo::iterator
185         I = LI->begin(), E = LI->end(); I != E; ++I) {
186    CurLoop = *I;
187
188    // Visit all of the instructions of the loop. We want to visit the subloops
189    // first, though, so that we can hoist their invariants first into their
190    // containing loop before we process that loop.
191    VisitAllLoops(CurLoop);
192  }
193
194  return Changed;
195}
196
197/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
198/// dominated by the specified block, and that are in the current loop) in depth
199/// first order w.r.t the DominatorTree. This allows us to visit definitions
200/// before uses, allowing us to hoist a loop body in one pass without iteration.
201///
202void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
203  assert(N != 0 && "Null dominator tree node?");
204  MachineBasicBlock *BB = N->getBlock();
205
206  // If this subregion is not in the top level loop at all, exit.
207  if (!CurLoop->contains(BB)) return;
208
209  // Only need to process the contents of this block if it is not part of a
210  // subloop (which would already have been processed).
211  if (!IsInSubLoop(BB))
212    for (MachineBasicBlock::iterator
213           I = BB->begin(), E = BB->end(); I != E; ) {
214      MachineInstr &MI = *I++;
215
216      // Try hoisting the instruction out of the loop. We can only do this if
217      // all of the operands of the instruction are loop invariant and if it is
218      // safe to hoist the instruction.
219      Hoist(MI);
220    }
221
222  const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
223
224  for (unsigned I = 0, E = Children.size(); I != E; ++I)
225    HoistRegion(Children[I]);
226}
227
228/// IsLoopInvariantInst - Returns true if the instruction is loop
229/// invariant. I.e., all virtual register operands are defined outside of the
230/// loop, physical registers aren't accessed explicitly, and there are no side
231/// effects that aren't captured by the operands or other flags.
232///
233bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
234  DEBUG({
235      DOUT << "--- Checking if we can hoist " << I;
236      if (I.getInstrDescriptor()->ImplicitUses) {
237        DOUT << "  * Instruction has implicit uses:\n";
238
239        const MRegisterInfo *MRI = TM->getRegisterInfo();
240        const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
241
242        for (; *ImpUses; ++ImpUses)
243          DOUT << "      -> " << MRI->getName(*ImpUses) << "\n";
244      }
245
246      if (I.getInstrDescriptor()->ImplicitDefs) {
247        DOUT << "  * Instruction has implicit defines:\n";
248
249        const MRegisterInfo *MRI = TM->getRegisterInfo();
250        const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
251
252        for (; *ImpDefs; ++ImpDefs)
253          DOUT << "      -> " << MRI->getName(*ImpDefs) << "\n";
254      }
255
256      if (TII->hasUnmodelledSideEffects(&I))
257        DOUT << "  * Instruction has side effects.\n";
258    });
259
260  // The instruction is loop invariant if all of its operands are loop-invariant
261  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
262    const MachineOperand &MO = I.getOperand(i);
263
264    if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
265      continue;
266
267    unsigned Reg = MO.getReg();
268
269    // Don't hoist instructions that access physical registers.
270    if (!MRegisterInfo::isVirtualRegister(Reg))
271      return false;
272
273    assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
274
275    // If the loop contains the definition of an operand, then the instruction
276    // isn't loop invariant.
277    if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
278      return false;
279  }
280
281  // Don't hoist something that has unmodelled side effects.
282  if (TII->hasUnmodelledSideEffects(&I)) return false;
283
284  // If we got this far, the instruction is loop invariant!
285  return true;
286}
287
288/// Hoist - When an instruction is found to only use loop invariant operands
289/// that is safe to hoist, this instruction is called to do the dirty work.
290///
291void MachineLICM::Hoist(MachineInstr &MI) {
292  if (!IsLoopInvariantInst(MI)) return;
293
294  std::vector<MachineBasicBlock*> Preds;
295
296  // Non-back-edge predecessors.
297  FindPredecessors(Preds);
298
299  // Either we don't have any predecessors(?!) or we have more than one, which
300  // is forbidden.
301  if (Preds.empty() || Preds.size() != 1) return;
302
303  // Check that the predecessor is qualified to take the hoisted
304  // instruction. I.e., there is only one edge from the predecessor, and it's to
305  // the loop header.
306  MachineBasicBlock *MBB = Preds.front();
307
308  // FIXME: We are assuming at first that the basic block coming into this loop
309  // has only one successor. This isn't the case in general because we haven't
310  // broken critical edges or added preheaders.
311  if (MBB->succ_size() != 1) return;
312  assert(*MBB->succ_begin() == CurLoop->getHeader() &&
313         "The predecessor doesn't feed directly into the loop header!");
314
315  // Now move the instructions to the predecessor.
316  MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
317  Changed = true;
318}
319