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