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