Hoist the contents of Loops in depth first order in the dominator tree,
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 // This pass is a simple loop invariant code motion pass.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Transforms/Scalar.h"
8 #include "llvm/Transforms/Utils/Local.h"
9 #include "llvm/Analysis/LoopInfo.h"
10 #include "llvm/Analysis/AliasAnalysis.h"
11 #include "llvm/Analysis/Dominators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/Support/InstVisitor.h"
15 #include "Support/STLExtras.h"
16 #include "Support/StatisticReporter.h"
17 #include <algorithm>
18 using std::string;
19
20 namespace {
21   Statistic<>NumHoisted("licm\t\t- Number of instructions hoisted out of loop");
22   Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
23
24   struct LICM : public FunctionPass, public InstVisitor<LICM> {
25     virtual bool runOnFunction(Function &F);
26
27     /// This transformation requires natural loop information & requires that
28     /// loop preheaders be inserted into the CFG...
29     ///
30     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
31       AU.preservesCFG();
32       AU.addRequiredID(LoopPreheadersID);
33       AU.addRequired<LoopInfo>();
34       AU.addRequired<DominatorTree>();
35       AU.addRequired<AliasAnalysis>();
36     }
37
38   private:
39     Loop *CurLoop;         // The current loop we are working on...
40     BasicBlock *Preheader; // The preheader block of the current loop...
41     bool Changed;          // Set to true when we change anything.
42     AliasAnalysis *AA;     // Currently AliasAnalysis information
43
44     /// visitLoop - Hoist expressions out of the specified loop...    
45     ///
46     void visitLoop(Loop *L);
47
48     /// HoistRegion - Walk the specified region of the CFG (defined by all
49     /// blocks dominated by the specified block, and that are in the current
50     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
51     /// visit defintions before uses, allowing us to hoist a loop body in one
52     /// pass without iteration.
53     ///
54     void HoistRegion(DominatorTree::Node *N);
55
56     /// inCurrentLoop - Little predicate that returns false if the specified
57     /// basic block is in a subloop of the current one, not the current one
58     /// itself.
59     ///
60     bool inCurrentLoop(BasicBlock *BB) {
61       for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
62         if (CurLoop->getSubLoops()[i]->contains(BB))
63           return false;  // A subloop actually contains this block!
64       return true;
65     }
66
67     /// hoist - When an instruction is found to only use loop invariant operands
68     /// that is safe to hoist, this instruction is called to do the dirty work.
69     ///
70     void hoist(Instruction &I);
71
72     /// pointerInvalidatedByLoop - Return true if the body of this loop may
73     /// store into the memory location pointed to by V.
74     /// 
75     bool pointerInvalidatedByLoop(Value *V);
76
77     /// isLoopInvariant - Return true if the specified value is loop invariant
78     ///
79     inline bool isLoopInvariant(Value *V) {
80       if (Instruction *I = dyn_cast<Instruction>(V))
81         return !CurLoop->contains(I->getParent());
82       return true;  // All non-instructions are loop invariant
83     }
84
85     /// Instruction visitation handlers... these basically control whether or
86     /// not the specified instruction types are hoisted.
87     ///
88     friend class InstVisitor<LICM>;
89     void visitBinaryOperator(Instruction &I) {
90       if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
91         hoist(I);
92     }
93     void visitCastInst(CastInst &CI) {
94       Instruction &I = (Instruction&)CI;
95       if (isLoopInvariant(I.getOperand(0))) hoist(I);
96     }
97     void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
98
99     void visitLoadInst(LoadInst &LI);
100
101     void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
102       Instruction &I = (Instruction&)GEPI;
103       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
104         if (!isLoopInvariant(I.getOperand(i))) return;
105       hoist(I);
106     }
107   };
108
109   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
110 }
111
112 Pass *createLICMPass() { return new LICM(); }
113
114 /// runOnFunction - For LICM, this simply traverses the loop structure of the
115 /// function, hoisting expressions out of loops if possible.
116 ///
117 bool LICM::runOnFunction(Function &) {
118   // Get information about the top level loops in the function...
119   const std::vector<Loop*> &TopLevelLoops =
120     getAnalysis<LoopInfo>().getTopLevelLoops();
121
122   // Get our alias analysis information...
123   AA = &getAnalysis<AliasAnalysis>();
124
125   // Traverse loops in postorder, hoisting expressions out of the deepest loops
126   // first.
127   //
128   Changed = false;
129   std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
130                 bind_obj(this, &LICM::visitLoop));
131   return Changed;
132 }
133
134
135 /// visitLoop - Hoist expressions out of the specified loop...    
136 ///
137 void LICM::visitLoop(Loop *L) {
138   // Recurse through all subloops before we process this loop...
139   std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
140                 bind_obj(this, &LICM::visitLoop));
141   CurLoop = L;
142
143   // Get the preheader block to move instructions into...
144   Preheader = L->getLoopPreheader();
145   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
146
147   // We want to visit all of the instructions in this loop... that are not parts
148   // of our subloops (they have already had their invariants hoisted out of
149   // their loop, into this loop, so there is no need to process the BODIES of
150   // the subloops).
151   //
152   // Traverse the body of the loop in depth first order on the dominator tree so
153   // that we are guaranteed to see definitions before we see uses.  This allows
154   // us to perform the LICM transformation in one pass, without iteration.
155   //
156   HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
157
158   // Clear out loops state information for the next iteration
159   CurLoop = 0;
160   Preheader = 0;
161 }
162
163 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
164 /// dominated by the specified block, and that are in the current loop) in depth
165 /// first order w.r.t the DominatorTree.  This allows us to visit defintions
166 /// before uses, allowing us to hoist a loop body in one pass without iteration.
167 ///
168 void LICM::HoistRegion(DominatorTree::Node *N) {
169   assert(N != 0 && "Null dominator tree node?");
170
171   // This subregion is not in the loop, it has already been already been hoisted
172   if (!inCurrentLoop(N->getNode()))
173     return;
174
175   visit(*N->getNode());
176
177   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
178   for (unsigned i = 0, e = Children.size(); i != e; ++i)
179     HoistRegion(Children[i]);
180 }
181
182
183 /// hoist - When an instruction is found to only use loop invariant operands
184 /// that is safe to hoist, this instruction is called to do the dirty work.
185 ///
186 void LICM::hoist(Instruction &Inst) {
187   DEBUG(std::cerr << "LICM hoisting: " << Inst);
188
189   BasicBlock *Header = CurLoop->getHeader();
190
191   // Remove the instruction from its current basic block... but don't delete the
192   // instruction.
193   Inst.getParent()->getInstList().remove(&Inst);
194
195   // Insert the new node in Preheader, before the terminator.
196   Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
197   
198   ++NumHoisted;
199   Changed = true;
200 }
201
202
203 void LICM::visitLoadInst(LoadInst &LI) {
204   if (isLoopInvariant(LI.getOperand(0)) &&
205       !pointerInvalidatedByLoop(LI.getOperand(0))) {
206     hoist(LI);
207     ++NumHoistedLoads;
208   }
209 }
210
211 /// pointerInvalidatedByLoop - Return true if the body of this loop may store
212 /// into the memory location pointed to by V.
213 /// 
214 bool LICM::pointerInvalidatedByLoop(Value *V) {
215   // Check to see if any of the basic blocks in CurLoop invalidate V.
216   for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
217     if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))
218       return true;
219   return false;
220 }