534a073abe190bf04d33a54477006545327a8a51
[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/Dominators.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
33 #include "Support/CommandLine.h"
34 #include "llvm/Assembly/Writer.h"
35 #include <algorithm>
36
37 namespace {
38   cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
39                              cl::desc("Disable memory promotion in LICM pass"));
40
41   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
42   Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
43   Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
44
45   /// LoopBodyInfo - We recursively traverse loops from most-deeply-nested to
46   /// least-deeply-nested.  For all of the loops nested within the current one,
47   /// we keep track of information so that we don't have to repeat queries.
48   ///
49   struct LoopBodyInfo {
50     std::vector<CallInst*> Calls;          // Call instructions in loop
51     std::vector<InvokeInst*> Invokes;      // Invoke instructions in loop
52
53     // StoredPointers - Targets of store instructions...
54     std::set<Value*> StoredPointers;
55
56     // LoadedPointers - Source pointers for load instructions...
57     std::set<Value*> LoadedPointers;
58
59     enum PointerClass {
60       PointerUnknown = 0, // Nothing is known about this pointer yet
61       PointerMustStore,   // Memory is stored to ONLY through this pointer
62       PointerMayStore,    // Memory is stored to through this or other pointers
63       PointerNoStore      // Memory is not modified in this loop
64     };
65
66     // PointerIsModified - Keep track of information as we find out about it in
67     // the loop body...
68     //
69     std::map<Value*, enum PointerClass> PointerIsModified;
70
71     /// CantModifyAnyPointers - Return true if no memory modifying instructions
72     /// occur in this loop.  This is just a conservative approximation, because
73     /// a call may not actually store anything.
74     bool CantModifyAnyPointers() const {
75       return Calls.empty() && Invokes.empty() && StoredPointers.empty();
76     }
77
78     /// incorporate - Incorporate information about a subloop into the current
79     /// loop.
80     void incorporate(const LoopBodyInfo &OtherLBI);
81     void incorporate(BasicBlock &BB);  // do the same for a basic block
82
83     PointerClass getPointerInfo(Value *V, AliasAnalysis &AA) {
84       PointerClass &VInfo = PointerIsModified[V];
85       if (VInfo == PointerUnknown)
86         VInfo = calculatePointerInfo(V, AA);
87       return VInfo;
88     }
89   private:
90     /// calculatePointerInfo - Calculate information about the specified
91     /// pointer.
92     PointerClass calculatePointerInfo(Value *V, AliasAnalysis &AA) const;
93   };
94 }
95
96 /// incorporate - Incorporate information about a subloop into the current loop.
97 void LoopBodyInfo::incorporate(const LoopBodyInfo &OtherLBI) {
98   // Do not incorporate NonModifiedPointers (which is just a cache) because it
99   // is too much trouble to make sure it's still valid.
100   Calls.insert  (Calls.end(),  OtherLBI.Calls.begin(),  OtherLBI.Calls.end());
101   Invokes.insert(Invokes.end(),OtherLBI.Invokes.begin(),OtherLBI.Invokes.end());
102   StoredPointers.insert(OtherLBI.StoredPointers.begin(),
103                         OtherLBI.StoredPointers.end());
104   LoadedPointers.insert(OtherLBI.LoadedPointers.begin(),
105                         OtherLBI.LoadedPointers.end());
106 }
107
108 void LoopBodyInfo::incorporate(BasicBlock &BB) {
109   for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
110     if (CallInst *CI = dyn_cast<CallInst>(&*I))
111       Calls.push_back(CI);
112     else if (StoreInst *SI = dyn_cast<StoreInst>(&*I))
113       StoredPointers.insert(SI->getOperand(1));
114     else if (LoadInst *LI = dyn_cast<LoadInst>(&*I))
115       LoadedPointers.insert(LI->getOperand(0));
116
117   if (InvokeInst *II = dyn_cast<InvokeInst>(BB.getTerminator()))
118     Invokes.push_back(II);
119 }
120
121
122 // calculatePointerInfo - Calculate information about the specified pointer.
123 LoopBodyInfo::PointerClass LoopBodyInfo::calculatePointerInfo(Value *V,
124                                                       AliasAnalysis &AA) const {
125   for (unsigned i = 0, e = Calls.size(); i != e; ++i)
126     if (AA.getModRefInfo(Calls[i], V, ~0))
127       return PointerMayStore;
128
129   for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
130     if (AA.getModRefInfo(Invokes[i], V, ~0))
131       return PointerMayStore;
132
133   PointerClass Result = PointerNoStore;
134   for (std::set<Value*>::const_iterator I = StoredPointers.begin(),
135          E = StoredPointers.end(); I != E; ++I)
136     if (AA.alias(V, ~0, *I, ~0))
137       if (V == *I)
138         Result = PointerMustStore;   // If this is the only alias, return must
139       else
140         return PointerMayStore;      // We have to return may
141   return Result;
142 }
143
144 namespace {
145   struct LICM : public FunctionPass, public InstVisitor<LICM> {
146     virtual bool runOnFunction(Function &F);
147
148     /// This transformation requires natural loop information & requires that
149     /// loop preheaders be inserted into the CFG...
150     ///
151     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152       AU.setPreservesCFG();
153       AU.addRequiredID(LoopPreheadersID);
154       AU.addRequired<LoopInfo>();
155       AU.addRequired<DominatorTree>();
156       AU.addRequired<DominanceFrontier>();
157       AU.addRequired<AliasAnalysis>();
158     }
159
160   private:
161     LoopInfo      *LI;       // Current LoopInfo
162     AliasAnalysis *AA;       // Current AliasAnalysis information
163     bool Changed;            // Set to true when we change anything.
164     BasicBlock *Preheader;   // The preheader block of the current loop...
165     Loop *CurLoop;           // The current loop we are working on...
166     LoopBodyInfo *CurLBI;    // Information about the current loop...
167
168     /// visitLoop - Hoist expressions out of the specified loop...    
169     ///
170     void visitLoop(Loop *L, LoopBodyInfo &LBI);
171
172     /// HoistRegion - Walk the specified region of the CFG (defined by all
173     /// blocks dominated by the specified block, and that are in the current
174     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
175     /// visit defintions before uses, allowing us to hoist a loop body in one
176     /// pass without iteration.
177     ///
178     void HoistRegion(DominatorTree::Node *N);
179
180     /// inSubLoop - Little predicate that returns true if the specified basic
181     /// block is in a subloop of the current one, not the current one itself.
182     ///
183     bool inSubLoop(BasicBlock *BB) {
184       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
185       for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
186         if (CurLoop->getSubLoops()[i]->contains(BB))
187           return true;  // A subloop actually contains this block!
188       return false;
189     }
190
191     /// hoist - When an instruction is found to only use loop invariant operands
192     /// that is safe to hoist, this instruction is called to do the dirty work.
193     ///
194     void hoist(Instruction &I);
195
196     /// pointerInvalidatedByLoop - Return true if the body of this loop may
197     /// store into the memory location pointed to by V.
198     /// 
199     bool pointerInvalidatedByLoop(Value *V) {
200       // Check to see if any of the basic blocks in CurLoop invalidate V.
201       return CurLBI->getPointerInfo(V, *AA) != LoopBodyInfo::PointerNoStore;
202     }
203
204     /// isLoopInvariant - Return true if the specified value is loop invariant
205     ///
206     inline bool isLoopInvariant(Value *V) {
207       if (Instruction *I = dyn_cast<Instruction>(V))
208         return !CurLoop->contains(I->getParent());
209       return true;  // All non-instructions are loop invariant
210     }
211
212     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
213     /// to scalars as we can.
214     ///
215     void PromoteValuesInLoop();
216
217     /// findPromotableValuesInLoop - Check the current loop for stores to
218     /// definate pointers, which are not loaded and stored through may aliases.
219     /// If these are found, create an alloca for the value, add it to the
220     /// PromotedValues list, and keep track of the mapping from value to
221     /// alloca...
222     ///
223     void findPromotableValuesInLoop(
224                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
225                                     std::map<Value*, AllocaInst*> &Val2AlMap);
226     
227
228     /// Instruction visitation handlers... these basically control whether or
229     /// not the specified instruction types are hoisted.
230     ///
231     friend class InstVisitor<LICM>;
232     void visitBinaryOperator(Instruction &I) {
233       if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
234         hoist(I);
235     }
236     void visitCastInst(CastInst &CI) {
237       Instruction &I = (Instruction&)CI;
238       if (isLoopInvariant(I.getOperand(0))) hoist(I);
239     }
240     void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
241
242     void visitLoadInst(LoadInst &LI);
243
244     void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
245       Instruction &I = (Instruction&)GEPI;
246       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
247         if (!isLoopInvariant(I.getOperand(i))) return;
248       hoist(I);
249     }
250   };
251
252   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
253 }
254
255 Pass *createLICMPass() { return new LICM(); }
256
257 /// runOnFunction - For LICM, this simply traverses the loop structure of the
258 /// function, hoisting expressions out of loops if possible.
259 ///
260 bool LICM::runOnFunction(Function &) {
261   Changed = false;
262
263   // Get our Loop and Alias Analysis information...
264   LI = &getAnalysis<LoopInfo>();
265   AA = &getAnalysis<AliasAnalysis>();
266
267   // Hoist expressions out of all of the top-level loops.
268   const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
269   for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
270          E = TopLevelLoops.end(); I != E; ++I) {
271     LoopBodyInfo LBI;
272     LICM::visitLoop(*I, LBI);
273   }
274   return Changed;
275 }
276
277
278 /// visitLoop - Hoist expressions out of the specified loop...    
279 ///
280 void LICM::visitLoop(Loop *L, LoopBodyInfo &LBI) {
281   // Recurse through all subloops before we process this loop...
282   for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
283          E = L->getSubLoops().end(); I != E; ++I) {
284     LoopBodyInfo SubLBI;
285     LICM::visitLoop(*I, SubLBI);
286
287     // Incorporate information about the subloops into this loop...
288     LBI.incorporate(SubLBI);
289   }
290   CurLoop = L;
291   CurLBI = &LBI;
292
293   // Get the preheader block to move instructions into...
294   Preheader = L->getLoopPreheader();
295   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
296
297   // Loop over the body of this loop, looking for calls, invokes, and stores.
298   // Because subloops have already been incorporated into LBI, we skip blocks in
299   // subloops.
300   //
301   const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
302   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
303          E = LoopBBs.end(); I != E; ++I)
304     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
305       LBI.incorporate(**I);             // Incorporate the specified basic block
306
307   // We want to visit all of the instructions in this loop... that are not parts
308   // of our subloops (they have already had their invariants hoisted out of
309   // their loop, into this loop, so there is no need to process the BODIES of
310   // the subloops).
311   //
312   // Traverse the body of the loop in depth first order on the dominator tree so
313   // that we are guaranteed to see definitions before we see uses.  This allows
314   // us to perform the LICM transformation in one pass, without iteration.
315   //
316   HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
317
318   // Now that all loop invariants have been removed from the loop, promote any
319   // memory references to scalars that we can...
320   if (!DisablePromotion)
321     PromoteValuesInLoop();
322
323   // Clear out loops state information for the next iteration
324   CurLoop = 0;
325   Preheader = 0;
326 }
327
328 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
329 /// dominated by the specified block, and that are in the current loop) in depth
330 /// first order w.r.t the DominatorTree.  This allows us to visit defintions
331 /// before uses, allowing us to hoist a loop body in one pass without iteration.
332 ///
333 void LICM::HoistRegion(DominatorTree::Node *N) {
334   assert(N != 0 && "Null dominator tree node?");
335
336   // If this subregion is not in the top level loop at all, exit.
337   if (!CurLoop->contains(N->getNode())) return;
338
339   // Only need to hoist the contents of this block if it is not part of a
340   // subloop (which would already have been hoisted)
341   if (!inSubLoop(N->getNode()))
342     visit(*N->getNode());
343
344   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
345   for (unsigned i = 0, e = Children.size(); i != e; ++i)
346     HoistRegion(Children[i]);
347 }
348
349
350 /// hoist - When an instruction is found to only use loop invariant operands
351 /// that is safe to hoist, this instruction is called to do the dirty work.
352 ///
353 void LICM::hoist(Instruction &Inst) {
354   DEBUG(std::cerr << "LICM hoisting to";
355         WriteAsOperand(std::cerr, Preheader, false);
356         std::cerr << ": " << Inst);
357
358   // Remove the instruction from its current basic block... but don't delete the
359   // instruction.
360   Inst.getParent()->getInstList().remove(&Inst);
361
362   // Insert the new node in Preheader, before the terminator.
363   Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
364   
365   ++NumHoisted;
366   Changed = true;
367 }
368
369
370 void LICM::visitLoadInst(LoadInst &LI) {
371   if (isLoopInvariant(LI.getOperand(0)) &&
372       !pointerInvalidatedByLoop(LI.getOperand(0))) {
373     hoist(LI);
374     ++NumHoistedLoads;
375   }
376 }
377
378 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
379 /// stores out of the loop and moving loads to before the loop.  We do this by
380 /// looping over the stores in the loop, looking for stores to Must pointers
381 /// which are loop invariant.  We promote these memory locations to use allocas
382 /// instead.  These allocas can easily be raised to register values by the
383 /// PromoteMem2Reg functionality.
384 ///
385 void LICM::PromoteValuesInLoop() {
386   // PromotedValues - List of values that are promoted out of the loop.  Each
387   // value has an alloca instruction for it, and a cannonical version of the
388   // pointer.
389   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
390   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
391
392   findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
393   if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
394
395   Changed = true;
396   NumPromoted += PromotedValues.size();
397
398   // Emit a copy from the value into the alloca'd value in the loop preheader
399   TerminatorInst *LoopPredInst = Preheader->getTerminator();
400   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
401     // Load from the memory we are promoting...
402     LoadInst *LI = new LoadInst(PromotedValues[i].second, 
403                                 PromotedValues[i].second->getName()+".promoted",
404                                 LoopPredInst);
405     // Store into the temporary alloca...
406     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
407   }
408   
409   // Scan the basic blocks in the loop, replacing uses of our pointers with
410   // uses of the allocas in question.  If we find a branch that exits the
411   // loop, make sure to put reload code into all of the successors of the
412   // loop.
413   //
414   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
415   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
416          E = LoopBBs.end(); I != E; ++I) {
417     // Rewrite all loads and stores in the block of the pointer...
418     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
419          II != E; ++II) {
420       if (LoadInst *L = dyn_cast<LoadInst>(&*II)) {
421         std::map<Value*, AllocaInst*>::iterator
422           I = ValueToAllocaMap.find(L->getOperand(0));
423         if (I != ValueToAllocaMap.end())
424           L->setOperand(0, I->second);    // Rewrite load instruction...
425       } else if (StoreInst *S = dyn_cast<StoreInst>(&*II)) {
426         std::map<Value*, AllocaInst*>::iterator
427           I = ValueToAllocaMap.find(S->getOperand(1));
428         if (I != ValueToAllocaMap.end())
429           S->setOperand(1, I->second);    // Rewrite store instruction...
430       }
431     }
432
433     // Check to see if any successors of this block are outside of the loop.
434     // If so, we need to copy the value from the alloca back into the memory
435     // location...
436     //
437     for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
438       if (!CurLoop->contains(*SI)) {
439         // Copy all of the allocas into their memory locations...
440         BasicBlock::iterator BI = (*SI)->begin();
441         while (isa<PHINode>(*BI))
442           ++BI;             // Skip over all of the phi nodes in the block...
443         Instruction *InsertPos = BI;
444         for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
445           // Load from the alloca...
446           LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
447           // Store into the memory we promoted...
448           new StoreInst(LI, PromotedValues[i].second, InsertPos);
449         }
450       }
451   }
452
453   // Now that we have done the deed, use the mem2reg functionality to promote
454   // all of the new allocas we just created into real SSA registers...
455   //
456   std::vector<AllocaInst*> PromotedAllocas;
457   PromotedAllocas.reserve(PromotedValues.size());
458   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
459     PromotedAllocas.push_back(PromotedValues[i].first);
460   PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>());
461 }
462
463 /// findPromotableValuesInLoop - Check the current loop for stores to definate
464 /// pointers, which are not loaded and stored through may aliases.  If these are
465 /// found, create an alloca for the value, add it to the PromotedValues list,
466 /// and keep track of the mapping from value to alloca...
467 ///
468 void LICM::findPromotableValuesInLoop(
469                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
470                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
471   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
472
473   for (std::set<Value*>::iterator I = CurLBI->StoredPointers.begin(),
474          E = CurLBI->StoredPointers.end(); I != E; ++I) {
475     Value *V = *I;
476     if (isLoopInvariant(V) &&
477         CurLBI->getPointerInfo(V, *AA) == LoopBodyInfo::PointerMustStore) {
478
479       // Don't add a new entry for this stored pointer if it aliases something
480       // we have already processed.
481       std::map<Value*, AllocaInst*>::iterator V2AMI = 
482         ValueToAllocaMap.lower_bound(V);
483       if (V2AMI == ValueToAllocaMap.end() || V2AMI->first != V) {
484         // Check to make sure that any loads in the loop are either NO or MUST
485         // aliases.  We cannot rewrite loads that _might_ come from this memory
486         // location.
487
488         bool PointerOk = true;
489         for (std::set<Value*>::const_iterator I =CurLBI->LoadedPointers.begin(),
490                E = CurLBI->LoadedPointers.end(); I != E; ++I)
491           if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MayAlias) {
492             PointerOk = false;
493             break;
494           }
495
496         if (PointerOk) {
497           const Type *Ty = cast<PointerType>(V->getType())->getElementType();
498           AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
499           PromotedValues.push_back(std::make_pair(AI, V));
500           ValueToAllocaMap.insert(V2AMI, std::make_pair(V, AI));
501
502           DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
503
504           // Loop over all of the loads and stores that alias this pointer,
505           // adding them to the Value2AllocaMap as well...
506           for (std::set<Value*>::const_iterator
507                  I = CurLBI->LoadedPointers.begin(),
508                  E = CurLBI->LoadedPointers.end(); I != E; ++I)
509             if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
510               ValueToAllocaMap[*I] = AI;
511
512           for (std::set<Value*>::const_iterator
513                  I = CurLBI->StoredPointers.begin(),
514                  E = CurLBI->StoredPointers.end(); I != E; ++I)
515             if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
516               ValueToAllocaMap[*I] = AI;
517         }
518       }
519     }
520   }
521 }