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