LICM.cpp revision 245431
1193323Sed//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass performs loop invariant code motion, attempting to remove as much
11193323Sed// code from the body of a loop as possible.  It does this by either hoisting
12193323Sed// code into the preheader block, or by sinking code to the exit blocks if it is
13193323Sed// safe.  This pass also promotes must-aliased memory locations in the loop to
14193323Sed// live in registers, thus hoisting and sinking "invariant" loads and stores.
15193323Sed//
16193323Sed// This pass uses alias analysis for two purposes:
17193323Sed//
18193323Sed//  1. Moving loop invariant loads and calls out of loops.  If we can determine
19193323Sed//     that a load or call inside of a loop never aliases anything stored to,
20193323Sed//     we can hoist it or sink it like any other instruction.
21193323Sed//  2. Scalar Promotion of Memory - If there is a store instruction inside of
22193323Sed//     the loop, we try to move the store to happen AFTER the loop instead of
23193323Sed//     inside of the loop.  This can only happen if a few conditions are true:
24193323Sed//       A. The pointer stored through is loop invariant
25193323Sed//       B. There are no stores or loads in the loop which _may_ alias the
26193323Sed//          pointer.  There are no calls in the loop which mod/ref the pointer.
27193323Sed//     If these conditions are true, we can promote the loads and stores in the
28193323Sed//     loop of the pointer to use a temporary alloca'd variable.  We then use
29212904Sdim//     the SSAUpdater to construct the appropriate SSA form for the value.
30193323Sed//
31193323Sed//===----------------------------------------------------------------------===//
32193323Sed
33193323Sed#define DEBUG_TYPE "licm"
34193323Sed#include "llvm/Transforms/Scalar.h"
35193323Sed#include "llvm/Constants.h"
36193323Sed#include "llvm/DerivedTypes.h"
37198090Srdivacky#include "llvm/IntrinsicInst.h"
38193323Sed#include "llvm/Instructions.h"
39218893Sdim#include "llvm/LLVMContext.h"
40212904Sdim#include "llvm/Analysis/AliasAnalysis.h"
41212904Sdim#include "llvm/Analysis/AliasSetTracker.h"
42212904Sdim#include "llvm/Analysis/ConstantFolding.h"
43193323Sed#include "llvm/Analysis/LoopInfo.h"
44193323Sed#include "llvm/Analysis/LoopPass.h"
45193323Sed#include "llvm/Analysis/Dominators.h"
46235633Sdim#include "llvm/Analysis/ValueTracking.h"
47212904Sdim#include "llvm/Transforms/Utils/Local.h"
48212904Sdim#include "llvm/Transforms/Utils/SSAUpdater.h"
49245431Sdim#include "llvm/DataLayout.h"
50235633Sdim#include "llvm/Target/TargetLibraryInfo.h"
51193323Sed#include "llvm/Support/CFG.h"
52193323Sed#include "llvm/Support/CommandLine.h"
53198090Srdivacky#include "llvm/Support/raw_ostream.h"
54193323Sed#include "llvm/Support/Debug.h"
55193323Sed#include "llvm/ADT/Statistic.h"
56193323Sed#include <algorithm>
57193323Sedusing namespace llvm;
58193323Sed
59193323SedSTATISTIC(NumSunk      , "Number of instructions sunk out of loop");
60193323SedSTATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
61193323SedSTATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
62193323SedSTATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
63193323SedSTATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
64193323Sed
65193323Sedstatic cl::opt<bool>
66193323SedDisablePromotion("disable-licm-promotion", cl::Hidden,
67193323Sed                 cl::desc("Disable memory promotion in LICM pass"));
68193323Sed
69193323Sednamespace {
70198090Srdivacky  struct LICM : public LoopPass {
71193323Sed    static char ID; // Pass identification, replacement for typeid
72218893Sdim    LICM() : LoopPass(ID) {
73218893Sdim      initializeLICMPass(*PassRegistry::getPassRegistry());
74218893Sdim    }
75193323Sed
76193323Sed    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
77193323Sed
78193323Sed    /// This transformation requires natural loop information & requires that
79193323Sed    /// loop preheaders be inserted into the CFG...
80193323Sed    ///
81193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82193323Sed      AU.setPreservesCFG();
83212904Sdim      AU.addRequired<DominatorTree>();
84212904Sdim      AU.addRequired<LoopInfo>();
85193323Sed      AU.addRequiredID(LoopSimplifyID);
86193323Sed      AU.addRequired<AliasAnalysis>();
87212904Sdim      AU.addPreserved<AliasAnalysis>();
88218893Sdim      AU.addPreserved("scalar-evolution");
89198090Srdivacky      AU.addPreservedID(LoopSimplifyID);
90235633Sdim      AU.addRequired<TargetLibraryInfo>();
91193323Sed    }
92193323Sed
93193323Sed    bool doFinalization() {
94212904Sdim      assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
95193323Sed      return false;
96193323Sed    }
97193323Sed
98193323Sed  private:
99193323Sed    AliasAnalysis *AA;       // Current AliasAnalysis information
100193323Sed    LoopInfo      *LI;       // Current LoopInfo
101212904Sdim    DominatorTree *DT;       // Dominator Tree for the current Loop.
102193323Sed
103245431Sdim    DataLayout *TD;          // DataLayout for constant folding.
104235633Sdim    TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
105235633Sdim
106212904Sdim    // State that is updated as we process loops.
107193323Sed    bool Changed;            // Set to true when we change anything.
108193323Sed    BasicBlock *Preheader;   // The preheader block of the current loop...
109193323Sed    Loop *CurLoop;           // The current loop we are working on...
110193323Sed    AliasSetTracker *CurAST; // AliasSet information for the current loop...
111245431Sdim    bool MayThrow;           // The current loop contains an instruction which
112245431Sdim                             // may throw, thus preventing code motion of
113245431Sdim                             // instructions with side effects.
114212904Sdim    DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
115193323Sed
116193323Sed    /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
117193323Sed    void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
118193323Sed
119193323Sed    /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
120193323Sed    /// set.
121193323Sed    void deleteAnalysisValue(Value *V, Loop *L);
122193323Sed
123193323Sed    /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
124193323Sed    /// dominated by the specified block, and that are in the current loop) in
125193323Sed    /// reverse depth first order w.r.t the DominatorTree.  This allows us to
126193323Sed    /// visit uses before definitions, allowing us to sink a loop body in one
127193323Sed    /// pass without iteration.
128193323Sed    ///
129193323Sed    void SinkRegion(DomTreeNode *N);
130193323Sed
131193323Sed    /// HoistRegion - Walk the specified region of the CFG (defined by all
132193323Sed    /// blocks dominated by the specified block, and that are in the current
133193323Sed    /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
134193323Sed    /// visit definitions before uses, allowing us to hoist a loop body in one
135193323Sed    /// pass without iteration.
136193323Sed    ///
137193323Sed    void HoistRegion(DomTreeNode *N);
138193323Sed
139193323Sed    /// inSubLoop - Little predicate that returns true if the specified basic
140193323Sed    /// block is in a subloop of the current one, not the current one itself.
141193323Sed    ///
142193323Sed    bool inSubLoop(BasicBlock *BB) {
143193323Sed      assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
144218893Sdim      return LI->getLoopFor(BB) != CurLoop;
145193323Sed    }
146193323Sed
147193323Sed    /// sink - When an instruction is found to only be used outside of the loop,
148193323Sed    /// this function moves it to the exit blocks and patches up SSA form as
149193323Sed    /// needed.
150193323Sed    ///
151193323Sed    void sink(Instruction &I);
152193323Sed
153193323Sed    /// hoist - When an instruction is found to only use loop invariant operands
154193323Sed    /// that is safe to hoist, this instruction is called to do the dirty work.
155193323Sed    ///
156193323Sed    void hoist(Instruction &I);
157193323Sed
158193323Sed    /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
159193323Sed    /// is not a trapping instruction or if it is a trapping instruction and is
160193323Sed    /// guaranteed to execute.
161193323Sed    ///
162193323Sed    bool isSafeToExecuteUnconditionally(Instruction &I);
163193323Sed
164226890Sdim    /// isGuaranteedToExecute - Check that the instruction is guaranteed to
165226890Sdim    /// execute.
166226890Sdim    ///
167226890Sdim    bool isGuaranteedToExecute(Instruction &I);
168226890Sdim
169193323Sed    /// pointerInvalidatedByLoop - Return true if the body of this loop may
170193323Sed    /// store into the memory location pointed to by V.
171193323Sed    ///
172218893Sdim    bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
173218893Sdim                                  const MDNode *TBAAInfo) {
174193323Sed      // Check to see if any of the basic blocks in CurLoop invalidate *V.
175218893Sdim      return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
176193323Sed    }
177193323Sed
178193323Sed    bool canSinkOrHoistInst(Instruction &I);
179193323Sed    bool isNotUsedInLoop(Instruction &I);
180193323Sed
181245431Sdim    void PromoteAliasSet(AliasSet &AS,
182245431Sdim                         SmallVectorImpl<BasicBlock*> &ExitBlocks,
183245431Sdim                         SmallVectorImpl<Instruction*> &InsertPts);
184193323Sed  };
185193323Sed}
186193323Sed
187193323Sedchar LICM::ID = 0;
188218893SdimINITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
189218893SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree)
190218893SdimINITIALIZE_PASS_DEPENDENCY(LoopInfo)
191218893SdimINITIALIZE_PASS_DEPENDENCY(LoopSimplify)
192235633SdimINITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
193218893SdimINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
194218893SdimINITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
195193323Sed
196193323SedPass *llvm::createLICMPass() { return new LICM(); }
197193323Sed
198193323Sed/// Hoist expressions out of the specified loop. Note, alias info for inner
199224145Sdim/// loop is not preserved so it is not a good idea to run LICM multiple
200193323Sed/// times on one loop.
201193323Sed///
202193323Sedbool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
203193323Sed  Changed = false;
204193323Sed
205193323Sed  // Get our Loop and Alias Analysis information...
206193323Sed  LI = &getAnalysis<LoopInfo>();
207193323Sed  AA = &getAnalysis<AliasAnalysis>();
208193323Sed  DT = &getAnalysis<DominatorTree>();
209193323Sed
210245431Sdim  TD = getAnalysisIfAvailable<DataLayout>();
211235633Sdim  TLI = &getAnalysis<TargetLibraryInfo>();
212235633Sdim
213193323Sed  CurAST = new AliasSetTracker(*AA);
214212904Sdim  // Collect Alias info from subloops.
215193323Sed  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
216193323Sed       LoopItr != LoopItrE; ++LoopItr) {
217193323Sed    Loop *InnerL = *LoopItr;
218212904Sdim    AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
219212904Sdim    assert(InnerAST && "Where is my AST?");
220193323Sed
221193323Sed    // What if InnerLoop was modified by other passes ?
222193323Sed    CurAST->add(*InnerAST);
223224145Sdim
224212904Sdim    // Once we've incorporated the inner loop's AST into ours, we don't need the
225212904Sdim    // subloop's anymore.
226212904Sdim    delete InnerAST;
227212904Sdim    LoopToAliasSetMap.erase(InnerL);
228193323Sed  }
229224145Sdim
230193323Sed  CurLoop = L;
231193323Sed
232193323Sed  // Get the preheader block to move instructions into...
233193323Sed  Preheader = L->getLoopPreheader();
234193323Sed
235193323Sed  // Loop over the body of this loop, looking for calls, invokes, and stores.
236193323Sed  // Because subloops have already been incorporated into AST, we skip blocks in
237193323Sed  // subloops.
238193323Sed  //
239193323Sed  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
240193323Sed       I != E; ++I) {
241193323Sed    BasicBlock *BB = *I;
242212904Sdim    if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
243193323Sed      CurAST->add(*BB);                 // Incorporate the specified basic block
244193323Sed  }
245193323Sed
246245431Sdim  MayThrow = false;
247245431Sdim  // TODO: We've already searched for instructions which may throw in subloops.
248245431Sdim  // We may want to reuse this information.
249245431Sdim  for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end();
250245431Sdim       (BB != BBE) && !MayThrow ; ++BB)
251245431Sdim    for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
252245431Sdim         (I != E) && !MayThrow; ++I)
253245431Sdim      MayThrow |= I->mayThrow();
254245431Sdim
255193323Sed  // We want to visit all of the instructions in this loop... that are not parts
256193323Sed  // of our subloops (they have already had their invariants hoisted out of
257193323Sed  // their loop, into this loop, so there is no need to process the BODIES of
258193323Sed  // the subloops).
259193323Sed  //
260193323Sed  // Traverse the body of the loop in depth first order on the dominator tree so
261193323Sed  // that we are guaranteed to see definitions before we see uses.  This allows
262193323Sed  // us to sink instructions in one pass, without iteration.  After sinking
263193323Sed  // instructions, we perform another pass to hoist them out of the loop.
264193323Sed  //
265199481Srdivacky  if (L->hasDedicatedExits())
266199481Srdivacky    SinkRegion(DT->getNode(L->getHeader()));
267199481Srdivacky  if (Preheader)
268199481Srdivacky    HoistRegion(DT->getNode(L->getHeader()));
269193323Sed
270193323Sed  // Now that all loop invariants have been removed from the loop, promote any
271212904Sdim  // memory references to scalars that we can.
272212904Sdim  if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
273245431Sdim    SmallVector<BasicBlock *, 8> ExitBlocks;
274245431Sdim    SmallVector<Instruction *, 8> InsertPts;
275245431Sdim
276212904Sdim    // Loop over all of the alias sets in the tracker object.
277212904Sdim    for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
278212904Sdim         I != E; ++I)
279245431Sdim      PromoteAliasSet(*I, ExitBlocks, InsertPts);
280212904Sdim  }
281224145Sdim
282193323Sed  // Clear out loops state information for the next iteration
283193323Sed  CurLoop = 0;
284193323Sed  Preheader = 0;
285193323Sed
286212904Sdim  // If this loop is nested inside of another one, save the alias information
287212904Sdim  // for when we process the outer loop.
288212904Sdim  if (L->getParentLoop())
289212904Sdim    LoopToAliasSetMap[L] = CurAST;
290212904Sdim  else
291212904Sdim    delete CurAST;
292193323Sed  return Changed;
293193323Sed}
294193323Sed
295193323Sed/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
296193323Sed/// dominated by the specified block, and that are in the current loop) in
297193323Sed/// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
298193323Sed/// uses before definitions, allowing us to sink a loop body in one pass without
299193323Sed/// iteration.
300193323Sed///
301193323Sedvoid LICM::SinkRegion(DomTreeNode *N) {
302193323Sed  assert(N != 0 && "Null dominator tree node?");
303193323Sed  BasicBlock *BB = N->getBlock();
304193323Sed
305193323Sed  // If this subregion is not in the top level loop at all, exit.
306193323Sed  if (!CurLoop->contains(BB)) return;
307193323Sed
308212904Sdim  // We are processing blocks in reverse dfo, so process children first.
309193323Sed  const std::vector<DomTreeNode*> &Children = N->getChildren();
310193323Sed  for (unsigned i = 0, e = Children.size(); i != e; ++i)
311193323Sed    SinkRegion(Children[i]);
312193323Sed
313193323Sed  // Only need to process the contents of this block if it is not part of a
314193323Sed  // subloop (which would already have been processed).
315193323Sed  if (inSubLoop(BB)) return;
316193323Sed
317193323Sed  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
318193323Sed    Instruction &I = *--II;
319224145Sdim
320212904Sdim    // If the instruction is dead, we would try to sink it because it isn't used
321212904Sdim    // in the loop, instead, just delete it.
322245431Sdim    if (isInstructionTriviallyDead(&I, TLI)) {
323212904Sdim      DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
324212904Sdim      ++II;
325212904Sdim      CurAST->deleteValue(&I);
326212904Sdim      I.eraseFromParent();
327212904Sdim      Changed = true;
328212904Sdim      continue;
329212904Sdim    }
330193323Sed
331193323Sed    // Check to see if we can sink this instruction to the exit blocks
332193323Sed    // of the loop.  We can do this if the all users of the instruction are
333193323Sed    // outside of the loop.  In this case, it doesn't even matter if the
334193323Sed    // operands of the instruction are loop invariant.
335193323Sed    //
336193323Sed    if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
337193323Sed      ++II;
338193323Sed      sink(I);
339193323Sed    }
340193323Sed  }
341193323Sed}
342193323Sed
343193323Sed/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
344193323Sed/// dominated by the specified block, and that are in the current loop) in depth
345193323Sed/// first order w.r.t the DominatorTree.  This allows us to visit definitions
346193323Sed/// before uses, allowing us to hoist a loop body in one pass without iteration.
347193323Sed///
348193323Sedvoid LICM::HoistRegion(DomTreeNode *N) {
349193323Sed  assert(N != 0 && "Null dominator tree node?");
350193323Sed  BasicBlock *BB = N->getBlock();
351193323Sed
352193323Sed  // If this subregion is not in the top level loop at all, exit.
353193323Sed  if (!CurLoop->contains(BB)) return;
354193323Sed
355193323Sed  // Only need to process the contents of this block if it is not part of a
356193323Sed  // subloop (which would already have been processed).
357193323Sed  if (!inSubLoop(BB))
358193323Sed    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
359193323Sed      Instruction &I = *II++;
360193323Sed
361212904Sdim      // Try constant folding this instruction.  If all the operands are
362212904Sdim      // constants, it is technically hoistable, but it would be better to just
363212904Sdim      // fold it.
364235633Sdim      if (Constant *C = ConstantFoldInstruction(&I, TD, TLI)) {
365212904Sdim        DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
366212904Sdim        CurAST->copyValue(&I, C);
367212904Sdim        CurAST->deleteValue(&I);
368212904Sdim        I.replaceAllUsesWith(C);
369212904Sdim        I.eraseFromParent();
370212904Sdim        continue;
371212904Sdim      }
372224145Sdim
373193323Sed      // Try hoisting the instruction out to the preheader.  We can only do this
374193323Sed      // if all of the operands of the instruction are loop invariant and if it
375193323Sed      // is safe to hoist the instruction.
376193323Sed      //
377218893Sdim      if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
378193323Sed          isSafeToExecuteUnconditionally(I))
379193323Sed        hoist(I);
380212904Sdim    }
381193323Sed
382193323Sed  const std::vector<DomTreeNode*> &Children = N->getChildren();
383193323Sed  for (unsigned i = 0, e = Children.size(); i != e; ++i)
384193323Sed    HoistRegion(Children[i]);
385193323Sed}
386193323Sed
387193323Sed/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
388193323Sed/// instruction.
389193323Sed///
390193323Sedbool LICM::canSinkOrHoistInst(Instruction &I) {
391193323Sed  // Loads have extra constraints we have to verify before we can hoist them.
392193323Sed  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
393226890Sdim    if (!LI->isUnordered())
394226890Sdim      return false;        // Don't hoist volatile/atomic loads!
395193323Sed
396193323Sed    // Loads from constant memory are always safe to move, even if they end up
397193323Sed    // in the same alias set as something that ends up being modified.
398199989Srdivacky    if (AA->pointsToConstantMemory(LI->getOperand(0)))
399193323Sed      return true;
400235633Sdim    if (LI->getMetadata("invariant.load"))
401235633Sdim      return true;
402224145Sdim
403193323Sed    // Don't hoist loads which have may-aliased stores in loop.
404218893Sdim    uint64_t Size = 0;
405193323Sed    if (LI->getType()->isSized())
406198090Srdivacky      Size = AA->getTypeStoreSize(LI->getType());
407218893Sdim    return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
408218893Sdim                                     LI->getMetadata(LLVMContext::MD_tbaa));
409193323Sed  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
410223017Sdim    // Don't sink or hoist dbg info; it's legal, but not useful.
411223017Sdim    if (isa<DbgInfoIntrinsic>(I))
412223017Sdim      return false;
413223017Sdim
414223017Sdim    // Handle simple cases by querying alias analysis.
415193323Sed    AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
416193323Sed    if (Behavior == AliasAnalysis::DoesNotAccessMemory)
417193323Sed      return true;
418218893Sdim    if (AliasAnalysis::onlyReadsMemory(Behavior)) {
419193323Sed      // If this call only reads from memory and there are no writes to memory
420193323Sed      // in the loop, we can hoist or sink the call as appropriate.
421193323Sed      bool FoundMod = false;
422193323Sed      for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
423193323Sed           I != E; ++I) {
424193323Sed        AliasSet &AS = *I;
425193323Sed        if (!AS.isForwardingAliasSet() && AS.isMod()) {
426193323Sed          FoundMod = true;
427193323Sed          break;
428193323Sed        }
429193323Sed      }
430193323Sed      if (!FoundMod) return true;
431193323Sed    }
432193323Sed
433245431Sdim    // FIXME: This should use mod/ref information to see if we can hoist or
434245431Sdim    // sink the call.
435193323Sed
436193323Sed    return false;
437193323Sed  }
438193323Sed
439245431Sdim  // Only these instructions are hoistable/sinkable.
440245431Sdim  bool HoistableKind = (isa<BinaryOperator>(I) || isa<CastInst>(I) ||
441245431Sdim                            isa<SelectInst>(I) || isa<GetElementPtrInst>(I) ||
442245431Sdim                            isa<CmpInst>(I)    || isa<InsertElementInst>(I) ||
443245431Sdim                            isa<ExtractElementInst>(I) ||
444245431Sdim                            isa<ShuffleVectorInst>(I));
445245431Sdim  if (!HoistableKind)
446245431Sdim      return false;
447245431Sdim
448245431Sdim  return isSafeToExecuteUnconditionally(I);
449193323Sed}
450193323Sed
451193323Sed/// isNotUsedInLoop - Return true if the only users of this instruction are
452193323Sed/// outside of the loop.  If this is true, we can sink the instruction to the
453193323Sed/// exit blocks of the loop.
454193323Sed///
455193323Sedbool LICM::isNotUsedInLoop(Instruction &I) {
456193323Sed  for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
457193323Sed    Instruction *User = cast<Instruction>(*UI);
458193323Sed    if (PHINode *PN = dyn_cast<PHINode>(User)) {
459193323Sed      // PHI node uses occur in predecessor blocks!
460193323Sed      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
461193323Sed        if (PN->getIncomingValue(i) == &I)
462193323Sed          if (CurLoop->contains(PN->getIncomingBlock(i)))
463193323Sed            return false;
464201360Srdivacky    } else if (CurLoop->contains(User)) {
465193323Sed      return false;
466193323Sed    }
467193323Sed  }
468193323Sed  return true;
469193323Sed}
470193323Sed
471193323Sed
472193323Sed/// sink - When an instruction is found to only be used outside of the loop,
473193323Sed/// this function moves it to the exit blocks and patches up SSA form as needed.
474193323Sed/// This method is guaranteed to remove the original instruction from its
475193323Sed/// position, and may either delete it or move it to outside of the loop.
476193323Sed///
477193323Sedvoid LICM::sink(Instruction &I) {
478212904Sdim  DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
479193323Sed
480193323Sed  SmallVector<BasicBlock*, 8> ExitBlocks;
481212904Sdim  CurLoop->getUniqueExitBlocks(ExitBlocks);
482193323Sed
483193323Sed  if (isa<LoadInst>(I)) ++NumMovedLoads;
484193323Sed  else if (isa<CallInst>(I)) ++NumMovedCalls;
485193323Sed  ++NumSunk;
486193323Sed  Changed = true;
487193323Sed
488193323Sed  // The case where there is only a single exit node of this loop is common
489193323Sed  // enough that we handle it as a special (more efficient) case.  It is more
490193323Sed  // efficient to handle because there are no PHI nodes that need to be placed.
491193323Sed  if (ExitBlocks.size() == 1) {
492223017Sdim    if (!DT->dominates(I.getParent(), ExitBlocks[0])) {
493193323Sed      // Instruction is not used, just delete it.
494193323Sed      CurAST->deleteValue(&I);
495198090Srdivacky      // If I has users in unreachable blocks, eliminate.
496198090Srdivacky      // If I is not void type then replaceAllUsesWith undef.
497198090Srdivacky      // This allows ValueHandlers and custom metadata to adjust itself.
498212904Sdim      if (!I.use_empty())
499198090Srdivacky        I.replaceAllUsesWith(UndefValue::get(I.getType()));
500193323Sed      I.eraseFromParent();
501193323Sed    } else {
502193323Sed      // Move the instruction to the start of the exit block, after any PHI
503193323Sed      // nodes in it.
504226890Sdim      I.moveBefore(ExitBlocks[0]->getFirstInsertionPt());
505212904Sdim
506212904Sdim      // This instruction is no longer in the AST for the current loop, because
507212904Sdim      // we just sunk it out of the loop.  If we just sunk it into an outer
508212904Sdim      // loop, we will rediscover the operation when we process it.
509212904Sdim      CurAST->deleteValue(&I);
510193323Sed    }
511212904Sdim    return;
512212904Sdim  }
513224145Sdim
514212904Sdim  if (ExitBlocks.empty()) {
515193323Sed    // The instruction is actually dead if there ARE NO exit blocks.
516193323Sed    CurAST->deleteValue(&I);
517198090Srdivacky    // If I has users in unreachable blocks, eliminate.
518198090Srdivacky    // If I is not void type then replaceAllUsesWith undef.
519198090Srdivacky    // This allows ValueHandlers and custom metadata to adjust itself.
520212904Sdim    if (!I.use_empty())
521198090Srdivacky      I.replaceAllUsesWith(UndefValue::get(I.getType()));
522193323Sed    I.eraseFromParent();
523212904Sdim    return;
524212904Sdim  }
525224145Sdim
526212904Sdim  // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
527212904Sdim  // hard work of inserting PHI nodes as necessary.
528212904Sdim  SmallVector<PHINode*, 8> NewPHIs;
529212904Sdim  SSAUpdater SSA(&NewPHIs);
530224145Sdim
531212904Sdim  if (!I.use_empty())
532212904Sdim    SSA.Initialize(I.getType(), I.getName());
533224145Sdim
534212904Sdim  // Insert a copy of the instruction in each exit block of the loop that is
535212904Sdim  // dominated by the instruction.  Each exit block is known to only be in the
536212904Sdim  // ExitBlocks list once.
537212904Sdim  BasicBlock *InstOrigBB = I.getParent();
538212904Sdim  unsigned NumInserted = 0;
539224145Sdim
540212904Sdim  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
541212904Sdim    BasicBlock *ExitBlock = ExitBlocks[i];
542224145Sdim
543218893Sdim    if (!DT->dominates(InstOrigBB, ExitBlock))
544212904Sdim      continue;
545224145Sdim
546212904Sdim    // Insert the code after the last PHI node.
547226890Sdim    BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();
548224145Sdim
549212904Sdim    // If this is the first exit block processed, just move the original
550212904Sdim    // instruction, otherwise clone the original instruction and insert
551212904Sdim    // the copy.
552212904Sdim    Instruction *New;
553212904Sdim    if (NumInserted++ == 0) {
554212904Sdim      I.moveBefore(InsertPt);
555212904Sdim      New = &I;
556212904Sdim    } else {
557212904Sdim      New = I.clone();
558212904Sdim      if (!I.getName().empty())
559212904Sdim        New->setName(I.getName()+".le");
560212904Sdim      ExitBlock->getInstList().insert(InsertPt, New);
561193323Sed    }
562224145Sdim
563212904Sdim    // Now that we have inserted the instruction, inform SSAUpdater.
564212904Sdim    if (!I.use_empty())
565212904Sdim      SSA.AddAvailableValue(ExitBlock, New);
566193323Sed  }
567224145Sdim
568212904Sdim  // If the instruction doesn't dominate any exit blocks, it must be dead.
569212904Sdim  if (NumInserted == 0) {
570212904Sdim    CurAST->deleteValue(&I);
571212904Sdim    if (!I.use_empty())
572212904Sdim      I.replaceAllUsesWith(UndefValue::get(I.getType()));
573212904Sdim    I.eraseFromParent();
574212904Sdim    return;
575212904Sdim  }
576224145Sdim
577212904Sdim  // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
578212904Sdim  for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
579212904Sdim    // Grab the use before incrementing the iterator.
580212904Sdim    Use &U = UI.getUse();
581212904Sdim    // Increment the iterator before removing the use from the list.
582212904Sdim    ++UI;
583212904Sdim    SSA.RewriteUseAfterInsertions(U);
584212904Sdim  }
585224145Sdim
586212904Sdim  // Update CurAST for NewPHIs if I had pointer type.
587212904Sdim  if (I.getType()->isPointerTy())
588212904Sdim    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
589212904Sdim      CurAST->copyValue(&I, NewPHIs[i]);
590224145Sdim
591212904Sdim  // Finally, remove the instruction from CurAST.  It is no longer in the loop.
592212904Sdim  CurAST->deleteValue(&I);
593193323Sed}
594193323Sed
595193323Sed/// hoist - When an instruction is found to only use loop invariant operands
596193323Sed/// that is safe to hoist, this instruction is called to do the dirty work.
597193323Sed///
598193323Sedvoid LICM::hoist(Instruction &I) {
599202375Srdivacky  DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
600198090Srdivacky        << I << "\n");
601193323Sed
602212904Sdim  // Move the new node to the Preheader, before its terminator.
603212904Sdim  I.moveBefore(Preheader->getTerminator());
604193323Sed
605193323Sed  if (isa<LoadInst>(I)) ++NumMovedLoads;
606193323Sed  else if (isa<CallInst>(I)) ++NumMovedCalls;
607193323Sed  ++NumHoisted;
608193323Sed  Changed = true;
609193323Sed}
610193323Sed
611193323Sed/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
612193323Sed/// not a trapping instruction or if it is a trapping instruction and is
613193323Sed/// guaranteed to execute.
614193323Sed///
615193323Sedbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
616193323Sed  // If it is not a trapping instruction, it is always safe to hoist.
617235633Sdim  if (isSafeToSpeculativelyExecute(&Inst))
618198090Srdivacky    return true;
619193323Sed
620226890Sdim  return isGuaranteedToExecute(Inst);
621226890Sdim}
622226890Sdim
623226890Sdimbool LICM::isGuaranteedToExecute(Instruction &Inst) {
624245431Sdim
625245431Sdim  // Somewhere in this loop there is an instruction which may throw and make us
626245431Sdim  // exit the loop.
627245431Sdim  if (MayThrow)
628245431Sdim    return false;
629245431Sdim
630193323Sed  // Otherwise we have to check to make sure that the instruction dominates all
631193323Sed  // of the exit blocks.  If it doesn't, then there is a path out of the loop
632193323Sed  // which does not execute this instruction, so we can't hoist it.
633193323Sed
634193323Sed  // If the instruction is in the header block for the loop (which is very
635193323Sed  // common), it is always guaranteed to dominate the exit blocks.  Since this
636193323Sed  // is a common case, and can save some work, check it now.
637193323Sed  if (Inst.getParent() == CurLoop->getHeader())
638193323Sed    return true;
639193323Sed
640193323Sed  // Get the exit blocks for the current loop.
641193323Sed  SmallVector<BasicBlock*, 8> ExitBlocks;
642193323Sed  CurLoop->getExitBlocks(ExitBlocks);
643193323Sed
644218893Sdim  // Verify that the block dominates each of the exit blocks of the loop.
645193323Sed  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
646218893Sdim    if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
647193323Sed      return false;
648193323Sed
649245431Sdim  // As a degenerate case, if the loop is statically infinite then we haven't
650245431Sdim  // proven anything since there are no exit blocks.
651245431Sdim  if (ExitBlocks.empty())
652245431Sdim    return false;
653245431Sdim
654193323Sed  return true;
655193323Sed}
656193323Sed
657218893Sdimnamespace {
658218893Sdim  class LoopPromoter : public LoadAndStorePromoter {
659218893Sdim    Value *SomePtr;  // Designated pointer to store to.
660218893Sdim    SmallPtrSet<Value*, 4> &PointerMustAliases;
661218893Sdim    SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
662245431Sdim    SmallVectorImpl<Instruction*> &LoopInsertPts;
663218893Sdim    AliasSetTracker &AST;
664223017Sdim    DebugLoc DL;
665224145Sdim    int Alignment;
666218893Sdim  public:
667218893Sdim    LoopPromoter(Value *SP,
668218893Sdim                 const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
669218893Sdim                 SmallPtrSet<Value*, 4> &PMA,
670245431Sdim                 SmallVectorImpl<BasicBlock*> &LEB,
671245431Sdim                 SmallVectorImpl<Instruction*> &LIP,
672245431Sdim                 AliasSetTracker &ast, DebugLoc dl, int alignment)
673224145Sdim      : LoadAndStorePromoter(Insts, S), SomePtr(SP),
674245431Sdim        PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP),
675245431Sdim        AST(ast), DL(dl), Alignment(alignment) {}
676224145Sdim
677218893Sdim    virtual bool isInstInList(Instruction *I,
678218893Sdim                              const SmallVectorImpl<Instruction*> &) const {
679218893Sdim      Value *Ptr;
680218893Sdim      if (LoadInst *LI = dyn_cast<LoadInst>(I))
681218893Sdim        Ptr = LI->getOperand(0);
682218893Sdim      else
683218893Sdim        Ptr = cast<StoreInst>(I)->getPointerOperand();
684218893Sdim      return PointerMustAliases.count(Ptr);
685218893Sdim    }
686224145Sdim
687218893Sdim    virtual void doExtraRewritesBeforeFinalDeletion() const {
688218893Sdim      // Insert stores after in the loop exit blocks.  Each exit block gets a
689218893Sdim      // store of the live-out values that feed them.  Since we've already told
690218893Sdim      // the SSA updater about the defs in the loop and the preheader
691218893Sdim      // definition, it is all set and we can start using it.
692218893Sdim      for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
693218893Sdim        BasicBlock *ExitBlock = LoopExitBlocks[i];
694218893Sdim        Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
695245431Sdim        Instruction *InsertPos = LoopInsertPts[i];
696223017Sdim        StoreInst *NewSI = new StoreInst(LiveInValue, SomePtr, InsertPos);
697224145Sdim        NewSI->setAlignment(Alignment);
698223017Sdim        NewSI->setDebugLoc(DL);
699218893Sdim      }
700218893Sdim    }
701218893Sdim
702218893Sdim    virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {
703218893Sdim      // Update alias analysis.
704218893Sdim      AST.copyValue(LI, V);
705218893Sdim    }
706218893Sdim    virtual void instructionDeleted(Instruction *I) const {
707218893Sdim      AST.deleteValue(I);
708218893Sdim    }
709218893Sdim  };
710218893Sdim} // end anon namespace
711218893Sdim
712212904Sdim/// PromoteAliasSet - Try to promote memory values to scalars by sinking
713193323Sed/// stores out of the loop and moving loads to before the loop.  We do this by
714193323Sed/// looping over the stores in the loop, looking for stores to Must pointers
715212904Sdim/// which are loop invariant.
716193323Sed///
717245431Sdimvoid LICM::PromoteAliasSet(AliasSet &AS,
718245431Sdim                           SmallVectorImpl<BasicBlock*> &ExitBlocks,
719245431Sdim                           SmallVectorImpl<Instruction*> &InsertPts) {
720212904Sdim  // We can promote this alias set if it has a store, if it is a "Must" alias
721212904Sdim  // set, if the pointer is loop invariant, and if we are not eliminating any
722212904Sdim  // volatile loads or stores.
723212904Sdim  if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
724212904Sdim      AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
725212904Sdim    return;
726224145Sdim
727212904Sdim  assert(!AS.empty() &&
728212904Sdim         "Must alias set should have at least one pointer element in it!");
729212904Sdim  Value *SomePtr = AS.begin()->getValue();
730193323Sed
731212904Sdim  // It isn't safe to promote a load/store from the loop if the load/store is
732212904Sdim  // conditional.  For example, turning:
733193323Sed  //
734212904Sdim  //    for () { if (c) *P += 1; }
735193323Sed  //
736212904Sdim  // into:
737212904Sdim  //
738212904Sdim  //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
739212904Sdim  //
740212904Sdim  // is not safe, because *P may only be valid to access if 'c' is true.
741224145Sdim  //
742212904Sdim  // It is safe to promote P if all uses are direct load/stores and if at
743212904Sdim  // least one is guaranteed to be executed.
744212904Sdim  bool GuaranteedToExecute = false;
745224145Sdim
746212904Sdim  SmallVector<Instruction*, 64> LoopUses;
747212904Sdim  SmallPtrSet<Value*, 4> PointerMustAliases;
748193323Sed
749224145Sdim  // We start with an alignment of one and try to find instructions that allow
750224145Sdim  // us to prove better alignment.
751224145Sdim  unsigned Alignment = 1;
752224145Sdim
753212904Sdim  // Check that all of the pointers in the alias set have the same type.  We
754212904Sdim  // cannot (yet) promote a memory location that is loaded and stored in
755212904Sdim  // different sizes.
756212904Sdim  for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
757212904Sdim    Value *ASIV = ASI->getValue();
758212904Sdim    PointerMustAliases.insert(ASIV);
759224145Sdim
760193323Sed    // Check that all of the pointers in the alias set have the same type.  We
761193323Sed    // cannot (yet) promote a memory location that is loaded and stored in
762193323Sed    // different sizes.
763212904Sdim    if (SomePtr->getType() != ASIV->getType())
764212904Sdim      return;
765224145Sdim
766212904Sdim    for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
767193323Sed         UI != UE; ++UI) {
768212904Sdim      // Ignore instructions that are outside the loop.
769193323Sed      Instruction *Use = dyn_cast<Instruction>(*UI);
770201360Srdivacky      if (!Use || !CurLoop->contains(Use))
771193323Sed        continue;
772224145Sdim
773212904Sdim      // If there is an non-load/store instruction in the loop, we can't promote
774212904Sdim      // it.
775224145Sdim      if (LoadInst *load = dyn_cast<LoadInst>(Use)) {
776226890Sdim        assert(!load->isVolatile() && "AST broken");
777226890Sdim        if (!load->isSimple())
778226890Sdim          return;
779224145Sdim      } else if (StoreInst *store = dyn_cast<StoreInst>(Use)) {
780218893Sdim        // Stores *of* the pointer are not interesting, only stores *to* the
781218893Sdim        // pointer.
782218893Sdim        if (Use->getOperand(1) != ASIV)
783218893Sdim          continue;
784226890Sdim        assert(!store->isVolatile() && "AST broken");
785226890Sdim        if (!store->isSimple())
786226890Sdim          return;
787226890Sdim
788226890Sdim        // Note that we only check GuaranteedToExecute inside the store case
789226890Sdim        // so that we do not introduce stores where they did not exist before
790226890Sdim        // (which would break the LLVM concurrency model).
791226890Sdim
792226890Sdim        // If the alignment of this instruction allows us to specify a more
793226890Sdim        // restrictive (and performant) alignment and if we are sure this
794226890Sdim        // instruction will be executed, update the alignment.
795226890Sdim        // Larger is better, with the exception of 0 being the best alignment.
796226890Sdim        unsigned InstAlignment = store->getAlignment();
797226890Sdim        if ((InstAlignment > Alignment || InstAlignment == 0)
798226890Sdim            && (Alignment != 0))
799226890Sdim          if (isGuaranteedToExecute(*Use)) {
800226890Sdim            GuaranteedToExecute = true;
801226890Sdim            Alignment = InstAlignment;
802226890Sdim          }
803226890Sdim
804226890Sdim        if (!GuaranteedToExecute)
805226890Sdim          GuaranteedToExecute = isGuaranteedToExecute(*Use);
806226890Sdim
807212904Sdim      } else
808212904Sdim        return; // Not a load or store.
809224145Sdim
810212904Sdim      LoopUses.push_back(Use);
811193323Sed    }
812212904Sdim  }
813224145Sdim
814212904Sdim  // If there isn't a guaranteed-to-execute instruction, we can't promote.
815212904Sdim  if (!GuaranteedToExecute)
816212904Sdim    return;
817224145Sdim
818212904Sdim  // Otherwise, this is safe to promote, lets do it!
819224145Sdim  DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
820212904Sdim  Changed = true;
821212904Sdim  ++NumPromoted;
822193323Sed
823223017Sdim  // Grab a debug location for the inserted loads/stores; given that the
824223017Sdim  // inserted loads/stores have little relation to the original loads/stores,
825223017Sdim  // this code just arbitrarily picks a location from one, since any debug
826223017Sdim  // location is better than none.
827223017Sdim  DebugLoc DL = LoopUses[0]->getDebugLoc();
828223017Sdim
829245431Sdim  // Figure out the loop exits and their insertion points, if this is the
830245431Sdim  // first promotion.
831245431Sdim  if (ExitBlocks.empty()) {
832245431Sdim    CurLoop->getUniqueExitBlocks(ExitBlocks);
833245431Sdim    InsertPts.resize(ExitBlocks.size());
834245431Sdim    for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
835245431Sdim      InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
836245431Sdim  }
837224145Sdim
838212904Sdim  // We use the SSAUpdater interface to insert phi nodes as required.
839212904Sdim  SmallVector<PHINode*, 16> NewPHIs;
840212904Sdim  SSAUpdater SSA(&NewPHIs);
841218893Sdim  LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
842245431Sdim                        InsertPts, *CurAST, DL, Alignment);
843224145Sdim
844218893Sdim  // Set up the preheader to have a definition of the value.  It is the live-out
845218893Sdim  // value from the preheader that uses in the loop will use.
846218893Sdim  LoadInst *PreheaderLoad =
847218893Sdim    new LoadInst(SomePtr, SomePtr->getName()+".promoted",
848218893Sdim                 Preheader->getTerminator());
849224145Sdim  PreheaderLoad->setAlignment(Alignment);
850223017Sdim  PreheaderLoad->setDebugLoc(DL);
851218893Sdim  SSA.AddAvailableValue(Preheader, PreheaderLoad);
852212904Sdim
853218893Sdim  // Rewrite all the loads in the loop and remember all the definitions from
854218893Sdim  // stores in the loop.
855218893Sdim  Promoter.run(LoopUses);
856221345Sdim
857221345Sdim  // If the SSAUpdater didn't use the load in the preheader, just zap it now.
858221345Sdim  if (PreheaderLoad->use_empty())
859221345Sdim    PreheaderLoad->eraseFromParent();
860193323Sed}
861193323Sed
862212904Sdim
863193323Sed/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
864193323Sedvoid LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
865212904Sdim  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
866193323Sed  if (!AST)
867193323Sed    return;
868193323Sed
869193323Sed  AST->copyValue(From, To);
870193323Sed}
871193323Sed
872193323Sed/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
873193323Sed/// set.
874193323Sedvoid LICM::deleteAnalysisValue(Value *V, Loop *L) {
875212904Sdim  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
876193323Sed  if (!AST)
877193323Sed    return;
878193323Sed
879193323Sed  AST->deleteValue(V);
880193323Sed}
881