1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // This pass is a simple loop invariant code motion pass.
5 //===----------------------------------------------------------------------===//
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"
21 Statistic<>NumHoisted("licm\t\t- Number of instructions hoisted out of loop");
22 Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
24 struct LICM : public FunctionPass, public InstVisitor<LICM> {
25 virtual bool runOnFunction(Function &F);
27 /// This transformation requires natural loop information & requires that
28 /// loop preheaders be inserted into the CFG...
30 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
32 AU.addRequiredID(LoopPreheadersID);
33 AU.addRequired<LoopInfo>();
34 AU.addRequired<DominatorTree>();
35 AU.addRequired<AliasAnalysis>();
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
44 /// visitLoop - Hoist expressions out of the specified loop...
46 void visitLoop(Loop *L);
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.
54 void HoistRegion(DominatorTree::Node *N);
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
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!
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.
70 void hoist(Instruction &I);
72 /// pointerInvalidatedByLoop - Return true if the body of this loop may
73 /// store into the memory location pointed to by V.
75 bool pointerInvalidatedByLoop(Value *V);
77 /// isLoopInvariant - Return true if the specified value is loop invariant
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
85 /// Instruction visitation handlers... these basically control whether or
86 /// not the specified instruction types are hoisted.
88 friend class InstVisitor<LICM>;
89 void visitBinaryOperator(Instruction &I) {
90 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
93 void visitCastInst(CastInst &CI) {
94 Instruction &I = (Instruction&)CI;
95 if (isLoopInvariant(I.getOperand(0))) hoist(I);
97 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
99 void visitLoadInst(LoadInst &LI);
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;
109 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
112 Pass *createLICMPass() { return new LICM(); }
114 /// runOnFunction - For LICM, this simply traverses the loop structure of the
115 /// function, hoisting expressions out of loops if possible.
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();
122 // Get our alias analysis information...
123 AA = &getAnalysis<AliasAnalysis>();
125 // Traverse loops in postorder, hoisting expressions out of the deepest loops
129 std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
130 bind_obj(this, &LICM::visitLoop));
135 /// visitLoop - Hoist expressions out of the specified loop...
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));
143 // Get the preheader block to move instructions into...
144 Preheader = L->getLoopPreheader();
145 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
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
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.
156 HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
158 // Clear out loops state information for the next iteration
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.
168 void LICM::HoistRegion(DominatorTree::Node *N) {
169 assert(N != 0 && "Null dominator tree node?");
171 // This subregion is not in the loop, it has already been already been hoisted
172 if (!inCurrentLoop(N->getNode()))
175 visit(*N->getNode());
177 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
178 for (unsigned i = 0, e = Children.size(); i != e; ++i)
179 HoistRegion(Children[i]);
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.
186 void LICM::hoist(Instruction &Inst) {
187 DEBUG(std::cerr << "LICM hoisting: " << Inst);
189 BasicBlock *Header = CurLoop->getHeader();
191 // Remove the instruction from its current basic block... but don't delete the
193 Inst.getParent()->getInstList().remove(&Inst);
195 // Insert the new node in Preheader, before the terminator.
196 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
203 void LICM::visitLoadInst(LoadInst &LI) {
204 if (isLoopInvariant(LI.getOperand(0)) &&
205 !pointerInvalidatedByLoop(LI.getOperand(0))) {
211 /// pointerInvalidatedByLoop - Return true if the body of this loop may store
212 /// into the memory location pointed to by V.
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))