LICM.cpp revision ce63ffb52f249b62cdf2d250c128007b13f27e71
10218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
20218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
30218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//                     The LLVM Compiler Infrastructure
40218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
50218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// This file is distributed under the University of Illinois Open Source
60218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// License. See LICENSE.TXT for details.
70218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
80218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//===----------------------------------------------------------------------===//
90218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
100218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// This pass performs loop invariant code motion, attempting to remove as much
110218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// code from the body of a loop as possible.  It does this by either hoisting
120218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// code into the preheader block, or by sinking code to the exit blocks if it is
130218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// safe.  This pass also promotes must-aliased memory locations in the loop to
140218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// live in registers, thus hoisting and sinking "invariant" loads and stores.
150218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
160218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// This pass uses alias analysis for two purposes:
170218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
180218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//  1. Moving loop invariant loads and calls out of loops.  If we can determine
190218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     that a load or call inside of a loop never aliases anything stored to,
200218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     we can hoist it or sink it like any other instruction.
214ebd7f54ad9ed6fb64fa2cfbbbebc97dbd30fba6Ted Kremenek//  2. Scalar Promotion of Memory - If there is a store instruction inside of
220218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     the loop, we try to move the store to happen AFTER the loop instead of
230218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     inside of the loop.  This can only happen if a few conditions are true:
240218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//       A. The pointer stored through is loop invariant
250218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//       B. There are no stores or loads in the loop which _may_ alias the
260218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//          pointer.  There are no calls in the loop which mod/ref the pointer.
270218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     If these conditions are true, we can promote the loads and stores in the
280218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     loop of the pointer to use a temporary alloca'd variable.  We then use
290218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     the mem2reg functionality to construct the appropriate SSA form for the
300218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//     variable.
310218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//
320218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor//===----------------------------------------------------------------------===//
330218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
340218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#define DEBUG_TYPE "licm"
350218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Transforms/Scalar.h"
365f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner#include "llvm/Constants.h"
370218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/DerivedTypes.h"
380218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Instructions.h"
390218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/LLVMContext.h"
400218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Target/TargetData.h"
415f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner#include "llvm/Analysis/LoopInfo.h"
420218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Analysis/LoopPass.h"
430218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Analysis/AliasAnalysis.h"
440218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Analysis/AliasSetTracker.h"
450218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Analysis/Dominators.h"
460218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Analysis/ScalarEvolution.h"
470218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Transforms/Utils/PromoteMemToReg.h"
480218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Support/CFG.h"
490218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Support/Compiler.h"
500218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Support/CommandLine.h"
510218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Support/raw_ostream.h"
520218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/Support/Debug.h"
530218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include "llvm/ADT/Statistic.h"
540218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor#include <algorithm>
550218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregorusing namespace llvm;
560218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
570218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorSTATISTIC(NumSunk      , "Number of instructions sunk out of loop");
585f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerSTATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
590218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorSTATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
600218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorSTATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
610218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorSTATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
620218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
630218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregorstatic cl::opt<bool>
640218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorDisablePromotion("disable-licm-promotion", cl::Hidden,
650218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor                 cl::desc("Disable memory promotion in LICM pass"));
660218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
670218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// This feature is currently disabled by default because CodeGen is not yet
680218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// capable of rematerializing these constants in PIC mode, so it can lead to
690218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// degraded performance. Compile test/CodeGen/X86/remat-constant.ll with
700218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor// -relocation-model=pic to see an example of this.
710218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregorstatic cl::opt<bool>
720218936235b137bbdcd29a6c36d61d9215bb4eddDouglas GregorEnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden,
730218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor                         cl::desc("Enable hoisting/sinking of constant "
740218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor                                  "global variables"));
750218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
760218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregornamespace {
770218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor  struct VISIBILITY_HIDDEN LICM : public LoopPass {
780218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    static char ID; // Pass identification, replacement for typeid
790218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    LICM() : LoopPass(&ID) {}
800218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
810218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
820218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
830218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// This transformation requires natural loop information & requires that
840218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// loop preheaders be inserted into the CFG...
850218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    ///
860218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
870218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      AU.setPreservesCFG();
880218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      AU.addRequiredID(LoopSimplifyID);
890218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      AU.addRequired<LoopInfo>();
900218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      AU.addRequired<DominatorTree>();
910218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      AU.addRequired<AliasAnalysis>();
936217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek      AU.addPreserved<ScalarEvolution>();
9457c856b96e6bbfc64c2d61b950b116b523dc3e46Douglas Gregor      AU.addPreserved<DominanceFrontier>();
9557c856b96e6bbfc64c2d61b950b116b523dc3e46Douglas Gregor    }
960218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
970218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    bool doFinalization() {
980218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      // Free the values stored in the map
990218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      for (std::map<Loop *, AliasSetTracker *>::iterator
1000218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor             I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
1010218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor        delete I->second;
1020218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1030218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      LoopToAliasMap.clear();
1040218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      return false;
1050218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    }
1060218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1070218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor  private:
1080218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    // Various analyses that we use...
1090218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    AliasAnalysis *AA;       // Current AliasAnalysis information
1100218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    LoopInfo      *LI;       // Current LoopInfo
1110218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    DominatorTree *DT;       // Dominator Tree for the current Loop...
1120218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    DominanceFrontier *DF;   // Current Dominance Frontier
1130218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1140218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    // State that is updated as we process loops
1150218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    bool Changed;            // Set to true when we change anything.
1160218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    BasicBlock *Preheader;   // The preheader block of the current loop...
1170218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    Loop *CurLoop;           // The current loop we are working on...
1180218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    AliasSetTracker *CurAST; // AliasSet information for the current loop...
1190218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
1200218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1210218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
1220218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
1235f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner
1241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
1250218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// set.
1260218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    void deleteAnalysisValue(Value *V, Loop *L);
1270218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1280218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
1290218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// dominated by the specified block, and that are in the current loop) in
1300218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// reverse depth first order w.r.t the DominatorTree.  This allows us to
1310218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// visit uses before definitions, allowing us to sink a loop body in one
1320218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// pass without iteration.
1330218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    ///
1340218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    void SinkRegion(DomTreeNode *N);
1350218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1361f81230ac57b9bda8bba9c8221652842ca786132Douglas Gregor    /// HoistRegion - Walk the specified region of the CFG (defined by all
1371f81230ac57b9bda8bba9c8221652842ca786132Douglas Gregor    /// blocks dominated by the specified block, and that are in the current
138ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
139ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// visit definitions before uses, allowing us to hoist a loop body in one
140ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// pass without iteration.
141ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    ///
142ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    void HoistRegion(DomTreeNode *N);
143ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman
144ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// inSubLoop - Little predicate that returns true if the specified basic
145ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// block is in a subloop of the current one, not the current one itself.
146ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    ///
1470218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    bool inSubLoop(BasicBlock *BB) {
1480218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1490218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
150ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman        if ((*I)->contains(BB))
1510218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor          return true;  // A subloop actually contains this block!
152ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman      return false;
1530218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    }
154ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman
155ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
156ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// specified exit block of the loop is dominated by the specified block
157ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// that is in the body of the loop.  We use these constraints to
1580218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor    /// dramatically limit the amount of the dominator tree that needs to be
159ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    /// searched.
160ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman    bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
161ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman                                           BasicBlock *BlockInLoop) const {
162ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman      // If the block in the loop is the loop header, it must be dominated!
163ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman      BasicBlock *LoopHeader = CurLoop->getHeader();
164ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman      if (BlockInLoop == LoopHeader)
165ef165c94cf743c7e5eb6f65bced28cdb9ba118f5Dan Gohman        return true;
1660218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor
1670218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
1680218936235b137bbdcd29a6c36d61d9215bb4eddDouglas Gregor      DomTreeNode *IDom            = DT->getNode(ExitBlock);
169
170      // Because the exit block is not in the loop, we know we have to get _at
171      // least_ its immediate dominator.
172      do {
173        // Get next Immediate Dominator.
174        IDom = IDom->getIDom();
175
176        // If we have got to the header of the loop, then the instructions block
177        // did not dominate the exit node, so we can't hoist it.
178        if (IDom->getBlock() == LoopHeader)
179          return false;
180
181      } while (IDom != BlockInLoopNode);
182
183      return true;
184    }
185
186    /// sink - When an instruction is found to only be used outside of the loop,
187    /// this function moves it to the exit blocks and patches up SSA form as
188    /// needed.
189    ///
190    void sink(Instruction &I);
191
192    /// hoist - When an instruction is found to only use loop invariant operands
193    /// that is safe to hoist, this instruction is called to do the dirty work.
194    ///
195    void hoist(Instruction &I);
196
197    /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
198    /// is not a trapping instruction or if it is a trapping instruction and is
199    /// guaranteed to execute.
200    ///
201    bool isSafeToExecuteUnconditionally(Instruction &I);
202
203    /// pointerInvalidatedByLoop - Return true if the body of this loop may
204    /// store into the memory location pointed to by V.
205    ///
206    bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
207      // Check to see if any of the basic blocks in CurLoop invalidate *V.
208      return CurAST->getAliasSetForPointer(V, Size).isMod();
209    }
210
211    bool canSinkOrHoistInst(Instruction &I);
212    bool isLoopInvariantInst(Instruction &I);
213    bool isNotUsedInLoop(Instruction &I);
214
215    /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
216    /// to scalars as we can.
217    ///
218    void PromoteValuesInLoop();
219
220    /// FindPromotableValuesInLoop - Check the current loop for stores to
221    /// definite pointers, which are not loaded and stored through may aliases.
222    /// If these are found, create an alloca for the value, add it to the
223    /// PromotedValues list, and keep track of the mapping from value to
224    /// alloca...
225    ///
226    void FindPromotableValuesInLoop(
227                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
228                                    std::map<Value*, AllocaInst*> &Val2AlMap);
229  };
230}
231
232char LICM::ID = 0;
233static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
234
235Pass *llvm::createLICMPass() { return new LICM(); }
236
237/// Hoist expressions out of the specified loop. Note, alias info for inner
238/// loop is not preserved so it is not a good idea to run LICM multiple
239/// times on one loop.
240///
241bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
242  Changed = false;
243
244  // Get our Loop and Alias Analysis information...
245  LI = &getAnalysis<LoopInfo>();
246  AA = &getAnalysis<AliasAnalysis>();
247  DF = &getAnalysis<DominanceFrontier>();
248  DT = &getAnalysis<DominatorTree>();
249
250  CurAST = new AliasSetTracker(*AA);
251  // Collect Alias info from subloops
252  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
253       LoopItr != LoopItrE; ++LoopItr) {
254    Loop *InnerL = *LoopItr;
255    AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
256    assert (InnerAST && "Where is my AST?");
257
258    // What if InnerLoop was modified by other passes ?
259    CurAST->add(*InnerAST);
260  }
261
262  CurLoop = L;
263
264  // Get the preheader block to move instructions into...
265  Preheader = L->getLoopPreheader();
266  assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
267
268  // Loop over the body of this loop, looking for calls, invokes, and stores.
269  // Because subloops have already been incorporated into AST, we skip blocks in
270  // subloops.
271  //
272  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
273       I != E; ++I) {
274    BasicBlock *BB = *I;
275    if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops...
276      CurAST->add(*BB);                 // Incorporate the specified basic block
277  }
278
279  // We want to visit all of the instructions in this loop... that are not parts
280  // of our subloops (they have already had their invariants hoisted out of
281  // their loop, into this loop, so there is no need to process the BODIES of
282  // the subloops).
283  //
284  // Traverse the body of the loop in depth first order on the dominator tree so
285  // that we are guaranteed to see definitions before we see uses.  This allows
286  // us to sink instructions in one pass, without iteration.  After sinking
287  // instructions, we perform another pass to hoist them out of the loop.
288  //
289  SinkRegion(DT->getNode(L->getHeader()));
290  HoistRegion(DT->getNode(L->getHeader()));
291
292  // Now that all loop invariants have been removed from the loop, promote any
293  // memory references to scalars that we can...
294  if (!DisablePromotion)
295    PromoteValuesInLoop();
296
297  // Clear out loops state information for the next iteration
298  CurLoop = 0;
299  Preheader = 0;
300
301  LoopToAliasMap[L] = CurAST;
302  return Changed;
303}
304
305/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
306/// dominated by the specified block, and that are in the current loop) in
307/// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
308/// uses before definitions, allowing us to sink a loop body in one pass without
309/// iteration.
310///
311void LICM::SinkRegion(DomTreeNode *N) {
312  assert(N != 0 && "Null dominator tree node?");
313  BasicBlock *BB = N->getBlock();
314
315  // If this subregion is not in the top level loop at all, exit.
316  if (!CurLoop->contains(BB)) return;
317
318  // We are processing blocks in reverse dfo, so process children first...
319  const std::vector<DomTreeNode*> &Children = N->getChildren();
320  for (unsigned i = 0, e = Children.size(); i != e; ++i)
321    SinkRegion(Children[i]);
322
323  // Only need to process the contents of this block if it is not part of a
324  // subloop (which would already have been processed).
325  if (inSubLoop(BB)) return;
326
327  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
328    Instruction &I = *--II;
329
330    // Check to see if we can sink this instruction to the exit blocks
331    // of the loop.  We can do this if the all users of the instruction are
332    // outside of the loop.  In this case, it doesn't even matter if the
333    // operands of the instruction are loop invariant.
334    //
335    if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
336      ++II;
337      sink(I);
338    }
339  }
340}
341
342
343/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
344/// dominated by the specified block, and that are in the current loop) in depth
345/// first order w.r.t the DominatorTree.  This allows us to visit definitions
346/// before uses, allowing us to hoist a loop body in one pass without iteration.
347///
348void LICM::HoistRegion(DomTreeNode *N) {
349  assert(N != 0 && "Null dominator tree node?");
350  BasicBlock *BB = N->getBlock();
351
352  // If this subregion is not in the top level loop at all, exit.
353  if (!CurLoop->contains(BB)) return;
354
355  // Only need to process the contents of this block if it is not part of a
356  // subloop (which would already have been processed).
357  if (!inSubLoop(BB))
358    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
359      Instruction &I = *II++;
360
361      // Try hoisting the instruction out to the preheader.  We can only do this
362      // if all of the operands of the instruction are loop invariant and if it
363      // is safe to hoist the instruction.
364      //
365      if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
366          isSafeToExecuteUnconditionally(I))
367        hoist(I);
368      }
369
370  const std::vector<DomTreeNode*> &Children = N->getChildren();
371  for (unsigned i = 0, e = Children.size(); i != e; ++i)
372    HoistRegion(Children[i]);
373}
374
375/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
376/// instruction.
377///
378bool LICM::canSinkOrHoistInst(Instruction &I) {
379  // Loads have extra constraints we have to verify before we can hoist them.
380  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
381    if (LI->isVolatile())
382      return false;        // Don't hoist volatile loads!
383
384    // Loads from constant memory are always safe to move, even if they end up
385    // in the same alias set as something that ends up being modified.
386    if (EnableLICMConstantMotion &&
387        AA->pointsToConstantMemory(LI->getOperand(0)))
388      return true;
389
390    // Don't hoist loads which have may-aliased stores in loop.
391    unsigned Size = 0;
392    if (LI->getType()->isSized())
393      Size = AA->getTargetData().getTypeStoreSize(LI->getType());
394    return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
395  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
396    // Handle obvious cases efficiently.
397    AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
398    if (Behavior == AliasAnalysis::DoesNotAccessMemory)
399      return true;
400    else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
401      // If this call only reads from memory and there are no writes to memory
402      // in the loop, we can hoist or sink the call as appropriate.
403      bool FoundMod = false;
404      for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
405           I != E; ++I) {
406        AliasSet &AS = *I;
407        if (!AS.isForwardingAliasSet() && AS.isMod()) {
408          FoundMod = true;
409          break;
410        }
411      }
412      if (!FoundMod) return true;
413    }
414
415    // FIXME: This should use mod/ref information to see if we can hoist or sink
416    // the call.
417
418    return false;
419  }
420
421  // Otherwise these instructions are hoistable/sinkable
422  return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
423         isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
424         isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
425         isa<ShuffleVectorInst>(I);
426}
427
428/// isNotUsedInLoop - Return true if the only users of this instruction are
429/// outside of the loop.  If this is true, we can sink the instruction to the
430/// exit blocks of the loop.
431///
432bool LICM::isNotUsedInLoop(Instruction &I) {
433  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
434    Instruction *User = cast<Instruction>(*UI);
435    if (PHINode *PN = dyn_cast<PHINode>(User)) {
436      // PHI node uses occur in predecessor blocks!
437      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
438        if (PN->getIncomingValue(i) == &I)
439          if (CurLoop->contains(PN->getIncomingBlock(i)))
440            return false;
441    } else if (CurLoop->contains(User->getParent())) {
442      return false;
443    }
444  }
445  return true;
446}
447
448
449/// isLoopInvariantInst - Return true if all operands of this instruction are
450/// loop invariant.  We also filter out non-hoistable instructions here just for
451/// efficiency.
452///
453bool LICM::isLoopInvariantInst(Instruction &I) {
454  // The instruction is loop invariant if all of its operands are loop-invariant
455  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
456    if (!CurLoop->isLoopInvariant(I.getOperand(i)))
457      return false;
458
459  // If we got this far, the instruction is loop invariant!
460  return true;
461}
462
463/// sink - When an instruction is found to only be used outside of the loop,
464/// this function moves it to the exit blocks and patches up SSA form as needed.
465/// This method is guaranteed to remove the original instruction from its
466/// position, and may either delete it or move it to outside of the loop.
467///
468void LICM::sink(Instruction &I) {
469  DOUT << "LICM sinking instruction: " << I;
470
471  SmallVector<BasicBlock*, 8> ExitBlocks;
472  CurLoop->getExitBlocks(ExitBlocks);
473
474  if (isa<LoadInst>(I)) ++NumMovedLoads;
475  else if (isa<CallInst>(I)) ++NumMovedCalls;
476  ++NumSunk;
477  Changed = true;
478
479  LLVMContext &Context = I.getContext();
480
481  // The case where there is only a single exit node of this loop is common
482  // enough that we handle it as a special (more efficient) case.  It is more
483  // efficient to handle because there are no PHI nodes that need to be placed.
484  if (ExitBlocks.size() == 1) {
485    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
486      // Instruction is not used, just delete it.
487      CurAST->deleteValue(&I);
488      if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
489        I.replaceAllUsesWith(Context.getUndef(I.getType()));
490      I.eraseFromParent();
491    } else {
492      // Move the instruction to the start of the exit block, after any PHI
493      // nodes in it.
494      I.removeFromParent();
495
496      BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
497      ExitBlocks[0]->getInstList().insert(InsertPt, &I);
498    }
499  } else if (ExitBlocks.empty()) {
500    // The instruction is actually dead if there ARE NO exit blocks.
501    CurAST->deleteValue(&I);
502    if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
503      I.replaceAllUsesWith(Context.getUndef(I.getType()));
504    I.eraseFromParent();
505  } else {
506    // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
507    // do all of the hard work of inserting PHI nodes as necessary.  We convert
508    // the value into a stack object to get it to do this.
509
510    // Firstly, we create a stack object to hold the value...
511    AllocaInst *AI = 0;
512
513    if (I.getType() != Type::VoidTy) {
514      AI = new AllocaInst(I.getType(), 0, I.getName(),
515                          I.getParent()->getParent()->getEntryBlock().begin());
516      CurAST->add(AI);
517    }
518
519    // Secondly, insert load instructions for each use of the instruction
520    // outside of the loop.
521    while (!I.use_empty()) {
522      Instruction *U = cast<Instruction>(I.use_back());
523
524      // If the user is a PHI Node, we actually have to insert load instructions
525      // in all predecessor blocks, not in the PHI block itself!
526      if (PHINode *UPN = dyn_cast<PHINode>(U)) {
527        // Only insert into each predecessor once, so that we don't have
528        // different incoming values from the same block!
529        std::map<BasicBlock*, Value*> InsertedBlocks;
530        for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
531          if (UPN->getIncomingValue(i) == &I) {
532            BasicBlock *Pred = UPN->getIncomingBlock(i);
533            Value *&PredVal = InsertedBlocks[Pred];
534            if (!PredVal) {
535              // Insert a new load instruction right before the terminator in
536              // the predecessor block.
537              PredVal = new LoadInst(AI, "", Pred->getTerminator());
538              CurAST->add(cast<LoadInst>(PredVal));
539            }
540
541            UPN->setIncomingValue(i, PredVal);
542          }
543
544      } else {
545        LoadInst *L = new LoadInst(AI, "", U);
546        U->replaceUsesOfWith(&I, L);
547        CurAST->add(L);
548      }
549    }
550
551    // Thirdly, insert a copy of the instruction in each exit block of the loop
552    // that is dominated by the instruction, storing the result into the memory
553    // location.  Be careful not to insert the instruction into any particular
554    // basic block more than once.
555    std::set<BasicBlock*> InsertedBlocks;
556    BasicBlock *InstOrigBB = I.getParent();
557
558    for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
559      BasicBlock *ExitBlock = ExitBlocks[i];
560
561      if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
562        // If we haven't already processed this exit block, do so now.
563        if (InsertedBlocks.insert(ExitBlock).second) {
564          // Insert the code after the last PHI node...
565          BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
566
567          // If this is the first exit block processed, just move the original
568          // instruction, otherwise clone the original instruction and insert
569          // the copy.
570          Instruction *New;
571          if (InsertedBlocks.size() == 1) {
572            I.removeFromParent();
573            ExitBlock->getInstList().insert(InsertPt, &I);
574            New = &I;
575          } else {
576            New = I.clone(Context);
577            CurAST->copyValue(&I, New);
578            if (!I.getName().empty())
579              New->setName(I.getName()+".le");
580            ExitBlock->getInstList().insert(InsertPt, New);
581          }
582
583          // Now that we have inserted the instruction, store it into the alloca
584          if (AI) new StoreInst(New, AI, InsertPt);
585        }
586      }
587    }
588
589    // If the instruction doesn't dominate any exit blocks, it must be dead.
590    if (InsertedBlocks.empty()) {
591      CurAST->deleteValue(&I);
592      I.eraseFromParent();
593    }
594
595    // Finally, promote the fine value to SSA form.
596    if (AI) {
597      std::vector<AllocaInst*> Allocas;
598      Allocas.push_back(AI);
599      PromoteMemToReg(Allocas, *DT, *DF, Context, CurAST);
600    }
601  }
602}
603
604/// hoist - When an instruction is found to only use loop invariant operands
605/// that is safe to hoist, this instruction is called to do the dirty work.
606///
607void LICM::hoist(Instruction &I) {
608  DEBUG(errs() << "LICM hoisting to " << Preheader->getName() << ": " << I);
609
610  // Remove the instruction from its current basic block... but don't delete the
611  // instruction.
612  I.removeFromParent();
613
614  // Insert the new node in Preheader, before the terminator.
615  Preheader->getInstList().insert(Preheader->getTerminator(), &I);
616
617  if (isa<LoadInst>(I)) ++NumMovedLoads;
618  else if (isa<CallInst>(I)) ++NumMovedCalls;
619  ++NumHoisted;
620  Changed = true;
621}
622
623/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
624/// not a trapping instruction or if it is a trapping instruction and is
625/// guaranteed to execute.
626///
627bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
628  // If it is not a trapping instruction, it is always safe to hoist.
629  if (Inst.isSafeToSpeculativelyExecute())
630    return true;
631
632  // Otherwise we have to check to make sure that the instruction dominates all
633  // of the exit blocks.  If it doesn't, then there is a path out of the loop
634  // which does not execute this instruction, so we can't hoist it.
635
636  // If the instruction is in the header block for the loop (which is very
637  // common), it is always guaranteed to dominate the exit blocks.  Since this
638  // is a common case, and can save some work, check it now.
639  if (Inst.getParent() == CurLoop->getHeader())
640    return true;
641
642  // Get the exit blocks for the current loop.
643  SmallVector<BasicBlock*, 8> ExitBlocks;
644  CurLoop->getExitBlocks(ExitBlocks);
645
646  // For each exit block, get the DT node and walk up the DT until the
647  // instruction's basic block is found or we exit the loop.
648  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
649    if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
650      return false;
651
652  return true;
653}
654
655
656/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
657/// stores out of the loop and moving loads to before the loop.  We do this by
658/// looping over the stores in the loop, looking for stores to Must pointers
659/// which are loop invariant.  We promote these memory locations to use allocas
660/// instead.  These allocas can easily be raised to register values by the
661/// PromoteMem2Reg functionality.
662///
663void LICM::PromoteValuesInLoop() {
664  // PromotedValues - List of values that are promoted out of the loop.  Each
665  // value has an alloca instruction for it, and a canonical version of the
666  // pointer.
667  std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
668  std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
669
670  FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
671  if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
672
673  Changed = true;
674  NumPromoted += PromotedValues.size();
675
676  std::vector<Value*> PointerValueNumbers;
677
678  // Emit a copy from the value into the alloca'd value in the loop preheader
679  TerminatorInst *LoopPredInst = Preheader->getTerminator();
680  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
681    Value *Ptr = PromotedValues[i].second;
682
683    // If we are promoting a pointer value, update alias information for the
684    // inserted load.
685    Value *LoadValue = 0;
686    if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
687      // Locate a load or store through the pointer, and assign the same value
688      // to LI as we are loading or storing.  Since we know that the value is
689      // stored in this loop, this will always succeed.
690      for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
691           UI != E; ++UI)
692        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
693          LoadValue = LI;
694          break;
695        } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
696          if (SI->getOperand(1) == Ptr) {
697            LoadValue = SI->getOperand(0);
698            break;
699          }
700        }
701      assert(LoadValue && "No store through the pointer found!");
702      PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
703    }
704
705    // Load from the memory we are promoting.
706    LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
707
708    if (LoadValue) CurAST->copyValue(LoadValue, LI);
709
710    // Store into the temporary alloca.
711    new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
712  }
713
714  // Scan the basic blocks in the loop, replacing uses of our pointers with
715  // uses of the allocas in question.
716  //
717  for (Loop::block_iterator I = CurLoop->block_begin(),
718         E = CurLoop->block_end(); I != E; ++I) {
719    BasicBlock *BB = *I;
720    // Rewrite all loads and stores in the block of the pointer...
721    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
722      if (LoadInst *L = dyn_cast<LoadInst>(II)) {
723        std::map<Value*, AllocaInst*>::iterator
724          I = ValueToAllocaMap.find(L->getOperand(0));
725        if (I != ValueToAllocaMap.end())
726          L->setOperand(0, I->second);    // Rewrite load instruction...
727      } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
728        std::map<Value*, AllocaInst*>::iterator
729          I = ValueToAllocaMap.find(S->getOperand(1));
730        if (I != ValueToAllocaMap.end())
731          S->setOperand(1, I->second);    // Rewrite store instruction...
732      }
733    }
734  }
735
736  // Now that the body of the loop uses the allocas instead of the original
737  // memory locations, insert code to copy the alloca value back into the
738  // original memory location on all exits from the loop.  Note that we only
739  // want to insert one copy of the code in each exit block, though the loop may
740  // exit to the same block more than once.
741  //
742  SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
743
744  SmallVector<BasicBlock*, 8> ExitBlocks;
745  CurLoop->getExitBlocks(ExitBlocks);
746  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
747    if (!ProcessedBlocks.insert(ExitBlocks[i]))
748      continue;
749
750    // Copy all of the allocas into their memory locations.
751    BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
752    Instruction *InsertPos = BI;
753    unsigned PVN = 0;
754    for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
755      // Load from the alloca.
756      LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
757
758      // If this is a pointer type, update alias info appropriately.
759      if (isa<PointerType>(LI->getType()))
760        CurAST->copyValue(PointerValueNumbers[PVN++], LI);
761
762      // Store into the memory we promoted.
763      new StoreInst(LI, PromotedValues[i].second, InsertPos);
764    }
765  }
766
767  // Now that we have done the deed, use the mem2reg functionality to promote
768  // all of the new allocas we just created into real SSA registers.
769  //
770  std::vector<AllocaInst*> PromotedAllocas;
771  PromotedAllocas.reserve(PromotedValues.size());
772  for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
773    PromotedAllocas.push_back(PromotedValues[i].first);
774  PromoteMemToReg(PromotedAllocas, *DT, *DF, Preheader->getContext(), CurAST);
775}
776
777/// FindPromotableValuesInLoop - Check the current loop for stores to definite
778/// pointers, which are not loaded and stored through may aliases and are safe
779/// for promotion.  If these are found, create an alloca for the value, add it
780/// to the PromotedValues list, and keep track of the mapping from value to
781/// alloca.
782void LICM::FindPromotableValuesInLoop(
783                   std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
784                             std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
785  Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
786
787  // Loop over all of the alias sets in the tracker object.
788  for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
789       I != E; ++I) {
790    AliasSet &AS = *I;
791    // We can promote this alias set if it has a store, if it is a "Must" alias
792    // set, if the pointer is loop invariant, and if we are not eliminating any
793    // volatile loads or stores.
794    if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
795        AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
796      continue;
797
798    assert(!AS.empty() &&
799           "Must alias set should have at least one pointer element in it!");
800    Value *V = AS.begin()->getValue();
801
802    // Check that all of the pointers in the alias set have the same type.  We
803    // cannot (yet) promote a memory location that is loaded and stored in
804    // different sizes.
805    {
806      bool PointerOk = true;
807      for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
808        if (V->getType() != I->getValue()->getType()) {
809          PointerOk = false;
810          break;
811        }
812      if (!PointerOk)
813        continue;
814    }
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    bool InvalidInst = false;
831    for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
832         UI != UE; ++UI) {
833      // Ignore instructions not in this loop.
834      Instruction *Use = dyn_cast<Instruction>(*UI);
835      if (!Use || !CurLoop->contains(Use->getParent()))
836        continue;
837
838      if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
839        InvalidInst = true;
840        break;
841      }
842
843      if (!GuaranteedToExecute)
844        GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
845    }
846
847    // If there is an non-load/store instruction in the loop, we can't promote
848    // it.  If there isn't a guaranteed-to-execute instruction, we can't
849    // promote.
850    if (InvalidInst || !GuaranteedToExecute)
851      continue;
852
853    const Type *Ty = cast<PointerType>(V->getType())->getElementType();
854    AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
855    PromotedValues.push_back(std::make_pair(AI, V));
856
857    // Update the AST and alias analysis.
858    CurAST->copyValue(V, AI);
859
860    for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
861      ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI));
862
863    DOUT << "LICM: Promoting value: " << *V << "\n";
864  }
865}
866
867/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
868void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
869  AliasSetTracker *AST = LoopToAliasMap[L];
870  if (!AST)
871    return;
872
873  AST->copyValue(From, To);
874}
875
876/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
877/// set.
878void LICM::deleteAnalysisValue(Value *V, Loop *L) {
879  AliasSetTracker *AST = LoopToAliasMap[L];
880  if (!AST)
881    return;
882
883  AST->deleteValue(V);
884}
885