Revert r110396 to fix buildbots.
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible.  It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe.  This pass also promotes must-aliased memory locations in the loop to
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
15 //
16 // This pass uses alias analysis for two purposes:
17 //
18 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
19 //     that a load or call inside of a loop never aliases anything stored to,
20 //     we can hoist it or sink it like any other instruction.
21 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
22 //     the loop, we try to move the store to happen AFTER the loop instead of
23 //     inside of the loop.  This can only happen if a few conditions are true:
24 //       A. The pointer stored through is loop invariant
25 //       B. There are no stores or loads in the loop which _may_ alias the
26 //          pointer.  There are no calls in the loop which mod/ref the pointer.
27 //     If these conditions are true, we can promote the loads and stores in the
28 //     loop of the pointer to use a temporary alloca'd variable.  We then use
29 //     the mem2reg functionality to construct the appropriate SSA form for the
30 //     variable.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #define DEBUG_TYPE "licm"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Analysis/LoopInfo.h"
42 #include "llvm/Analysis/LoopPass.h"
43 #include "llvm/Analysis/AliasAnalysis.h"
44 #include "llvm/Analysis/AliasSetTracker.h"
45 #include "llvm/Analysis/Dominators.h"
46 #include "llvm/Analysis/ScalarEvolution.h"
47 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/ADT/Statistic.h"
53 #include <algorithm>
54 using namespace llvm;
55
56 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
57 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
58 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
59 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
60 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
61
62 static cl::opt<bool>
63 DisablePromotion("disable-licm-promotion", cl::Hidden,
64                  cl::desc("Disable memory promotion in LICM pass"));
65
66 namespace {
67   struct LICM : public LoopPass {
68     static char ID; // Pass identification, replacement for typeid
69     LICM() : LoopPass(&ID) {}
70
71     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
72
73     /// This transformation requires natural loop information & requires that
74     /// loop preheaders be inserted into the CFG...
75     ///
76     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77       AU.setPreservesCFG();
78       AU.addRequired<DominatorTree>();
79       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
80       AU.addRequired<LoopInfo>();
81       AU.addRequiredID(LoopSimplifyID);
82       AU.addRequired<AliasAnalysis>();
83       AU.addPreserved<ScalarEvolution>();
84       AU.addPreserved<DominanceFrontier>();
85       AU.addPreservedID(LoopSimplifyID);
86     }
87
88     bool doFinalization() {
89       // Free the values stored in the map
90       for (std::map<Loop *, AliasSetTracker *>::iterator
91              I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
92         delete I->second;
93
94       LoopToAliasMap.clear();
95       return false;
96     }
97
98   private:
99     // Various analyses that we use...
100     AliasAnalysis *AA;       // Current AliasAnalysis information
101     LoopInfo      *LI;       // Current LoopInfo
102     DominatorTree *DT;       // Dominator Tree for the current Loop...
103     DominanceFrontier *DF;   // Current Dominance Frontier
104
105     // State that is updated as we process loops
106     bool Changed;            // Set to true when we change anything.
107     BasicBlock *Preheader;   // The preheader block of the current loop...
108     Loop *CurLoop;           // The current loop we are working on...
109     AliasSetTracker *CurAST; // AliasSet information for the current loop...
110     std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
111
112     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
113     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
114
115     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
116     /// set.
117     void deleteAnalysisValue(Value *V, Loop *L);
118
119     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
120     /// dominated by the specified block, and that are in the current loop) in
121     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
122     /// visit uses before definitions, allowing us to sink a loop body in one
123     /// pass without iteration.
124     ///
125     void SinkRegion(DomTreeNode *N);
126
127     /// HoistRegion - Walk the specified region of the CFG (defined by all
128     /// blocks dominated by the specified block, and that are in the current
129     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
130     /// visit definitions before uses, allowing us to hoist a loop body in one
131     /// pass without iteration.
132     ///
133     void HoistRegion(DomTreeNode *N);
134
135     /// inSubLoop - Little predicate that returns true if the specified basic
136     /// block is in a subloop of the current one, not the current one itself.
137     ///
138     bool inSubLoop(BasicBlock *BB) {
139       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
140       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
141         if ((*I)->contains(BB))
142           return true;  // A subloop actually contains this block!
143       return false;
144     }
145
146     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
147     /// specified exit block of the loop is dominated by the specified block
148     /// that is in the body of the loop.  We use these constraints to
149     /// dramatically limit the amount of the dominator tree that needs to be
150     /// searched.
151     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
152                                            BasicBlock *BlockInLoop) const {
153       // If the block in the loop is the loop header, it must be dominated!
154       BasicBlock *LoopHeader = CurLoop->getHeader();
155       if (BlockInLoop == LoopHeader)
156         return true;
157
158       DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
159       DomTreeNode *IDom            = DT->getNode(ExitBlock);
160
161       // Because the exit block is not in the loop, we know we have to get _at
162       // least_ its immediate dominator.
163       IDom = IDom->getIDom();
164       
165       while (IDom && IDom != BlockInLoopNode) {
166         // If we have got to the header of the loop, then the instructions block
167         // did not dominate the exit node, so we can't hoist it.
168         if (IDom->getBlock() == LoopHeader)
169           return false;
170
171         // Get next Immediate Dominator.
172         IDom = IDom->getIDom();
173       };
174
175       return true;
176     }
177
178     /// sink - When an instruction is found to only be used outside of the loop,
179     /// this function moves it to the exit blocks and patches up SSA form as
180     /// needed.
181     ///
182     void sink(Instruction &I);
183
184     /// hoist - When an instruction is found to only use loop invariant operands
185     /// that is safe to hoist, this instruction is called to do the dirty work.
186     ///
187     void hoist(Instruction &I);
188
189     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
190     /// is not a trapping instruction or if it is a trapping instruction and is
191     /// guaranteed to execute.
192     ///
193     bool isSafeToExecuteUnconditionally(Instruction &I);
194
195     /// pointerInvalidatedByLoop - Return true if the body of this loop may
196     /// store into the memory location pointed to by V.
197     ///
198     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
199       // Check to see if any of the basic blocks in CurLoop invalidate *V.
200       return CurAST->getAliasSetForPointer(V, Size).isMod();
201     }
202
203     bool canSinkOrHoistInst(Instruction &I);
204     bool isLoopInvariantInst(Instruction &I);
205     bool isNotUsedInLoop(Instruction &I);
206
207     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
208     /// to scalars as we can.
209     ///
210     void PromoteValuesInLoop();
211
212     /// FindPromotableValuesInLoop - Check the current loop for stores to
213     /// definite pointers, which are not loaded and stored through may aliases.
214     /// If these are found, create an alloca for the value, add it to the
215     /// PromotedValues list, and keep track of the mapping from value to
216     /// alloca...
217     ///
218     void FindPromotableValuesInLoop(
219                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
220                                     std::map<Value*, AllocaInst*> &Val2AlMap);
221   };
222 }
223
224 char LICM::ID = 0;
225 INITIALIZE_PASS(LICM, "licm", "Loop Invariant Code Motion", false, false);
226
227 Pass *llvm::createLICMPass() { return new LICM(); }
228
229 /// Hoist expressions out of the specified loop. Note, alias info for inner
230 /// loop is not preserved so it is not a good idea to run LICM multiple 
231 /// times on one loop.
232 ///
233 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
234   Changed = false;
235
236   // Get our Loop and Alias Analysis information...
237   LI = &getAnalysis<LoopInfo>();
238   AA = &getAnalysis<AliasAnalysis>();
239   DF = &getAnalysis<DominanceFrontier>();
240   DT = &getAnalysis<DominatorTree>();
241
242   CurAST = new AliasSetTracker(*AA);
243   // Collect Alias info from subloops
244   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
245        LoopItr != LoopItrE; ++LoopItr) {
246     Loop *InnerL = *LoopItr;
247     AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
248     assert (InnerAST && "Where is my AST?");
249
250     // What if InnerLoop was modified by other passes ?
251     CurAST->add(*InnerAST);
252   }
253   
254   CurLoop = L;
255
256   // Get the preheader block to move instructions into...
257   Preheader = L->getLoopPreheader();
258
259   // Loop over the body of this loop, looking for calls, invokes, and stores.
260   // Because subloops have already been incorporated into AST, we skip blocks in
261   // subloops.
262   //
263   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
264        I != E; ++I) {
265     BasicBlock *BB = *I;
266     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops...
267       CurAST->add(*BB);                 // Incorporate the specified basic block
268   }
269
270   // We want to visit all of the instructions in this loop... that are not parts
271   // of our subloops (they have already had their invariants hoisted out of
272   // their loop, into this loop, so there is no need to process the BODIES of
273   // the subloops).
274   //
275   // Traverse the body of the loop in depth first order on the dominator tree so
276   // that we are guaranteed to see definitions before we see uses.  This allows
277   // us to sink instructions in one pass, without iteration.  After sinking
278   // instructions, we perform another pass to hoist them out of the loop.
279   //
280   if (L->hasDedicatedExits())
281     SinkRegion(DT->getNode(L->getHeader()));
282   if (Preheader)
283     HoistRegion(DT->getNode(L->getHeader()));
284
285   // Now that all loop invariants have been removed from the loop, promote any
286   // memory references to scalars that we can...
287   if (!DisablePromotion && Preheader && L->hasDedicatedExits())
288     PromoteValuesInLoop();
289
290   // Clear out loops state information for the next iteration
291   CurLoop = 0;
292   Preheader = 0;
293
294   LoopToAliasMap[L] = CurAST;
295   return Changed;
296 }
297
298 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
299 /// dominated by the specified block, and that are in the current loop) in
300 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
301 /// uses before definitions, allowing us to sink a loop body in one pass without
302 /// iteration.
303 ///
304 void LICM::SinkRegion(DomTreeNode *N) {
305   assert(N != 0 && "Null dominator tree node?");
306   BasicBlock *BB = N->getBlock();
307
308   // If this subregion is not in the top level loop at all, exit.
309   if (!CurLoop->contains(BB)) return;
310
311   // We are processing blocks in reverse dfo, so process children first...
312   const std::vector<DomTreeNode*> &Children = N->getChildren();
313   for (unsigned i = 0, e = Children.size(); i != e; ++i)
314     SinkRegion(Children[i]);
315
316   // Only need to process the contents of this block if it is not part of a
317   // subloop (which would already have been processed).
318   if (inSubLoop(BB)) return;
319
320   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
321     Instruction &I = *--II;
322
323     // Check to see if we can sink this instruction to the exit blocks
324     // of the loop.  We can do this if the all users of the instruction are
325     // outside of the loop.  In this case, it doesn't even matter if the
326     // operands of the instruction are loop invariant.
327     //
328     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
329       ++II;
330       sink(I);
331     }
332   }
333 }
334
335 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
336 /// dominated by the specified block, and that are in the current loop) in depth
337 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
338 /// before uses, allowing us to hoist a loop body in one pass without iteration.
339 ///
340 void LICM::HoistRegion(DomTreeNode *N) {
341   assert(N != 0 && "Null dominator tree node?");
342   BasicBlock *BB = N->getBlock();
343
344   // If this subregion is not in the top level loop at all, exit.
345   if (!CurLoop->contains(BB)) return;
346
347   // Only need to process the contents of this block if it is not part of a
348   // subloop (which would already have been processed).
349   if (!inSubLoop(BB))
350     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
351       Instruction &I = *II++;
352
353       // Try hoisting the instruction out to the preheader.  We can only do this
354       // if all of the operands of the instruction are loop invariant and if it
355       // is safe to hoist the instruction.
356       //
357       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
358           isSafeToExecuteUnconditionally(I))
359         hoist(I);
360       }
361
362   const std::vector<DomTreeNode*> &Children = N->getChildren();
363   for (unsigned i = 0, e = Children.size(); i != e; ++i)
364     HoistRegion(Children[i]);
365 }
366
367 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
368 /// instruction.
369 ///
370 bool LICM::canSinkOrHoistInst(Instruction &I) {
371   // Loads have extra constraints we have to verify before we can hoist them.
372   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
373     if (LI->isVolatile())
374       return false;        // Don't hoist volatile loads!
375
376     // Loads from constant memory are always safe to move, even if they end up
377     // in the same alias set as something that ends up being modified.
378     if (AA->pointsToConstantMemory(LI->getOperand(0)))
379       return true;
380     
381     // Don't hoist loads which have may-aliased stores in loop.
382     unsigned Size = 0;
383     if (LI->getType()->isSized())
384       Size = AA->getTypeStoreSize(LI->getType());
385     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
386   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
387     // Handle obvious cases efficiently.
388     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
389     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
390       return true;
391     else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
392       // If this call only reads from memory and there are no writes to memory
393       // in the loop, we can hoist or sink the call as appropriate.
394       bool FoundMod = false;
395       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
396            I != E; ++I) {
397         AliasSet &AS = *I;
398         if (!AS.isForwardingAliasSet() && AS.isMod()) {
399           FoundMod = true;
400           break;
401         }
402       }
403       if (!FoundMod) return true;
404     }
405
406     // FIXME: This should use mod/ref information to see if we can hoist or sink
407     // the call.
408
409     return false;
410   }
411
412   // Otherwise these instructions are hoistable/sinkable
413   return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
414          isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
415          isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
416          isa<ShuffleVectorInst>(I);
417 }
418
419 /// isNotUsedInLoop - Return true if the only users of this instruction are
420 /// outside of the loop.  If this is true, we can sink the instruction to the
421 /// exit blocks of the loop.
422 ///
423 bool LICM::isNotUsedInLoop(Instruction &I) {
424   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
425     Instruction *User = cast<Instruction>(*UI);
426     if (PHINode *PN = dyn_cast<PHINode>(User)) {
427       // PHI node uses occur in predecessor blocks!
428       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
429         if (PN->getIncomingValue(i) == &I)
430           if (CurLoop->contains(PN->getIncomingBlock(i)))
431             return false;
432     } else if (CurLoop->contains(User)) {
433       return false;
434     }
435   }
436   return true;
437 }
438
439
440 /// isLoopInvariantInst - Return true if all operands of this instruction are
441 /// loop invariant.  We also filter out non-hoistable instructions here just for
442 /// efficiency.
443 ///
444 bool LICM::isLoopInvariantInst(Instruction &I) {
445   // The instruction is loop invariant if all of its operands are loop-invariant
446   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
447     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
448       return false;
449
450   // If we got this far, the instruction is loop invariant!
451   return true;
452 }
453
454 /// sink - When an instruction is found to only be used outside of the loop,
455 /// this function moves it to the exit blocks and patches up SSA form as needed.
456 /// This method is guaranteed to remove the original instruction from its
457 /// position, and may either delete it or move it to outside of the loop.
458 ///
459 void LICM::sink(Instruction &I) {
460   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
461
462   SmallVector<BasicBlock*, 8> ExitBlocks;
463   CurLoop->getExitBlocks(ExitBlocks);
464
465   if (isa<LoadInst>(I)) ++NumMovedLoads;
466   else if (isa<CallInst>(I)) ++NumMovedCalls;
467   ++NumSunk;
468   Changed = true;
469
470   // The case where there is only a single exit node of this loop is common
471   // enough that we handle it as a special (more efficient) case.  It is more
472   // efficient to handle because there are no PHI nodes that need to be placed.
473   if (ExitBlocks.size() == 1) {
474     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
475       // Instruction is not used, just delete it.
476       CurAST->deleteValue(&I);
477       // If I has users in unreachable blocks, eliminate.
478       // If I is not void type then replaceAllUsesWith undef.
479       // This allows ValueHandlers and custom metadata to adjust itself.
480       if (!I.getType()->isVoidTy())
481         I.replaceAllUsesWith(UndefValue::get(I.getType()));
482       I.eraseFromParent();
483     } else {
484       // Move the instruction to the start of the exit block, after any PHI
485       // nodes in it.
486       I.removeFromParent();
487       BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
488       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
489     }
490   } else if (ExitBlocks.empty()) {
491     // The instruction is actually dead if there ARE NO exit blocks.
492     CurAST->deleteValue(&I);
493     // If I has users in unreachable blocks, eliminate.
494     // If I is not void type then replaceAllUsesWith undef.
495     // This allows ValueHandlers and custom metadata to adjust itself.
496     if (!I.getType()->isVoidTy())
497       I.replaceAllUsesWith(UndefValue::get(I.getType()));
498     I.eraseFromParent();
499   } else {
500     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
501     // do all of the hard work of inserting PHI nodes as necessary.  We convert
502     // the value into a stack object to get it to do this.
503
504     // Firstly, we create a stack object to hold the value...
505     AllocaInst *AI = 0;
506
507     if (!I.getType()->isVoidTy()) {
508       AI = new AllocaInst(I.getType(), 0, I.getName(),
509                           I.getParent()->getParent()->getEntryBlock().begin());
510       CurAST->add(AI);
511     }
512
513     // Secondly, insert load instructions for each use of the instruction
514     // outside of the loop.
515     while (!I.use_empty()) {
516       Instruction *U = cast<Instruction>(I.use_back());
517
518       // If the user is a PHI Node, we actually have to insert load instructions
519       // in all predecessor blocks, not in the PHI block itself!
520       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
521         // Only insert into each predecessor once, so that we don't have
522         // different incoming values from the same block!
523         std::map<BasicBlock*, Value*> InsertedBlocks;
524         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
525           if (UPN->getIncomingValue(i) == &I) {
526             BasicBlock *Pred = UPN->getIncomingBlock(i);
527             Value *&PredVal = InsertedBlocks[Pred];
528             if (!PredVal) {
529               // Insert a new load instruction right before the terminator in
530               // the predecessor block.
531               PredVal = new LoadInst(AI, "", Pred->getTerminator());
532               CurAST->add(cast<LoadInst>(PredVal));
533             }
534
535             UPN->setIncomingValue(i, PredVal);
536           }
537
538       } else {
539         LoadInst *L = new LoadInst(AI, "", U);
540         U->replaceUsesOfWith(&I, L);
541         CurAST->add(L);
542       }
543     }
544
545     // Thirdly, insert a copy of the instruction in each exit block of the loop
546     // that is dominated by the instruction, storing the result into the memory
547     // location.  Be careful not to insert the instruction into any particular
548     // basic block more than once.
549     std::set<BasicBlock*> InsertedBlocks;
550     BasicBlock *InstOrigBB = I.getParent();
551
552     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
553       BasicBlock *ExitBlock = ExitBlocks[i];
554
555       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
556         // If we haven't already processed this exit block, do so now.
557         if (InsertedBlocks.insert(ExitBlock).second) {
558           // Insert the code after the last PHI node...
559           BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
560
561           // If this is the first exit block processed, just move the original
562           // instruction, otherwise clone the original instruction and insert
563           // the copy.
564           Instruction *New;
565           if (InsertedBlocks.size() == 1) {
566             I.removeFromParent();
567             ExitBlock->getInstList().insert(InsertPt, &I);
568             New = &I;
569           } else {
570             New = I.clone();
571             CurAST->copyValue(&I, New);
572             if (!I.getName().empty())
573               New->setName(I.getName()+".le");
574             ExitBlock->getInstList().insert(InsertPt, New);
575           }
576
577           // Now that we have inserted the instruction, store it into the alloca
578           if (AI) new StoreInst(New, AI, InsertPt);
579         }
580       }
581     }
582
583     // If the instruction doesn't dominate any exit blocks, it must be dead.
584     if (InsertedBlocks.empty()) {
585       CurAST->deleteValue(&I);
586       I.eraseFromParent();
587     }
588
589     // Finally, promote the fine value to SSA form.
590     if (AI) {
591       std::vector<AllocaInst*> Allocas;
592       Allocas.push_back(AI);
593       PromoteMemToReg(Allocas, *DT, *DF, CurAST);
594     }
595   }
596 }
597
598 /// hoist - When an instruction is found to only use loop invariant operands
599 /// that is safe to hoist, this instruction is called to do the dirty work.
600 ///
601 void LICM::hoist(Instruction &I) {
602   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
603         << I << "\n");
604
605   // Remove the instruction from its current basic block... but don't delete the
606   // instruction.
607   I.removeFromParent();
608
609   // Insert the new node in Preheader, before the terminator.
610   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
611
612   if (isa<LoadInst>(I)) ++NumMovedLoads;
613   else if (isa<CallInst>(I)) ++NumMovedCalls;
614   ++NumHoisted;
615   Changed = true;
616 }
617
618 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
619 /// not a trapping instruction or if it is a trapping instruction and is
620 /// guaranteed to execute.
621 ///
622 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
623   // If it is not a trapping instruction, it is always safe to hoist.
624   if (Inst.isSafeToSpeculativelyExecute())
625     return true;
626
627   // Otherwise we have to check to make sure that the instruction dominates all
628   // of the exit blocks.  If it doesn't, then there is a path out of the loop
629   // which does not execute this instruction, so we can't hoist it.
630
631   // If the instruction is in the header block for the loop (which is very
632   // common), it is always guaranteed to dominate the exit blocks.  Since this
633   // is a common case, and can save some work, check it now.
634   if (Inst.getParent() == CurLoop->getHeader())
635     return true;
636
637   // Get the exit blocks for the current loop.
638   SmallVector<BasicBlock*, 8> ExitBlocks;
639   CurLoop->getExitBlocks(ExitBlocks);
640
641   // For each exit block, get the DT node and walk up the DT until the
642   // instruction's basic block is found or we exit the loop.
643   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
644     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
645       return false;
646
647   return true;
648 }
649
650
651 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
652 /// stores out of the loop and moving loads to before the loop.  We do this by
653 /// looping over the stores in the loop, looking for stores to Must pointers
654 /// which are loop invariant.  We promote these memory locations to use allocas
655 /// instead.  These allocas can easily be raised to register values by the
656 /// PromoteMem2Reg functionality.
657 ///
658 void LICM::PromoteValuesInLoop() {
659   // PromotedValues - List of values that are promoted out of the loop.  Each
660   // value has an alloca instruction for it, and a canonical version of the
661   // pointer.
662   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
663   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
664
665   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
666   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
667
668   Changed = true;
669   NumPromoted += PromotedValues.size();
670
671   std::vector<Value*> PointerValueNumbers;
672
673   // Emit a copy from the value into the alloca'd value in the loop preheader
674   TerminatorInst *LoopPredInst = Preheader->getTerminator();
675   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
676     Value *Ptr = PromotedValues[i].second;
677
678     // If we are promoting a pointer value, update alias information for the
679     // inserted load.
680     Value *LoadValue = 0;
681     if (cast<PointerType>(Ptr->getType())->getElementType()->isPointerTy()) {
682       // Locate a load or store through the pointer, and assign the same value
683       // to LI as we are loading or storing.  Since we know that the value is
684       // stored in this loop, this will always succeed.
685       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
686            UI != E; ++UI) {
687         User *U = *UI;
688         if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
689           LoadValue = LI;
690           break;
691         } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
692           if (SI->getOperand(1) == Ptr) {
693             LoadValue = SI->getOperand(0);
694             break;
695           }
696         }
697       }
698       assert(LoadValue && "No store through the pointer found!");
699       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
700     }
701
702     // Load from the memory we are promoting.
703     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
704
705     if (LoadValue) CurAST->copyValue(LoadValue, LI);
706
707     // Store into the temporary alloca.
708     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
709   }
710
711   // Scan the basic blocks in the loop, replacing uses of our pointers with
712   // uses of the allocas in question.
713   //
714   for (Loop::block_iterator I = CurLoop->block_begin(),
715          E = CurLoop->block_end(); I != E; ++I) {
716     BasicBlock *BB = *I;
717     // Rewrite all loads and stores in the block of the pointer...
718     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
719       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
720         std::map<Value*, AllocaInst*>::iterator
721           I = ValueToAllocaMap.find(L->getOperand(0));
722         if (I != ValueToAllocaMap.end())
723           L->setOperand(0, I->second);    // Rewrite load instruction...
724       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
725         std::map<Value*, AllocaInst*>::iterator
726           I = ValueToAllocaMap.find(S->getOperand(1));
727         if (I != ValueToAllocaMap.end())
728           S->setOperand(1, I->second);    // Rewrite store instruction...
729       }
730     }
731   }
732
733   // Now that the body of the loop uses the allocas instead of the original
734   // memory locations, insert code to copy the alloca value back into the
735   // original memory location on all exits from the loop.  Note that we only
736   // want to insert one copy of the code in each exit block, though the loop may
737   // exit to the same block more than once.
738   //
739   SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
740
741   SmallVector<BasicBlock*, 8> ExitBlocks;
742   CurLoop->getExitBlocks(ExitBlocks);
743   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
744     if (!ProcessedBlocks.insert(ExitBlocks[i]))
745       continue;
746   
747     // Copy all of the allocas into their memory locations.
748     BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
749     Instruction *InsertPos = BI;
750     unsigned PVN = 0;
751     for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
752       // Load from the alloca.
753       LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
754
755       // If this is a pointer type, update alias info appropriately.
756       if (LI->getType()->isPointerTy())
757         CurAST->copyValue(PointerValueNumbers[PVN++], LI);
758
759       // Store into the memory we promoted.
760       new StoreInst(LI, PromotedValues[i].second, InsertPos);
761     }
762   }
763
764   // Now that we have done the deed, use the mem2reg functionality to promote
765   // all of the new allocas we just created into real SSA registers.
766   //
767   std::vector<AllocaInst*> PromotedAllocas;
768   PromotedAllocas.reserve(PromotedValues.size());
769   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
770     PromotedAllocas.push_back(PromotedValues[i].first);
771   PromoteMemToReg(PromotedAllocas, *DT, *DF, CurAST);
772 }
773
774 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
775 /// pointers, which are not loaded and stored through may aliases and are safe
776 /// for promotion.  If these are found, create an alloca for the value, add it 
777 /// to the PromotedValues list, and keep track of the mapping from value to 
778 /// alloca. 
779 void LICM::FindPromotableValuesInLoop(
780                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
781                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
782   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
783
784   // Loop over all of the alias sets in the tracker object.
785   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
786        I != E; ++I) {
787     AliasSet &AS = *I;
788     // We can promote this alias set if it has a store, if it is a "Must" alias
789     // set, if the pointer is loop invariant, and if we are not eliminating any
790     // volatile loads or stores.
791     if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
792         AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
793       continue;
794     
795     assert(!AS.empty() &&
796            "Must alias set should have at least one pointer element in it!");
797     Value *V = AS.begin()->getValue();
798
799     // Check that all of the pointers in the alias set have the same type.  We
800     // cannot (yet) promote a memory location that is loaded and stored in
801     // different sizes.
802     {
803       bool PointerOk = true;
804       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
805         if (V->getType() != I->getValue()->getType()) {
806           PointerOk = false;
807           break;
808         }
809       if (!PointerOk)
810         continue;
811     }
812
813     // It isn't safe to promote a load/store from the loop if the load/store is
814     // conditional.  For example, turning:
815     //
816     //    for () { if (c) *P += 1; }
817     //
818     // into:
819     //
820     //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
821     //
822     // is not safe, because *P may only be valid to access if 'c' is true.
823     // 
824     // It is safe to promote P if all uses are direct load/stores and if at
825     // least one is guaranteed to be executed.
826     bool GuaranteedToExecute = false;
827     bool InvalidInst = false;
828     for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
829          UI != UE; ++UI) {
830       // Ignore instructions not in this loop.
831       Instruction *Use = dyn_cast<Instruction>(*UI);
832       if (!Use || !CurLoop->contains(Use))
833         continue;
834
835       if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
836         InvalidInst = true;
837         break;
838       }
839       
840       if (!GuaranteedToExecute)
841         GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
842     }
843
844     // If there is an non-load/store instruction in the loop, we can't promote
845     // it.  If there isn't a guaranteed-to-execute instruction, we can't
846     // promote.
847     if (InvalidInst || !GuaranteedToExecute)
848       continue;
849     
850     const Type *Ty = cast<PointerType>(V->getType())->getElementType();
851     AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
852     PromotedValues.push_back(std::make_pair(AI, V));
853
854     // Update the AST and alias analysis.
855     CurAST->copyValue(V, AI);
856
857     for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
858       ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI));
859
860     DEBUG(dbgs() << "LICM: Promoting value: " << *V << "\n");
861   }
862 }
863
864 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
865 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
866   AliasSetTracker *AST = LoopToAliasMap[L];
867   if (!AST)
868     return;
869
870   AST->copyValue(From, To);
871 }
872
873 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
874 /// set.
875 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
876   AliasSetTracker *AST = LoopToAliasMap[L];
877   if (!AST)
878     return;
879
880   AST->deleteValue(V);
881 }