Minor non-functional changes:
[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.  An interesting aspect
4 // of this pass is that it uses alias analysis for two purposes:
5 //
6 //  1. Moving loop invariant loads out of loops.  If we can determine that a
7 //     load inside of a loop never aliases anything stored to, we can hoist it
8 //     like any other instruction.
9 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
10 //     the loop, we try to move the store to happen AFTER the loop instead of
11 //     inside of the loop.  This can only happen if a few conditions are true:
12 //       A. The pointer stored through is loop invariant
13 //       B. There are no stores or loads in the loop which _may_ alias the
14 //          pointer.  There are no calls in the loop which mod/ref the pointer.
15 //     If these conditions are true, we can promote the loads and stores in the
16 //     loop of the pointer to use a temporary alloca'd variable.  We then use
17 //     the mem2reg functionality to construct the appropriate SSA form for the
18 //     variable.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Support/InstVisitor.h"
33 #include "llvm/Support/CFG.h"
34 #include "Support/Statistic.h"
35 #include "Support/CommandLine.h"
36 #include "llvm/Assembly/Writer.h"
37 #include <algorithm>
38
39 namespace {
40   cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
41                              cl::desc("Disable memory promotion in LICM pass"));
42
43   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
44   Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
45   Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
46
47   struct LICM : public FunctionPass, public InstVisitor<LICM> {
48     virtual bool runOnFunction(Function &F);
49
50     /// This transformation requires natural loop information & requires that
51     /// loop preheaders be inserted into the CFG...
52     ///
53     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54       AU.setPreservesCFG();
55       AU.addRequiredID(LoopPreheadersID);
56       AU.addRequired<LoopInfo>();
57       AU.addRequired<DominatorTree>();
58       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
59       AU.addRequired<AliasAnalysis>();
60     }
61
62   private:
63     LoopInfo      *LI;       // Current LoopInfo
64     AliasAnalysis *AA;       // Current AliasAnalysis information
65     bool Changed;            // Set to true when we change anything.
66     BasicBlock *Preheader;   // The preheader block of the current loop...
67     Loop *CurLoop;           // The current loop we are working on...
68     AliasSetTracker *CurAST; // AliasSet information for the current loop...
69
70     /// visitLoop - Hoist expressions out of the specified loop...    
71     ///
72     void visitLoop(Loop *L, AliasSetTracker &AST);
73
74     /// HoistRegion - Walk the specified region of the CFG (defined by all
75     /// blocks dominated by the specified block, and that are in the current
76     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
77     /// visit defintions before uses, allowing us to hoist a loop body in one
78     /// pass without iteration.
79     ///
80     void HoistRegion(DominatorTree::Node *N);
81
82     /// inSubLoop - Little predicate that returns true if the specified basic
83     /// block is in a subloop of the current one, not the current one itself.
84     ///
85     bool inSubLoop(BasicBlock *BB) {
86       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
87       for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
88         if (CurLoop->getSubLoops()[i]->contains(BB))
89           return true;  // A subloop actually contains this block!
90       return false;
91     }
92
93     /// hoist - When an instruction is found to only use loop invariant operands
94     /// that is safe to hoist, this instruction is called to do the dirty work.
95     ///
96     void hoist(Instruction &I);
97
98     /// pointerInvalidatedByLoop - Return true if the body of this loop may
99     /// store into the memory location pointed to by V.
100     /// 
101     bool pointerInvalidatedByLoop(Value *V) {
102       // Check to see if any of the basic blocks in CurLoop invalidate *V.
103       return CurAST->getAliasSetForPointer(V, 0).isMod();
104     }
105
106     /// isLoopInvariant - Return true if the specified value is loop invariant
107     ///
108     inline bool isLoopInvariant(Value *V) {
109       if (Instruction *I = dyn_cast<Instruction>(V))
110         return !CurLoop->contains(I->getParent());
111       return true;  // All non-instructions are loop invariant
112     }
113
114     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
115     /// to scalars as we can.
116     ///
117     void PromoteValuesInLoop();
118
119     /// findPromotableValuesInLoop - Check the current loop for stores to
120     /// definate pointers, which are not loaded and stored through may aliases.
121     /// If these are found, create an alloca for the value, add it to the
122     /// PromotedValues list, and keep track of the mapping from value to
123     /// alloca...
124     ///
125     void findPromotableValuesInLoop(
126                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
127                                     std::map<Value*, AllocaInst*> &Val2AlMap);
128     
129
130     /// Instruction visitation handlers... these basically control whether or
131     /// not the specified instruction types are hoisted.
132     ///
133     friend class InstVisitor<LICM>;
134     void visitBinaryOperator(Instruction &I) {
135       if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
136         hoist(I);
137     }
138     void visitCastInst(CastInst &CI) {
139       Instruction &I = (Instruction&)CI;
140       if (isLoopInvariant(I.getOperand(0))) hoist(I);
141     }
142     void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
143
144     void visitLoadInst(LoadInst &LI);
145
146     void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
147       Instruction &I = (Instruction&)GEPI;
148       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
149         if (!isLoopInvariant(I.getOperand(i))) return;
150       hoist(I);
151     }
152   };
153
154   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
155 }
156
157 Pass *createLICMPass() { return new LICM(); }
158
159 /// runOnFunction - For LICM, this simply traverses the loop structure of the
160 /// function, hoisting expressions out of loops if possible.
161 ///
162 bool LICM::runOnFunction(Function &) {
163   Changed = false;
164
165   // Get our Loop and Alias Analysis information...
166   LI = &getAnalysis<LoopInfo>();
167   AA = &getAnalysis<AliasAnalysis>();
168
169   // Hoist expressions out of all of the top-level loops.
170   const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
171   for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
172          E = TopLevelLoops.end(); I != E; ++I) {
173     AliasSetTracker AST(*AA);
174     LICM::visitLoop(*I, AST);
175   }
176   return Changed;
177 }
178
179
180 /// visitLoop - Hoist expressions out of the specified loop...    
181 ///
182 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
183   // Recurse through all subloops before we process this loop...
184   for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
185          E = L->getSubLoops().end(); I != E; ++I) {
186     AliasSetTracker SubAST(*AA);
187     LICM::visitLoop(*I, SubAST);
188
189     // Incorporate information about the subloops into this loop...
190     AST.add(SubAST);
191   }
192   CurLoop = L;
193   CurAST = &AST;
194
195   // Get the preheader block to move instructions into...
196   Preheader = L->getLoopPreheader();
197   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
198
199   // Loop over the body of this loop, looking for calls, invokes, and stores.
200   // Because subloops have already been incorporated into AST, we skip blocks in
201   // subloops.
202   //
203   const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
204   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
205          E = LoopBBs.end(); I != E; ++I)
206     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
207       AST.add(**I);                     // Incorporate the specified basic block
208
209   // We want to visit all of the instructions in this loop... that are not parts
210   // of our subloops (they have already had their invariants hoisted out of
211   // their loop, into this loop, so there is no need to process the BODIES of
212   // the subloops).
213   //
214   // Traverse the body of the loop in depth first order on the dominator tree so
215   // that we are guaranteed to see definitions before we see uses.  This allows
216   // us to perform the LICM transformation in one pass, without iteration.
217   //
218   HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
219
220   // Now that all loop invariants have been removed from the loop, promote any
221   // memory references to scalars that we can...
222   if (!DisablePromotion)
223     PromoteValuesInLoop();
224
225   // Clear out loops state information for the next iteration
226   CurLoop = 0;
227   Preheader = 0;
228 }
229
230 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
231 /// dominated by the specified block, and that are in the current loop) in depth
232 /// first order w.r.t the DominatorTree.  This allows us to visit defintions
233 /// before uses, allowing us to hoist a loop body in one pass without iteration.
234 ///
235 void LICM::HoistRegion(DominatorTree::Node *N) {
236   assert(N != 0 && "Null dominator tree node?");
237
238   // If this subregion is not in the top level loop at all, exit.
239   if (!CurLoop->contains(N->getNode())) return;
240
241   // Only need to hoist the contents of this block if it is not part of a
242   // subloop (which would already have been hoisted)
243   if (!inSubLoop(N->getNode()))
244     visit(*N->getNode());
245
246   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
247   for (unsigned i = 0, e = Children.size(); i != e; ++i)
248     HoistRegion(Children[i]);
249 }
250
251
252 /// hoist - When an instruction is found to only use loop invariant operands
253 /// that is safe to hoist, this instruction is called to do the dirty work.
254 ///
255 void LICM::hoist(Instruction &Inst) {
256   DEBUG(std::cerr << "LICM hoisting to";
257         WriteAsOperand(std::cerr, Preheader, false);
258         std::cerr << ": " << Inst);
259
260   // Remove the instruction from its current basic block... but don't delete the
261   // instruction.
262   Inst.getParent()->getInstList().remove(&Inst);
263
264   // Insert the new node in Preheader, before the terminator.
265   Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
266   
267   ++NumHoisted;
268   Changed = true;
269 }
270
271
272 void LICM::visitLoadInst(LoadInst &LI) {
273   if (isLoopInvariant(LI.getOperand(0)) &&
274       !pointerInvalidatedByLoop(LI.getOperand(0))) {
275     hoist(LI);
276     ++NumHoistedLoads;
277   }
278 }
279
280 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
281 /// stores out of the loop and moving loads to before the loop.  We do this by
282 /// looping over the stores in the loop, looking for stores to Must pointers
283 /// which are loop invariant.  We promote these memory locations to use allocas
284 /// instead.  These allocas can easily be raised to register values by the
285 /// PromoteMem2Reg functionality.
286 ///
287 void LICM::PromoteValuesInLoop() {
288   // PromotedValues - List of values that are promoted out of the loop.  Each
289   // value has an alloca instruction for it, and a cannonical version of the
290   // pointer.
291   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
292   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
293
294   findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
295   if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
296
297   Changed = true;
298   NumPromoted += PromotedValues.size();
299
300   // Emit a copy from the value into the alloca'd value in the loop preheader
301   TerminatorInst *LoopPredInst = Preheader->getTerminator();
302   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
303     // Load from the memory we are promoting...
304     LoadInst *LI = new LoadInst(PromotedValues[i].second, 
305                                 PromotedValues[i].second->getName()+".promoted",
306                                 LoopPredInst);
307     // Store into the temporary alloca...
308     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
309   }
310   
311   // Scan the basic blocks in the loop, replacing uses of our pointers with
312   // uses of the allocas in question.  If we find a branch that exits the
313   // loop, make sure to put reload code into all of the successors of the
314   // loop.
315   //
316   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
317   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
318          E = LoopBBs.end(); I != E; ++I) {
319     // Rewrite all loads and stores in the block of the pointer...
320     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
321          II != E; ++II) {
322       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
323         std::map<Value*, AllocaInst*>::iterator
324           I = ValueToAllocaMap.find(L->getOperand(0));
325         if (I != ValueToAllocaMap.end())
326           L->setOperand(0, I->second);    // Rewrite load instruction...
327       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
328         std::map<Value*, AllocaInst*>::iterator
329           I = ValueToAllocaMap.find(S->getOperand(1));
330         if (I != ValueToAllocaMap.end())
331           S->setOperand(1, I->second);    // Rewrite store instruction...
332       }
333     }
334
335     // Check to see if any successors of this block are outside of the loop.
336     // If so, we need to copy the value from the alloca back into the memory
337     // location...
338     //
339     for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
340       if (!CurLoop->contains(*SI)) {
341         // Copy all of the allocas into their memory locations...
342         BasicBlock::iterator BI = (*SI)->begin();
343         while (isa<PHINode>(*BI))
344           ++BI;             // Skip over all of the phi nodes in the block...
345         Instruction *InsertPos = BI;
346         for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
347           // Load from the alloca...
348           LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
349           // Store into the memory we promoted...
350           new StoreInst(LI, PromotedValues[i].second, InsertPos);
351         }
352       }
353   }
354
355   // Now that we have done the deed, use the mem2reg functionality to promote
356   // all of the new allocas we just created into real SSA registers...
357   //
358   std::vector<AllocaInst*> PromotedAllocas;
359   PromotedAllocas.reserve(PromotedValues.size());
360   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
361     PromotedAllocas.push_back(PromotedValues[i].first);
362   PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>(),
363                   AA->getTargetData());
364 }
365
366 /// findPromotableValuesInLoop - Check the current loop for stores to definate
367 /// pointers, which are not loaded and stored through may aliases.  If these are
368 /// found, create an alloca for the value, add it to the PromotedValues list,
369 /// and keep track of the mapping from value to alloca...
370 ///
371 void LICM::findPromotableValuesInLoop(
372                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
373                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
374   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
375
376   // Loop over all of the alias sets in the tracker object...
377   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
378        I != E; ++I) {
379     AliasSet &AS = *I;
380     // We can promote this alias set if it has a store, if it is a "Must" alias
381     // set, and if the pointer is loop invariant.
382     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
383         isLoopInvariant(AS.begin()->first)) {
384       assert(AS.begin() != AS.end() &&
385              "Must alias set should have at least one pointer element in it!");
386       Value *V = AS.begin()->first;
387
388       // Check that all of the pointers in the alias set have the same type.  We
389       // cannot (yet) promote a memory location that is loaded and stored in
390       // different sizes.
391       bool PointerOk = true;
392       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
393         if (V->getType() != I->first->getType()) {
394           PointerOk = false;
395           break;
396         }
397
398       if (PointerOk) {
399         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
400         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
401         PromotedValues.push_back(std::make_pair(AI, V));
402         
403         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
404           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
405         
406         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
407       }
408     }
409   }
410 }