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