Disable most IR-level transform passes on functions marked 'optnone'.
[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 SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32
33 #define DEBUG_TYPE "licm"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Analysis/ConstantFolding.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Dominators.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/Support/CFG.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetLibraryInfo.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59 #include <algorithm>
60 using namespace llvm;
61
62 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
63 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
64 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
65 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
66 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
67
68 static cl::opt<bool>
69 DisablePromotion("disable-licm-promotion", cl::Hidden,
70                  cl::desc("Disable memory promotion in LICM pass"));
71
72 namespace {
73   struct LICM : public LoopPass {
74     static char ID; // Pass identification, replacement for typeid
75     LICM() : LoopPass(ID) {
76       initializeLICMPass(*PassRegistry::getPassRegistry());
77     }
78
79     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
80
81     /// This transformation requires natural loop information & requires that
82     /// loop preheaders be inserted into the CFG...
83     ///
84     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.setPreservesCFG();
86       AU.addRequired<DominatorTreeWrapperPass>();
87       AU.addRequired<LoopInfo>();
88       AU.addRequiredID(LoopSimplifyID);
89       AU.addPreservedID(LoopSimplifyID);
90       AU.addRequiredID(LCSSAID);
91       AU.addPreservedID(LCSSAID);
92       AU.addRequired<AliasAnalysis>();
93       AU.addPreserved<AliasAnalysis>();
94       AU.addPreserved<ScalarEvolution>();
95       AU.addRequired<TargetLibraryInfo>();
96     }
97
98     using llvm::Pass::doFinalization;
99
100     bool doFinalization() {
101       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
102       return false;
103     }
104
105   private:
106     AliasAnalysis *AA;       // Current AliasAnalysis information
107     LoopInfo      *LI;       // Current LoopInfo
108     DominatorTree *DT;       // Dominator Tree for the current Loop.
109
110     DataLayout *TD;          // DataLayout for constant folding.
111     TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
112
113     // State that is updated as we process loops.
114     bool Changed;            // Set to true when we change anything.
115     BasicBlock *Preheader;   // The preheader block of the current loop...
116     Loop *CurLoop;           // The current loop we are working on...
117     AliasSetTracker *CurAST; // AliasSet information for the current loop...
118     bool MayThrow;           // The current loop contains an instruction which
119                              // may throw, thus preventing code motion of
120                              // instructions with side effects.
121     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
122
123     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
124     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
125
126     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
127     /// set.
128     void deleteAnalysisValue(Value *V, Loop *L);
129
130     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
131     /// dominated by the specified block, and that are in the current loop) in
132     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
133     /// visit uses before definitions, allowing us to sink a loop body in one
134     /// pass without iteration.
135     ///
136     void SinkRegion(DomTreeNode *N);
137
138     /// HoistRegion - Walk the specified region of the CFG (defined by all
139     /// blocks dominated by the specified block, and that are in the current
140     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
141     /// visit definitions before uses, allowing us to hoist a loop body in one
142     /// pass without iteration.
143     ///
144     void HoistRegion(DomTreeNode *N);
145
146     /// inSubLoop - Little predicate that returns true if the specified basic
147     /// block is in a subloop of the current one, not the current one itself.
148     ///
149     bool inSubLoop(BasicBlock *BB) {
150       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
151       return LI->getLoopFor(BB) != CurLoop;
152     }
153
154     /// sink - When an instruction is found to only be used outside of the loop,
155     /// this function moves it to the exit blocks and patches up SSA form as
156     /// needed.
157     ///
158     void sink(Instruction &I);
159
160     /// hoist - When an instruction is found to only use loop invariant operands
161     /// that is safe to hoist, this instruction is called to do the dirty work.
162     ///
163     void hoist(Instruction &I);
164
165     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
166     /// is not a trapping instruction or if it is a trapping instruction and is
167     /// guaranteed to execute.
168     ///
169     bool isSafeToExecuteUnconditionally(Instruction &I);
170
171     /// isGuaranteedToExecute - Check that the instruction is guaranteed to
172     /// execute.
173     ///
174     bool isGuaranteedToExecute(Instruction &I);
175
176     /// pointerInvalidatedByLoop - Return true if the body of this loop may
177     /// store into the memory location pointed to by V.
178     ///
179     bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
180                                   const MDNode *TBAAInfo) {
181       // Check to see if any of the basic blocks in CurLoop invalidate *V.
182       return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
183     }
184
185     bool canSinkOrHoistInst(Instruction &I);
186     bool isNotUsedInLoop(Instruction &I);
187
188     void PromoteAliasSet(AliasSet &AS,
189                          SmallVectorImpl<BasicBlock*> &ExitBlocks,
190                          SmallVectorImpl<Instruction*> &InsertPts);
191   };
192 }
193
194 char LICM::ID = 0;
195 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
196 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
197 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
198 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
199 INITIALIZE_PASS_DEPENDENCY(LCSSA)
200 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
201 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
202 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
203 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
204
205 Pass *llvm::createLICMPass() { return new LICM(); }
206
207 /// Hoist expressions out of the specified loop. Note, alias info for inner
208 /// loop is not preserved so it is not a good idea to run LICM multiple
209 /// times on one loop.
210 ///
211 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
212   if (skipOptnoneFunction(L))
213     return false;
214
215   Changed = false;
216
217   // Get our Loop and Alias Analysis information...
218   LI = &getAnalysis<LoopInfo>();
219   AA = &getAnalysis<AliasAnalysis>();
220   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
221
222   TD = getAnalysisIfAvailable<DataLayout>();
223   TLI = &getAnalysis<TargetLibraryInfo>();
224
225   CurAST = new AliasSetTracker(*AA);
226   // Collect Alias info from subloops.
227   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
228        LoopItr != LoopItrE; ++LoopItr) {
229     Loop *InnerL = *LoopItr;
230     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
231     assert(InnerAST && "Where is my AST?");
232
233     // What if InnerLoop was modified by other passes ?
234     CurAST->add(*InnerAST);
235
236     // Once we've incorporated the inner loop's AST into ours, we don't need the
237     // subloop's anymore.
238     delete InnerAST;
239     LoopToAliasSetMap.erase(InnerL);
240   }
241
242   CurLoop = L;
243
244   // Get the preheader block to move instructions into...
245   Preheader = L->getLoopPreheader();
246
247   // Loop over the body of this loop, looking for calls, invokes, and stores.
248   // Because subloops have already been incorporated into AST, we skip blocks in
249   // subloops.
250   //
251   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
252        I != E; ++I) {
253     BasicBlock *BB = *I;
254     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
255       CurAST->add(*BB);                 // Incorporate the specified basic block
256   }
257
258   MayThrow = false;
259   // TODO: We've already searched for instructions which may throw in subloops.
260   // We may want to reuse this information.
261   for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end();
262        (BB != BBE) && !MayThrow ; ++BB)
263     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
264          (I != E) && !MayThrow; ++I)
265       MayThrow |= I->mayThrow();
266
267   // We want to visit all of the instructions in this loop... that are not parts
268   // of our subloops (they have already had their invariants hoisted out of
269   // their loop, into this loop, so there is no need to process the BODIES of
270   // the subloops).
271   //
272   // Traverse the body of the loop in depth first order on the dominator tree so
273   // that we are guaranteed to see definitions before we see uses.  This allows
274   // us to sink instructions in one pass, without iteration.  After sinking
275   // instructions, we perform another pass to hoist them out of the loop.
276   //
277   if (L->hasDedicatedExits())
278     SinkRegion(DT->getNode(L->getHeader()));
279   if (Preheader)
280     HoistRegion(DT->getNode(L->getHeader()));
281
282   // Now that all loop invariants have been removed from the loop, promote any
283   // memory references to scalars that we can.
284   if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
285     SmallVector<BasicBlock *, 8> ExitBlocks;
286     SmallVector<Instruction *, 8> InsertPts;
287
288     // Loop over all of the alias sets in the tracker object.
289     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
290          I != E; ++I)
291       PromoteAliasSet(*I, ExitBlocks, InsertPts);
292
293     // Once we have promoted values across the loop body we have to recursively
294     // reform LCSSA as any nested loop may now have values defined within the
295     // loop used in the outer loop.
296     // FIXME: This is really heavy handed. It would be a bit better to use an
297     // SSAUpdater strategy during promotion that was LCSSA aware and reformed
298     // it as it went.
299     if (Changed)
300       formLCSSARecursively(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
301
302   } else if (Changed) {
303     // If we have successfully changed the loop but not used SSAUpdater to
304     // re-write instructions throughout the loop body, re-form LCSSA just for
305     // this loop.
306     formLCSSA(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
307   }
308
309   // Regardless of how we changed the loop, reform LCSSA on its parent as
310   // hoisting or sinking could have disrupted it.
311   if (Changed)
312     if (Loop *ParentL = L->getParentLoop())
313       formLCSSA(*ParentL, *DT, getAnalysisIfAvailable<ScalarEvolution>());
314
315   // Clear out loops state information for the next iteration
316   CurLoop = 0;
317   Preheader = 0;
318
319   // If this loop is nested inside of another one, save the alias information
320   // for when we process the outer loop.
321   if (L->getParentLoop())
322     LoopToAliasSetMap[L] = CurAST;
323   else
324     delete CurAST;
325   return Changed;
326 }
327
328 /// SinkRegion - 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
330 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
331 /// uses before definitions, allowing us to sink a loop body in one pass without
332 /// iteration.
333 ///
334 void LICM::SinkRegion(DomTreeNode *N) {
335   assert(N != 0 && "Null dominator tree node?");
336   BasicBlock *BB = N->getBlock();
337
338   // If this subregion is not in the top level loop at all, exit.
339   if (!CurLoop->contains(BB)) return;
340
341   // We are processing blocks in reverse dfo, so process children first.
342   const std::vector<DomTreeNode*> &Children = N->getChildren();
343   for (unsigned i = 0, e = Children.size(); i != e; ++i)
344     SinkRegion(Children[i]);
345
346   // Only need to process the contents of this block if it is not part of a
347   // subloop (which would already have been processed).
348   if (inSubLoop(BB)) return;
349
350   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
351     Instruction &I = *--II;
352
353     // If the instruction is dead, we would try to sink it because it isn't used
354     // in the loop, instead, just delete it.
355     if (isInstructionTriviallyDead(&I, TLI)) {
356       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
357       ++II;
358       CurAST->deleteValue(&I);
359       I.eraseFromParent();
360       Changed = true;
361       continue;
362     }
363
364     // Check to see if we can sink this instruction to the exit blocks
365     // of the loop.  We can do this if the all users of the instruction are
366     // outside of the loop.  In this case, it doesn't even matter if the
367     // operands of the instruction are loop invariant.
368     //
369     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
370       ++II;
371       sink(I);
372     }
373   }
374 }
375
376 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
377 /// dominated by the specified block, and that are in the current loop) in depth
378 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
379 /// before uses, allowing us to hoist a loop body in one pass without iteration.
380 ///
381 void LICM::HoistRegion(DomTreeNode *N) {
382   assert(N != 0 && "Null dominator tree node?");
383   BasicBlock *BB = N->getBlock();
384
385   // If this subregion is not in the top level loop at all, exit.
386   if (!CurLoop->contains(BB)) return;
387
388   // Only need to process the contents of this block if it is not part of a
389   // subloop (which would already have been processed).
390   if (!inSubLoop(BB))
391     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
392       Instruction &I = *II++;
393
394       // Try constant folding this instruction.  If all the operands are
395       // constants, it is technically hoistable, but it would be better to just
396       // fold it.
397       if (Constant *C = ConstantFoldInstruction(&I, TD, TLI)) {
398         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
399         CurAST->copyValue(&I, C);
400         CurAST->deleteValue(&I);
401         I.replaceAllUsesWith(C);
402         I.eraseFromParent();
403         continue;
404       }
405
406       // Try hoisting the instruction out to the preheader.  We can only do this
407       // if all of the operands of the instruction are loop invariant and if it
408       // is safe to hoist the instruction.
409       //
410       if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
411           isSafeToExecuteUnconditionally(I))
412         hoist(I);
413     }
414
415   const std::vector<DomTreeNode*> &Children = N->getChildren();
416   for (unsigned i = 0, e = Children.size(); i != e; ++i)
417     HoistRegion(Children[i]);
418 }
419
420 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
421 /// instruction.
422 ///
423 bool LICM::canSinkOrHoistInst(Instruction &I) {
424   // Loads have extra constraints we have to verify before we can hoist them.
425   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
426     if (!LI->isUnordered())
427       return false;        // Don't hoist volatile/atomic loads!
428
429     // Loads from constant memory are always safe to move, even if they end up
430     // in the same alias set as something that ends up being modified.
431     if (AA->pointsToConstantMemory(LI->getOperand(0)))
432       return true;
433     if (LI->getMetadata("invariant.load"))
434       return true;
435
436     // Don't hoist loads which have may-aliased stores in loop.
437     uint64_t Size = 0;
438     if (LI->getType()->isSized())
439       Size = AA->getTypeStoreSize(LI->getType());
440     return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
441                                      LI->getMetadata(LLVMContext::MD_tbaa));
442   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
443     // Don't sink or hoist dbg info; it's legal, but not useful.
444     if (isa<DbgInfoIntrinsic>(I))
445       return false;
446
447     // Handle simple cases by querying alias analysis.
448     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
449     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
450       return true;
451     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
452       // If this call only reads from memory and there are no writes to memory
453       // in the loop, we can hoist or sink the call as appropriate.
454       bool FoundMod = false;
455       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
456            I != E; ++I) {
457         AliasSet &AS = *I;
458         if (!AS.isForwardingAliasSet() && AS.isMod()) {
459           FoundMod = true;
460           break;
461         }
462       }
463       if (!FoundMod) return true;
464     }
465
466     // FIXME: This should use mod/ref information to see if we can hoist or
467     // sink the call.
468
469     return false;
470   }
471
472   // Only these instructions are hoistable/sinkable.
473   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
474       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
475       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
476       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
477       !isa<InsertValueInst>(I))
478     return false;
479
480   return isSafeToExecuteUnconditionally(I);
481 }
482
483 /// \brief Returns true if a PHINode is a trivially replaceable with an
484 /// Instruction.
485 ///
486 /// This is true when all incoming values are that instruction. This pattern
487 /// occurs most often with LCSSA PHI nodes.
488 static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
489   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
490     if (PN.getIncomingValue(i) != &I)
491       return false;
492
493   return true;
494 }
495
496 /// isNotUsedInLoop - Return true if the only users of this instruction are
497 /// outside of the loop.  If this is true, we can sink the instruction to the
498 /// exit blocks of the loop.
499 ///
500 bool LICM::isNotUsedInLoop(Instruction &I) {
501   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
502     Instruction *User = cast<Instruction>(*UI);
503     if (PHINode *PN = dyn_cast<PHINode>(User)) {
504       // A PHI node where all of the incoming values are this instruction are
505       // special -- they can just be RAUW'ed with the instruction and thus
506       // don't require a use in the predecessor. This is a particular important
507       // special case because it is the pattern found in LCSSA form.
508       if (isTriviallyReplacablePHI(*PN, I)) {
509         if (CurLoop->contains(PN))
510           return false;
511         else
512           continue;
513       }
514
515       // Otherwise, PHI node uses occur in predecessor blocks if the incoming
516       // values. Check for such a use being inside the loop.
517       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
518         if (PN->getIncomingValue(i) == &I)
519           if (CurLoop->contains(PN->getIncomingBlock(i)))
520             return false;
521
522       continue;
523     }
524
525     if (CurLoop->contains(User))
526       return false;
527   }
528   return true;
529 }
530
531 static BasicBlock::iterator
532 replaceTrivialPHIsAndGetInsertionPt(BasicBlock &BB, Instruction &I) {
533   BasicBlock::iterator II = BB.begin();
534   while (PHINode *PN = dyn_cast<PHINode>(II)) {
535     ++II;
536     if (isTriviallyReplacablePHI(*PN, I)) {
537       PN->replaceAllUsesWith(&I);
538       PN->eraseFromParent();
539     }
540   }
541   if (isa<LandingPadInst>(II))
542     ++II;
543
544   return II;
545 }
546
547 /// sink - When an instruction is found to only be used outside of the loop,
548 /// this function moves it to the exit blocks and patches up SSA form as needed.
549 /// This method is guaranteed to remove the original instruction from its
550 /// position, and may either delete it or move it to outside of the loop.
551 ///
552 void LICM::sink(Instruction &I) {
553   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
554
555   SmallVector<BasicBlock*, 8> ExitBlocks;
556   CurLoop->getUniqueExitBlocks(ExitBlocks);
557
558   if (isa<LoadInst>(I)) ++NumMovedLoads;
559   else if (isa<CallInst>(I)) ++NumMovedCalls;
560   ++NumSunk;
561   Changed = true;
562
563   // The case where there is only a single exit node of this loop is common
564   // enough that we handle it as a special (more efficient) case.  It is more
565   // efficient to handle because there are no PHI nodes that need to be placed.
566   if (ExitBlocks.size() == 1) {
567     if (!DT->dominates(I.getParent(), ExitBlocks[0])) {
568       // Instruction is not used, just delete it.
569       CurAST->deleteValue(&I);
570       // If I has users in unreachable blocks, eliminate.
571       // If I is not void type then replaceAllUsesWith undef.
572       // This allows ValueHandlers and custom metadata to adjust itself.
573       if (!I.use_empty())
574         I.replaceAllUsesWith(UndefValue::get(I.getType()));
575       I.eraseFromParent();
576     } else {
577       // Look for any LCSSA PHI nodes for this instruction in the exit blocks
578       // and replace them.
579       BasicBlock::iterator II =
580           replaceTrivialPHIsAndGetInsertionPt(*ExitBlocks[0], I);
581
582       // Move the instruction to the start of the exit block, after any PHI
583       // nodes in it.
584       I.moveBefore(II);
585
586       // This instruction is no longer in the AST for the current loop, because
587       // we just sunk it out of the loop.  If we just sunk it into an outer
588       // loop, we will rediscover the operation when we process it.
589       CurAST->deleteValue(&I);
590     }
591     return;
592   }
593
594   if (ExitBlocks.empty()) {
595     // The instruction is actually dead if there ARE NO exit blocks.
596     CurAST->deleteValue(&I);
597     // If I has users in unreachable blocks, eliminate.
598     // If I is not void type then replaceAllUsesWith undef.
599     // This allows ValueHandlers and custom metadata to adjust itself.
600     if (!I.use_empty())
601       I.replaceAllUsesWith(UndefValue::get(I.getType()));
602     I.eraseFromParent();
603     return;
604   }
605
606   // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
607   // hard work of inserting PHI nodes as necessary.
608   SmallVector<PHINode*, 8> NewPHIs;
609   SSAUpdater SSA(&NewPHIs);
610
611   if (!I.use_empty())
612     SSA.Initialize(I.getType(), I.getName());
613
614   // Insert a copy of the instruction in each exit block of the loop that is
615   // dominated by the instruction.  Each exit block is known to only be in the
616   // ExitBlocks list once.
617   BasicBlock *InstOrigBB = I.getParent();
618   unsigned NumInserted = 0;
619
620   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
621     BasicBlock *ExitBlock = ExitBlocks[i];
622
623     if (!DT->dominates(InstOrigBB, ExitBlock))
624       continue;
625
626     // Look for any LCSSA PHI nodes for this instruction in the exit blocks
627     // and replace them. Then get the insertion point after the last PHI.
628     BasicBlock::iterator InsertPt =
629       replaceTrivialPHIsAndGetInsertionPt(*ExitBlock, I);
630
631     // If this is the first exit block processed, just move the original
632     // instruction, otherwise clone the original instruction and insert
633     // the copy.
634     Instruction *New;
635     if (NumInserted++ == 0) {
636       I.moveBefore(InsertPt);
637       New = &I;
638     } else {
639       New = I.clone();
640       if (!I.getName().empty())
641         New->setName(I.getName()+".le");
642       ExitBlock->getInstList().insert(InsertPt, New);
643     }
644
645     // Now that we have inserted the instruction, inform SSAUpdater.
646     if (!I.use_empty())
647       SSA.AddAvailableValue(ExitBlock, New);
648   }
649
650   // If the instruction doesn't dominate any exit blocks, it must be dead.
651   if (NumInserted == 0) {
652     CurAST->deleteValue(&I);
653     if (!I.use_empty())
654       I.replaceAllUsesWith(UndefValue::get(I.getType()));
655     I.eraseFromParent();
656     return;
657   }
658
659   // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
660   for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
661     // Grab the use before incrementing the iterator.
662     Use &U = UI.getUse();
663     // Increment the iterator before removing the use from the list.
664     ++UI;
665     SSA.RewriteUseAfterInsertions(U);
666   }
667
668   // Update CurAST for NewPHIs if I had pointer type.
669   if (I.getType()->isPointerTy())
670     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
671       CurAST->copyValue(&I, NewPHIs[i]);
672
673   // Finally, remove the instruction from CurAST.  It is no longer in the loop.
674   CurAST->deleteValue(&I);
675 }
676
677 /// hoist - When an instruction is found to only use loop invariant operands
678 /// that is safe to hoist, this instruction is called to do the dirty work.
679 ///
680 void LICM::hoist(Instruction &I) {
681   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
682         << I << "\n");
683
684   // Move the new node to the Preheader, before its terminator.
685   I.moveBefore(Preheader->getTerminator());
686
687   if (isa<LoadInst>(I)) ++NumMovedLoads;
688   else if (isa<CallInst>(I)) ++NumMovedCalls;
689   ++NumHoisted;
690   Changed = true;
691 }
692
693 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
694 /// not a trapping instruction or if it is a trapping instruction and is
695 /// guaranteed to execute.
696 ///
697 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
698   // If it is not a trapping instruction, it is always safe to hoist.
699   if (isSafeToSpeculativelyExecute(&Inst))
700     return true;
701
702   return isGuaranteedToExecute(Inst);
703 }
704
705 bool LICM::isGuaranteedToExecute(Instruction &Inst) {
706
707   // Somewhere in this loop there is an instruction which may throw and make us
708   // exit the loop.
709   if (MayThrow)
710     return false;
711
712   // Otherwise we have to check to make sure that the instruction dominates all
713   // of the exit blocks.  If it doesn't, then there is a path out of the loop
714   // which does not execute this instruction, so we can't hoist it.
715
716   // If the instruction is in the header block for the loop (which is very
717   // common), it is always guaranteed to dominate the exit blocks.  Since this
718   // is a common case, and can save some work, check it now.
719   if (Inst.getParent() == CurLoop->getHeader())
720     return true;
721
722   // Get the exit blocks for the current loop.
723   SmallVector<BasicBlock*, 8> ExitBlocks;
724   CurLoop->getExitBlocks(ExitBlocks);
725
726   // Verify that the block dominates each of the exit blocks of the loop.
727   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
728     if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
729       return false;
730
731   // As a degenerate case, if the loop is statically infinite then we haven't
732   // proven anything since there are no exit blocks.
733   if (ExitBlocks.empty())
734     return false;
735
736   return true;
737 }
738
739 namespace {
740   class LoopPromoter : public LoadAndStorePromoter {
741     Value *SomePtr;  // Designated pointer to store to.
742     SmallPtrSet<Value*, 4> &PointerMustAliases;
743     SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
744     SmallVectorImpl<Instruction*> &LoopInsertPts;
745     AliasSetTracker &AST;
746     DebugLoc DL;
747     int Alignment;
748     MDNode *TBAATag;
749   public:
750     LoopPromoter(Value *SP,
751                  const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
752                  SmallPtrSet<Value*, 4> &PMA,
753                  SmallVectorImpl<BasicBlock*> &LEB,
754                  SmallVectorImpl<Instruction*> &LIP,
755                  AliasSetTracker &ast, DebugLoc dl, int alignment,
756                  MDNode *TBAATag)
757       : LoadAndStorePromoter(Insts, S), SomePtr(SP),
758         PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP),
759         AST(ast), DL(dl), Alignment(alignment), TBAATag(TBAATag) {}
760
761     virtual bool isInstInList(Instruction *I,
762                               const SmallVectorImpl<Instruction*> &) const {
763       Value *Ptr;
764       if (LoadInst *LI = dyn_cast<LoadInst>(I))
765         Ptr = LI->getOperand(0);
766       else
767         Ptr = cast<StoreInst>(I)->getPointerOperand();
768       return PointerMustAliases.count(Ptr);
769     }
770
771     virtual void doExtraRewritesBeforeFinalDeletion() const {
772       // Insert stores after in the loop exit blocks.  Each exit block gets a
773       // store of the live-out values that feed them.  Since we've already told
774       // the SSA updater about the defs in the loop and the preheader
775       // definition, it is all set and we can start using it.
776       for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
777         BasicBlock *ExitBlock = LoopExitBlocks[i];
778         Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
779         Instruction *InsertPos = LoopInsertPts[i];
780         StoreInst *NewSI = new StoreInst(LiveInValue, SomePtr, InsertPos);
781         NewSI->setAlignment(Alignment);
782         NewSI->setDebugLoc(DL);
783         if (TBAATag) NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
784       }
785     }
786
787     virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {
788       // Update alias analysis.
789       AST.copyValue(LI, V);
790     }
791     virtual void instructionDeleted(Instruction *I) const {
792       AST.deleteValue(I);
793     }
794   };
795 } // end anon namespace
796
797 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
798 /// stores out of the loop and moving loads to before the loop.  We do this by
799 /// looping over the stores in the loop, looking for stores to Must pointers
800 /// which are loop invariant.
801 ///
802 void LICM::PromoteAliasSet(AliasSet &AS,
803                            SmallVectorImpl<BasicBlock*> &ExitBlocks,
804                            SmallVectorImpl<Instruction*> &InsertPts) {
805   // We can promote this alias set if it has a store, if it is a "Must" alias
806   // set, if the pointer is loop invariant, and if we are not eliminating any
807   // volatile loads or stores.
808   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
809       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
810     return;
811
812   assert(!AS.empty() &&
813          "Must alias set should have at least one pointer element in it!");
814   Value *SomePtr = AS.begin()->getValue();
815
816   // It isn't safe to promote a load/store from the loop if the load/store is
817   // conditional.  For example, turning:
818   //
819   //    for () { if (c) *P += 1; }
820   //
821   // into:
822   //
823   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
824   //
825   // is not safe, because *P may only be valid to access if 'c' is true.
826   //
827   // It is safe to promote P if all uses are direct load/stores and if at
828   // least one is guaranteed to be executed.
829   bool GuaranteedToExecute = false;
830
831   SmallVector<Instruction*, 64> LoopUses;
832   SmallPtrSet<Value*, 4> PointerMustAliases;
833
834   // We start with an alignment of one and try to find instructions that allow
835   // us to prove better alignment.
836   unsigned Alignment = 1;
837   MDNode *TBAATag = 0;
838
839   // Check that all of the pointers in the alias set have the same type.  We
840   // cannot (yet) promote a memory location that is loaded and stored in
841   // different sizes.  While we are at it, collect alignment and TBAA info.
842   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
843     Value *ASIV = ASI->getValue();
844     PointerMustAliases.insert(ASIV);
845
846     // Check that all of the pointers in the alias set have the same type.  We
847     // cannot (yet) promote a memory location that is loaded and stored in
848     // different sizes.
849     if (SomePtr->getType() != ASIV->getType())
850       return;
851
852     for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
853          UI != UE; ++UI) {
854       // Ignore instructions that are outside the loop.
855       Instruction *Use = dyn_cast<Instruction>(*UI);
856       if (!Use || !CurLoop->contains(Use))
857         continue;
858
859       // If there is an non-load/store instruction in the loop, we can't promote
860       // it.
861       if (LoadInst *load = dyn_cast<LoadInst>(Use)) {
862         assert(!load->isVolatile() && "AST broken");
863         if (!load->isSimple())
864           return;
865       } else if (StoreInst *store = dyn_cast<StoreInst>(Use)) {
866         // Stores *of* the pointer are not interesting, only stores *to* the
867         // pointer.
868         if (Use->getOperand(1) != ASIV)
869           continue;
870         assert(!store->isVolatile() && "AST broken");
871         if (!store->isSimple())
872           return;
873
874         // Note that we only check GuaranteedToExecute inside the store case
875         // so that we do not introduce stores where they did not exist before
876         // (which would break the LLVM concurrency model).
877
878         // If the alignment of this instruction allows us to specify a more
879         // restrictive (and performant) alignment and if we are sure this
880         // instruction will be executed, update the alignment.
881         // Larger is better, with the exception of 0 being the best alignment.
882         unsigned InstAlignment = store->getAlignment();
883         if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
884           if (isGuaranteedToExecute(*Use)) {
885             GuaranteedToExecute = true;
886             Alignment = InstAlignment;
887           }
888
889         if (!GuaranteedToExecute)
890           GuaranteedToExecute = isGuaranteedToExecute(*Use);
891
892       } else
893         return; // Not a load or store.
894
895       // Merge the TBAA tags.
896       if (LoopUses.empty()) {
897         // On the first load/store, just take its TBAA tag.
898         TBAATag = Use->getMetadata(LLVMContext::MD_tbaa);
899       } else if (TBAATag) {
900         TBAATag = MDNode::getMostGenericTBAA(TBAATag,
901                                        Use->getMetadata(LLVMContext::MD_tbaa));
902       }
903       
904       LoopUses.push_back(Use);
905     }
906   }
907
908   // If there isn't a guaranteed-to-execute instruction, we can't promote.
909   if (!GuaranteedToExecute)
910     return;
911
912   // Otherwise, this is safe to promote, lets do it!
913   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
914   Changed = true;
915   ++NumPromoted;
916
917   // Grab a debug location for the inserted loads/stores; given that the
918   // inserted loads/stores have little relation to the original loads/stores,
919   // this code just arbitrarily picks a location from one, since any debug
920   // location is better than none.
921   DebugLoc DL = LoopUses[0]->getDebugLoc();
922
923   // Figure out the loop exits and their insertion points, if this is the
924   // first promotion.
925   if (ExitBlocks.empty()) {
926     CurLoop->getUniqueExitBlocks(ExitBlocks);
927     InsertPts.resize(ExitBlocks.size());
928     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
929       InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
930   }
931
932   // We use the SSAUpdater interface to insert phi nodes as required.
933   SmallVector<PHINode*, 16> NewPHIs;
934   SSAUpdater SSA(&NewPHIs);
935   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
936                         InsertPts, *CurAST, DL, Alignment, TBAATag);
937
938   // Set up the preheader to have a definition of the value.  It is the live-out
939   // value from the preheader that uses in the loop will use.
940   LoadInst *PreheaderLoad =
941     new LoadInst(SomePtr, SomePtr->getName()+".promoted",
942                  Preheader->getTerminator());
943   PreheaderLoad->setAlignment(Alignment);
944   PreheaderLoad->setDebugLoc(DL);
945   if (TBAATag) PreheaderLoad->setMetadata(LLVMContext::MD_tbaa, TBAATag);
946   SSA.AddAvailableValue(Preheader, PreheaderLoad);
947
948   // Rewrite all the loads in the loop and remember all the definitions from
949   // stores in the loop.
950   Promoter.run(LoopUses);
951
952   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
953   if (PreheaderLoad->use_empty())
954     PreheaderLoad->eraseFromParent();
955 }
956
957
958 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
959 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
960   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
961   if (!AST)
962     return;
963
964   AST->copyValue(From, To);
965 }
966
967 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
968 /// set.
969 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
970   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
971   if (!AST)
972     return;
973
974   AST->deleteValue(V);
975 }