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/LICM.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/CaptureTracking.h"
39 #include "llvm/Analysis/ConstantFolding.h"
40 #include "llvm/Analysis/GlobalsModRef.h"
41 #include "llvm/Analysis/GuardUtils.h"
42 #include "llvm/Analysis/Loads.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/Analysis/MemorySSA.h"
47 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
48 #include "llvm/Analysis/ScalarEvolution.h"
49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Transforms/Utils/Local.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/LLVMContext.h"
61 #include "llvm/IR/Metadata.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/PredIteratorCache.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Transforms/Scalar.h"
68 #include "llvm/Transforms/Scalar/LoopPassManager.h"
69 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70 #include "llvm/Transforms/Utils/LoopUtils.h"
71 #include "llvm/Transforms/Utils/SSAUpdater.h"
72 #include <algorithm>
73 #include <utility>
74 using namespace llvm;
75 
76 #define DEBUG_TYPE "licm"
77 
78 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
79 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
80 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
81 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
82 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
83 
84 /// Memory promotion is enabled by default.
85 static cl::opt<bool>
86     DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
87                      cl::desc("Disable memory promotion in LICM pass"));
88 
89 static cl::opt<uint32_t> MaxNumUsesTraversed(
90     "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
91     cl::desc("Max num uses visited for identifying load "
92              "invariance in loop using invariant start (default = 8)"));
93 
94 // Default value of zero implies we use the regular alias set tracker mechanism
95 // instead of the cross product using AA to identify aliasing of the memory
96 // location we are interested in.
97 static cl::opt<int>
98 LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
99                cl::desc("How many instruction to cross product using AA"));
100 
101 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
102 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
103                                   const LoopSafetyInfo *SafetyInfo,
104                                   TargetTransformInfo *TTI, bool &FreeInLoop);
105 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
106                   LoopSafetyInfo *SafetyInfo,
107                   OptimizationRemarkEmitter *ORE);
108 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
109                  const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
110                  OptimizationRemarkEmitter *ORE, bool FreeInLoop);
111 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
112                                            const DominatorTree *DT,
113                                            const Loop *CurLoop,
114                                            const LoopSafetyInfo *SafetyInfo,
115                                            OptimizationRemarkEmitter *ORE,
116                                            const Instruction *CtxI = nullptr);
117 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
118                                      AliasSetTracker *CurAST, Loop *CurLoop,
119                                      AliasAnalysis *AA);
120 
121 static Instruction *
122 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
123                             const LoopInfo *LI,
124                             const LoopSafetyInfo *SafetyInfo);
125 
126 namespace {
127 struct LoopInvariantCodeMotion {
128   using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
129   bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
130                  TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
131                  ScalarEvolution *SE, MemorySSA *MSSA,
132                  OptimizationRemarkEmitter *ORE, bool DeleteAST);
133 
134   ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
135 
136 private:
137   ASTrackerMapTy LoopToAliasSetMap;
138 
139   std::unique_ptr<AliasSetTracker>
140   collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
141 };
142 
143 struct LegacyLICMPass : public LoopPass {
144   static char ID; // Pass identification, replacement for typeid
145   LegacyLICMPass() : LoopPass(ID) {
146     initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
147   }
148 
149   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
150     if (skipLoop(L)) {
151       // If we have run LICM on a previous loop but now we are skipping
152       // (because we've hit the opt-bisect limit), we need to clear the
153       // loop alias information.
154       LICM.getLoopToAliasSetMap().clear();
155       return false;
156     }
157 
158     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
159     MemorySSA *MSSA = EnableMSSALoopDependency
160                           ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
161                           : nullptr;
162     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
163     // pass.  Function analyses need to be preserved across loop transformations
164     // but ORE cannot be preserved (see comment before the pass definition).
165     OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
166     return LICM.runOnLoop(L,
167                           &getAnalysis<AAResultsWrapperPass>().getAAResults(),
168                           &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
169                           &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
170                           &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
171                           &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
172                               *L->getHeader()->getParent()),
173                           SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
174   }
175 
176   /// This transformation requires natural loop information & requires that
177   /// loop preheaders be inserted into the CFG...
178   ///
179   void getAnalysisUsage(AnalysisUsage &AU) const override {
180     AU.addPreserved<DominatorTreeWrapperPass>();
181     AU.addPreserved<LoopInfoWrapperPass>();
182     AU.addRequired<TargetLibraryInfoWrapperPass>();
183     if (EnableMSSALoopDependency)
184       AU.addRequired<MemorySSAWrapperPass>();
185     AU.addRequired<TargetTransformInfoWrapperPass>();
186     getLoopAnalysisUsage(AU);
187   }
188 
189   using llvm::Pass::doFinalization;
190 
191   bool doFinalization() override {
192     assert(LICM.getLoopToAliasSetMap().empty() &&
193            "Didn't free loop alias sets");
194     return false;
195   }
196 
197 private:
198   LoopInvariantCodeMotion LICM;
199 
200   /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
201   void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
202                                Loop *L) override;
203 
204   /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
205   /// set.
206   void deleteAnalysisValue(Value *V, Loop *L) override;
207 
208   /// Simple Analysis hook. Delete loop L from alias set map.
209   void deleteAnalysisLoop(Loop *L) override;
210 };
211 } // namespace
212 
213 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
214                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
215   const auto &FAM =
216       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
217   Function *F = L.getHeader()->getParent();
218 
219   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
220   // FIXME: This should probably be optional rather than required.
221   if (!ORE)
222     report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
223                        "cached at a higher level");
224 
225   LoopInvariantCodeMotion LICM;
226   if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
227                       AR.MSSA, ORE, true))
228     return PreservedAnalyses::all();
229 
230   auto PA = getLoopPassPreservedAnalyses();
231 
232   PA.preserve<DominatorTreeAnalysis>();
233   PA.preserve<LoopAnalysis>();
234 
235   return PA;
236 }
237 
238 char LegacyLICMPass::ID = 0;
239 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
240                       false, false)
241 INITIALIZE_PASS_DEPENDENCY(LoopPass)
242 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
243 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
244 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
245 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
246                     false)
247 
248 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
249 
250 /// Hoist expressions out of the specified loop. Note, alias info for inner
251 /// loop is not preserved so it is not a good idea to run LICM multiple
252 /// times on one loop.
253 /// We should delete AST for inner loops in the new pass manager to avoid
254 /// memory leak.
255 ///
256 bool LoopInvariantCodeMotion::runOnLoop(
257     Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
258     TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
259     MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
260   bool Changed = false;
261 
262   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
263 
264   std::unique_ptr<AliasSetTracker> CurAST = collectAliasInfoForLoop(L, LI, AA);
265 
266   // Get the preheader block to move instructions into...
267   BasicBlock *Preheader = L->getLoopPreheader();
268 
269   // Compute loop safety information.
270   LoopSafetyInfo SafetyInfo;
271   SafetyInfo.computeLoopSafetyInfo(L);
272 
273   // We want to visit all of the instructions in this loop... that are not parts
274   // of our subloops (they have already had their invariants hoisted out of
275   // their loop, into this loop, so there is no need to process the BODIES of
276   // the subloops).
277   //
278   // Traverse the body of the loop in depth first order on the dominator tree so
279   // that we are guaranteed to see definitions before we see uses.  This allows
280   // us to sink instructions in one pass, without iteration.  After sinking
281   // instructions, we perform another pass to hoist them out of the loop.
282   //
283   if (L->hasDedicatedExits())
284     Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
285                           CurAST.get(), &SafetyInfo, ORE);
286   if (Preheader)
287     Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
288                            CurAST.get(), &SafetyInfo, ORE);
289 
290   // Now that all loop invariants have been removed from the loop, promote any
291   // memory references to scalars that we can.
292   // Don't sink stores from loops without dedicated block exits. Exits
293   // containing indirect branches are not transformed by loop simplify,
294   // make sure we catch that. An additional load may be generated in the
295   // preheader for SSA updater, so also avoid sinking when no preheader
296   // is available.
297   if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
298     // Figure out the loop exits and their insertion points
299     SmallVector<BasicBlock *, 8> ExitBlocks;
300     L->getUniqueExitBlocks(ExitBlocks);
301 
302     // We can't insert into a catchswitch.
303     bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
304       return isa<CatchSwitchInst>(Exit->getTerminator());
305     });
306 
307     if (!HasCatchSwitch) {
308       SmallVector<Instruction *, 8> InsertPts;
309       InsertPts.reserve(ExitBlocks.size());
310       for (BasicBlock *ExitBlock : ExitBlocks)
311         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
312 
313       PredIteratorCache PIC;
314 
315       bool Promoted = false;
316 
317       // Loop over all of the alias sets in the tracker object.
318       for (AliasSet &AS : *CurAST) {
319         // We can promote this alias set if it has a store, if it is a "Must"
320         // alias set, if the pointer is loop invariant, and if we are not
321         // eliminating any volatile loads or stores.
322         if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
323             !L->isLoopInvariant(AS.begin()->getValue()))
324           continue;
325 
326         assert(
327             !AS.empty() &&
328             "Must alias set should have at least one pointer element in it!");
329 
330         SmallSetVector<Value *, 8> PointerMustAliases;
331         for (const auto &ASI : AS)
332           PointerMustAliases.insert(ASI.getValue());
333 
334         Promoted |= promoteLoopAccessesToScalars(
335             PointerMustAliases, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L,
336             CurAST.get(), &SafetyInfo, ORE);
337       }
338 
339       // Once we have promoted values across the loop body we have to
340       // recursively reform LCSSA as any nested loop may now have values defined
341       // within the loop used in the outer loop.
342       // FIXME: This is really heavy handed. It would be a bit better to use an
343       // SSAUpdater strategy during promotion that was LCSSA aware and reformed
344       // it as it went.
345       if (Promoted)
346         formLCSSARecursively(*L, *DT, LI, SE);
347 
348       Changed |= Promoted;
349     }
350   }
351 
352   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
353   // specifically moving instructions across the loop boundary and so it is
354   // especially in need of sanity checking here.
355   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
356   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
357          "Parent loop not left in LCSSA form after LICM!");
358 
359   // If this loop is nested inside of another one, save the alias information
360   // for when we process the outer loop.
361   if (L->getParentLoop() && !DeleteAST)
362     LoopToAliasSetMap[L] = std::move(CurAST);
363 
364   if (Changed && SE)
365     SE->forgetLoopDispositions(L);
366   return Changed;
367 }
368 
369 /// Walk the specified region of the CFG (defined by all blocks dominated by
370 /// the specified block, and that are in the current loop) in reverse depth
371 /// first order w.r.t the DominatorTree.  This allows us to visit uses before
372 /// definitions, allowing us to sink a loop body in one pass without iteration.
373 ///
374 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
375                       DominatorTree *DT, TargetLibraryInfo *TLI,
376                       TargetTransformInfo *TTI, Loop *CurLoop,
377                       AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
378                       OptimizationRemarkEmitter *ORE) {
379 
380   // Verify inputs.
381   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
382          CurLoop != nullptr && CurAST && SafetyInfo != nullptr &&
383          "Unexpected input to sinkRegion");
384 
385   // We want to visit children before parents. We will enque all the parents
386   // before their children in the worklist and process the worklist in reverse
387   // order.
388   SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
389 
390   bool Changed = false;
391   for (DomTreeNode *DTN : reverse(Worklist)) {
392     BasicBlock *BB = DTN->getBlock();
393     // Only need to process the contents of this block if it is not part of a
394     // subloop (which would already have been processed).
395     if (inSubLoop(BB, CurLoop, LI))
396       continue;
397 
398     for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
399       Instruction &I = *--II;
400 
401       // If the instruction is dead, we would try to sink it because it isn't
402       // used in the loop, instead, just delete it.
403       if (isInstructionTriviallyDead(&I, TLI)) {
404         LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
405         salvageDebugInfo(I);
406         ++II;
407         CurAST->deleteValue(&I);
408         I.eraseFromParent();
409         Changed = true;
410         continue;
411       }
412 
413       // Check to see if we can sink this instruction to the exit blocks
414       // of the loop.  We can do this if the all users of the instruction are
415       // outside of the loop.  In this case, it doesn't even matter if the
416       // operands of the instruction are loop invariant.
417       //
418       bool FreeInLoop = false;
419       if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
420           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
421           !I.mayHaveSideEffects()) {
422         if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
423           if (!FreeInLoop) {
424             ++II;
425             CurAST->deleteValue(&I);
426             I.eraseFromParent();
427           }
428           Changed = true;
429         }
430       }
431     }
432   }
433   return Changed;
434 }
435 
436 /// Walk the specified region of the CFG (defined by all blocks dominated by
437 /// the specified block, and that are in the current loop) in depth first
438 /// order w.r.t the DominatorTree.  This allows us to visit definitions before
439 /// uses, allowing us to hoist a loop body in one pass without iteration.
440 ///
441 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
442                        DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
443                        AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
444                        OptimizationRemarkEmitter *ORE) {
445   // Verify inputs.
446   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
447          CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
448          "Unexpected input to hoistRegion");
449 
450   // We want to visit parents before children. We will enque all the parents
451   // before their children in the worklist and process the worklist in order.
452   SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
453 
454   bool Changed = false;
455   for (DomTreeNode *DTN : Worklist) {
456     BasicBlock *BB = DTN->getBlock();
457     // Only need to process the contents of this block if it is not part of a
458     // subloop (which would already have been processed).
459     if (inSubLoop(BB, CurLoop, LI))
460       continue;
461 
462     // Keep track of whether the prefix of instructions visited so far are such
463     // that the next instruction visited is guaranteed to execute if the loop
464     // is entered.
465     bool IsMustExecute = CurLoop->getHeader() == BB;
466     // Keep track of whether the prefix instructions could have written memory.
467     // TODO: This and IsMustExecute may be done smarter if we keep track of all
468     // throwing and mem-writing operations in every block, e.g. using something
469     // similar to isGuaranteedToExecute.
470     bool IsMemoryNotModified = CurLoop->getHeader() == BB;
471 
472     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
473       Instruction &I = *II++;
474       // Try constant folding this instruction.  If all the operands are
475       // constants, it is technically hoistable, but it would be better to
476       // just fold it.
477       if (Constant *C = ConstantFoldInstruction(
478               &I, I.getModule()->getDataLayout(), TLI)) {
479         LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C
480                           << '\n');
481         CurAST->copyValue(&I, C);
482         I.replaceAllUsesWith(C);
483         if (isInstructionTriviallyDead(&I, TLI)) {
484           CurAST->deleteValue(&I);
485           I.eraseFromParent();
486         }
487         Changed = true;
488         continue;
489       }
490 
491       // Try hoisting the instruction out to the preheader.  We can only do
492       // this if all of the operands of the instruction are loop invariant and
493       // if it is safe to hoist the instruction.
494       //
495       if (CurLoop->hasLoopInvariantOperands(&I) &&
496           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, true, ORE) &&
497           (IsMustExecute ||
498            isSafeToExecuteUnconditionally(
499                I, DT, CurLoop, SafetyInfo, ORE,
500                CurLoop->getLoopPreheader()->getTerminator()))) {
501         hoist(I, DT, CurLoop, SafetyInfo, ORE);
502         Changed = true;
503         continue;
504       }
505 
506       // Attempt to remove floating point division out of the loop by
507       // converting it to a reciprocal multiplication.
508       if (I.getOpcode() == Instruction::FDiv &&
509           CurLoop->isLoopInvariant(I.getOperand(1)) &&
510           I.hasAllowReciprocal()) {
511         auto Divisor = I.getOperand(1);
512         auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
513         auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
514         ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
515         ReciprocalDivisor->insertBefore(&I);
516 
517         auto Product =
518             BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
519         Product->setFastMathFlags(I.getFastMathFlags());
520         Product->insertAfter(&I);
521         I.replaceAllUsesWith(Product);
522         I.eraseFromParent();
523 
524         hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
525         Changed = true;
526         continue;
527       }
528 
529       using namespace PatternMatch;
530       if (((I.use_empty() &&
531             match(&I, m_Intrinsic<Intrinsic::invariant_start>())) ||
532            isGuard(&I)) &&
533           IsMustExecute && IsMemoryNotModified &&
534           CurLoop->hasLoopInvariantOperands(&I)) {
535         hoist(I, DT, CurLoop, SafetyInfo, ORE);
536         Changed = true;
537         continue;
538       }
539 
540       if (IsMustExecute)
541         IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I);
542       if (IsMemoryNotModified)
543         IsMemoryNotModified = !I.mayWriteToMemory();
544     }
545   }
546 
547   return Changed;
548 }
549 
550 // Return true if LI is invariant within scope of the loop. LI is invariant if
551 // CurLoop is dominated by an invariant.start representing the same memory
552 // location and size as the memory location LI loads from, and also the
553 // invariant.start has no uses.
554 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
555                                   Loop *CurLoop) {
556   Value *Addr = LI->getOperand(0);
557   const DataLayout &DL = LI->getModule()->getDataLayout();
558   const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
559       cast<PointerType>(Addr->getType())->getElementType());
560 
561   // if the type is i8 addrspace(x)*, we know this is the type of
562   // llvm.invariant.start operand
563   auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
564                                      LI->getPointerAddressSpace());
565   unsigned BitcastsVisited = 0;
566   // Look through bitcasts until we reach the i8* type (this is invariant.start
567   // operand type).
568   while (Addr->getType() != PtrInt8Ty) {
569     auto *BC = dyn_cast<BitCastInst>(Addr);
570     // Avoid traversing high number of bitcast uses.
571     if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
572       return false;
573     Addr = BC->getOperand(0);
574   }
575 
576   unsigned UsesVisited = 0;
577   // Traverse all uses of the load operand value, to see if invariant.start is
578   // one of the uses, and whether it dominates the load instruction.
579   for (auto *U : Addr->users()) {
580     // Avoid traversing for Load operand with high number of users.
581     if (++UsesVisited > MaxNumUsesTraversed)
582       return false;
583     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
584     // If there are escaping uses of invariant.start instruction, the load maybe
585     // non-invariant.
586     if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
587         !II->use_empty())
588       continue;
589     unsigned InvariantSizeInBits =
590         cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
591     // Confirm the invariant.start location size contains the load operand size
592     // in bits. Also, the invariant.start should dominate the load, and we
593     // should not hoist the load out of a loop that contains this dominating
594     // invariant.start.
595     if (LocSizeInBits <= InvariantSizeInBits &&
596         DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
597       return true;
598   }
599 
600   return false;
601 }
602 
603 namespace {
604 /// Return true if-and-only-if we know how to (mechanically) both hoist and
605 /// sink a given instruction out of a loop.  Does not address legality
606 /// concerns such as aliasing or speculation safety.
607 bool isHoistableAndSinkableInst(Instruction &I) {
608   // Only these instructions are hoistable/sinkable.
609   return (isa<LoadInst>(I) || isa<StoreInst>(I) ||
610           isa<CallInst>(I) || isa<FenceInst>(I) ||
611           isa<BinaryOperator>(I) || isa<CastInst>(I) ||
612           isa<SelectInst>(I) || isa<GetElementPtrInst>(I) ||
613           isa<CmpInst>(I) || isa<InsertElementInst>(I) ||
614           isa<ExtractElementInst>(I) || isa<ShuffleVectorInst>(I) ||
615           isa<ExtractValueInst>(I) || isa<InsertValueInst>(I));
616 }
617 /// Return true if all of the alias sets within this AST are known not to
618 /// contain a Mod.
619 bool isReadOnly(AliasSetTracker *CurAST) {
620   for (AliasSet &AS : *CurAST) {
621     if (!AS.isForwardingAliasSet() && AS.isMod()) {
622       return false;
623     }
624   }
625   return true;
626 }
627 }
628 
629 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
630                               Loop *CurLoop, AliasSetTracker *CurAST,
631                               bool TargetExecutesOncePerLoop,
632                               OptimizationRemarkEmitter *ORE) {
633   // If we don't understand the instruction, bail early.
634   if (!isHoistableAndSinkableInst(I))
635     return false;
636 
637   // Loads have extra constraints we have to verify before we can hoist them.
638   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
639     if (!LI->isUnordered())
640       return false; // Don't sink/hoist volatile or ordered atomic loads!
641 
642     // Loads from constant memory are always safe to move, even if they end up
643     // in the same alias set as something that ends up being modified.
644     if (AA->pointsToConstantMemory(LI->getOperand(0)))
645       return true;
646     if (LI->getMetadata(LLVMContext::MD_invariant_load))
647       return true;
648 
649     if (LI->isAtomic() && !TargetExecutesOncePerLoop)
650       return false; // Don't risk duplicating unordered loads
651 
652     // This checks for an invariant.start dominating the load.
653     if (isLoadInvariantInLoop(LI, DT, CurLoop))
654       return true;
655 
656     // Don't hoist loads which have may-aliased stores in loop.
657     uint64_t Size = 0;
658     if (LI->getType()->isSized())
659       Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
660 
661     AAMDNodes AAInfo;
662     LI->getAAMetadata(AAInfo);
663 
664     bool Invalidated = pointerInvalidatedByLoop(
665         MemoryLocation(LI->getOperand(0), Size, AAInfo), CurAST, CurLoop, AA);
666     // Check loop-invariant address because this may also be a sinkable load
667     // whose address is not necessarily loop-invariant.
668     if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
669       ORE->emit([&]() {
670         return OptimizationRemarkMissed(
671                    DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
672                << "failed to move load with loop-invariant address "
673                   "because the loop may invalidate its value";
674       });
675 
676     return !Invalidated;
677   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
678     // Don't sink or hoist dbg info; it's legal, but not useful.
679     if (isa<DbgInfoIntrinsic>(I))
680       return false;
681 
682     // Don't sink calls which can throw.
683     if (CI->mayThrow())
684       return false;
685 
686     using namespace PatternMatch;
687     if (match(CI, m_Intrinsic<Intrinsic::assume>()))
688       // Assumes don't actually alias anything or throw
689       return true;
690 
691     // Handle simple cases by querying alias analysis.
692     FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
693     if (Behavior == FMRB_DoesNotAccessMemory)
694       return true;
695     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
696       // A readonly argmemonly function only reads from memory pointed to by
697       // it's arguments with arbitrary offsets.  If we can prove there are no
698       // writes to this memory in the loop, we can hoist or sink.
699       if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
700         // TODO: expand to writeable arguments
701         for (Value *Op : CI->arg_operands())
702           if (Op->getType()->isPointerTy() &&
703               pointerInvalidatedByLoop(
704                   MemoryLocation(Op, MemoryLocation::UnknownSize, AAMDNodes()),
705                   CurAST, CurLoop, AA))
706             return false;
707         return true;
708       }
709 
710       // If this call only reads from memory and there are no writes to memory
711       // in the loop, we can hoist or sink the call as appropriate.
712       if (isReadOnly(CurAST))
713         return true;
714     }
715 
716     // FIXME: This should use mod/ref information to see if we can hoist or
717     // sink the call.
718 
719     return false;
720   } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
721     // Fences alias (most) everything to provide ordering.  For the moment,
722     // just give up if there are any other memory operations in the loop.
723     auto Begin = CurAST->begin();
724     assert(Begin != CurAST->end() && "must contain FI");
725     if (std::next(Begin) != CurAST->end())
726       // constant memory for instance, TODO: handle better
727       return false;
728     auto *UniqueI = Begin->getUniqueInstruction();
729     if (!UniqueI)
730       // other memory op, give up
731       return false;
732     (void)FI; //suppress unused variable warning
733     assert(UniqueI == FI && "AS must contain FI");
734     return true;
735   } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
736     if (!SI->isUnordered())
737       return false; // Don't sink/hoist volatile or ordered atomic store!
738 
739     // We can only hoist a store that we can prove writes a value which is not
740     // read or overwritten within the loop.  For those cases, we fallback to
741     // load store promotion instead.  TODO: We can extend this to cases where
742     // there is exactly one write to the location and that write dominates an
743     // arbitrary number of reads in the loop.
744     auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
745 
746     if (AS.isRef() || !AS.isMustAlias())
747       // Quick exit test, handled by the full path below as well.
748       return false;
749     auto *UniqueI = AS.getUniqueInstruction();
750     if (!UniqueI)
751       // other memory op, give up
752       return false;
753     assert(UniqueI == SI && "AS must contain SI");
754     return true;
755   }
756 
757   assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
758 
759   // We've established mechanical ability and aliasing, it's up to the caller
760   // to check fault safety
761   return true;
762 }
763 
764 /// Returns true if a PHINode is a trivially replaceable with an
765 /// Instruction.
766 /// This is true when all incoming values are that instruction.
767 /// This pattern occurs most often with LCSSA PHI nodes.
768 ///
769 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
770   for (const Value *IncValue : PN.incoming_values())
771     if (IncValue != &I)
772       return false;
773 
774   return true;
775 }
776 
777 /// Return true if the instruction is free in the loop.
778 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
779                          const TargetTransformInfo *TTI) {
780 
781   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
782     if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
783       return false;
784     // For a GEP, we cannot simply use getUserCost because currently it
785     // optimistically assume that a GEP will fold into addressing mode
786     // regardless of its users.
787     const BasicBlock *BB = GEP->getParent();
788     for (const User *U : GEP->users()) {
789       const Instruction *UI = cast<Instruction>(U);
790       if (CurLoop->contains(UI) &&
791           (BB != UI->getParent() ||
792            (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
793         return false;
794     }
795     return true;
796   } else
797     return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
798 }
799 
800 /// Return true if the only users of this instruction are outside of
801 /// the loop. If this is true, we can sink the instruction to the exit
802 /// blocks of the loop.
803 ///
804 /// We also return true if the instruction could be folded away in lowering.
805 /// (e.g.,  a GEP can be folded into a load as an addressing mode in the loop).
806 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
807                                   const LoopSafetyInfo *SafetyInfo,
808                                   TargetTransformInfo *TTI, bool &FreeInLoop) {
809   const auto &BlockColors = SafetyInfo->BlockColors;
810   bool IsFree = isFreeInLoop(I, CurLoop, TTI);
811   for (const User *U : I.users()) {
812     const Instruction *UI = cast<Instruction>(U);
813     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
814       const BasicBlock *BB = PN->getParent();
815       // We cannot sink uses in catchswitches.
816       if (isa<CatchSwitchInst>(BB->getTerminator()))
817         return false;
818 
819       // We need to sink a callsite to a unique funclet.  Avoid sinking if the
820       // phi use is too muddled.
821       if (isa<CallInst>(I))
822         if (!BlockColors.empty() &&
823             BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
824           return false;
825     }
826 
827     if (CurLoop->contains(UI)) {
828       if (IsFree) {
829         FreeInLoop = true;
830         continue;
831       }
832       return false;
833     }
834   }
835   return true;
836 }
837 
838 static Instruction *
839 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
840                             const LoopInfo *LI,
841                             const LoopSafetyInfo *SafetyInfo) {
842   Instruction *New;
843   if (auto *CI = dyn_cast<CallInst>(&I)) {
844     const auto &BlockColors = SafetyInfo->BlockColors;
845 
846     // Sinking call-sites need to be handled differently from other
847     // instructions.  The cloned call-site needs a funclet bundle operand
848     // appropriate for it's location in the CFG.
849     SmallVector<OperandBundleDef, 1> OpBundles;
850     for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
851          BundleIdx != BundleEnd; ++BundleIdx) {
852       OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
853       if (Bundle.getTagID() == LLVMContext::OB_funclet)
854         continue;
855 
856       OpBundles.emplace_back(Bundle);
857     }
858 
859     if (!BlockColors.empty()) {
860       const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
861       assert(CV.size() == 1 && "non-unique color for exit block!");
862       BasicBlock *BBColor = CV.front();
863       Instruction *EHPad = BBColor->getFirstNonPHI();
864       if (EHPad->isEHPad())
865         OpBundles.emplace_back("funclet", EHPad);
866     }
867 
868     New = CallInst::Create(CI, OpBundles);
869   } else {
870     New = I.clone();
871   }
872 
873   ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
874   if (!I.getName().empty())
875     New->setName(I.getName() + ".le");
876 
877   // Build LCSSA PHI nodes for any in-loop operands. Note that this is
878   // particularly cheap because we can rip off the PHI node that we're
879   // replacing for the number and blocks of the predecessors.
880   // OPT: If this shows up in a profile, we can instead finish sinking all
881   // invariant instructions, and then walk their operands to re-establish
882   // LCSSA. That will eliminate creating PHI nodes just to nuke them when
883   // sinking bottom-up.
884   for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
885        ++OI)
886     if (Instruction *OInst = dyn_cast<Instruction>(*OI))
887       if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
888         if (!OLoop->contains(&PN)) {
889           PHINode *OpPN =
890               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
891                               OInst->getName() + ".lcssa", &ExitBlock.front());
892           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
893             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
894           *OI = OpPN;
895         }
896   return New;
897 }
898 
899 static Instruction *sinkThroughTriviallyReplaceablePHI(
900     PHINode *TPN, Instruction *I, LoopInfo *LI,
901     SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
902     const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
903   assert(isTriviallyReplaceablePHI(*TPN, *I) &&
904          "Expect only trivially replaceable PHI");
905   BasicBlock *ExitBlock = TPN->getParent();
906   Instruction *New;
907   auto It = SunkCopies.find(ExitBlock);
908   if (It != SunkCopies.end())
909     New = It->second;
910   else
911     New = SunkCopies[ExitBlock] =
912         CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
913   return New;
914 }
915 
916 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
917   BasicBlock *BB = PN->getParent();
918   if (!BB->canSplitPredecessors())
919     return false;
920   // It's not impossible to split EHPad blocks, but if BlockColors already exist
921   // it require updating BlockColors for all offspring blocks accordingly. By
922   // skipping such corner case, we can make updating BlockColors after splitting
923   // predecessor fairly simple.
924   if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad())
925     return false;
926   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
927     BasicBlock *BBPred = *PI;
928     if (isa<IndirectBrInst>(BBPred->getTerminator()))
929       return false;
930   }
931   return true;
932 }
933 
934 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
935                                         LoopInfo *LI, const Loop *CurLoop,
936                                         LoopSafetyInfo *SafetyInfo) {
937 #ifndef NDEBUG
938   SmallVector<BasicBlock *, 32> ExitBlocks;
939   CurLoop->getUniqueExitBlocks(ExitBlocks);
940   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
941                                              ExitBlocks.end());
942 #endif
943   BasicBlock *ExitBB = PN->getParent();
944   assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
945 
946   // Split predecessors of the loop exit to make instructions in the loop are
947   // exposed to exit blocks through trivially replaceable PHIs while keeping the
948   // loop in the canonical form where each predecessor of each exit block should
949   // be contained within the loop. For example, this will convert the loop below
950   // from
951   //
952   // LB1:
953   //   %v1 =
954   //   br %LE, %LB2
955   // LB2:
956   //   %v2 =
957   //   br %LE, %LB1
958   // LE:
959   //   %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
960   //
961   // to
962   //
963   // LB1:
964   //   %v1 =
965   //   br %LE.split, %LB2
966   // LB2:
967   //   %v2 =
968   //   br %LE.split2, %LB1
969   // LE.split:
970   //   %p1 = phi [%v1, %LB1]  <-- trivially replaceable
971   //   br %LE
972   // LE.split2:
973   //   %p2 = phi [%v2, %LB2]  <-- trivially replaceable
974   //   br %LE
975   // LE:
976   //   %p = phi [%p1, %LE.split], [%p2, %LE.split2]
977   //
978   auto &BlockColors = SafetyInfo->BlockColors;
979   SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
980   while (!PredBBs.empty()) {
981     BasicBlock *PredBB = *PredBBs.begin();
982     assert(CurLoop->contains(PredBB) &&
983            "Expect all predecessors are in the loop");
984     if (PN->getBasicBlockIndex(PredBB) >= 0) {
985       BasicBlock *NewPred = SplitBlockPredecessors(
986           ExitBB, PredBB, ".split.loop.exit", DT, LI, nullptr, true);
987       // Since we do not allow splitting EH-block with BlockColors in
988       // canSplitPredecessors(), we can simply assign predecessor's color to
989       // the new block.
990       if (!BlockColors.empty()) {
991         // Grab a reference to the ColorVector to be inserted before getting the
992         // reference to the vector we are copying because inserting the new
993         // element in BlockColors might cause the map to be reallocated.
994         ColorVector &ColorsForNewBlock = BlockColors[NewPred];
995         ColorVector &ColorsForOldBlock = BlockColors[PredBB];
996         ColorsForNewBlock = ColorsForOldBlock;
997       }
998     }
999     PredBBs.remove(PredBB);
1000   }
1001 }
1002 
1003 /// When an instruction is found to only be used outside of the loop, this
1004 /// function moves it to the exit blocks and patches up SSA form as needed.
1005 /// This method is guaranteed to remove the original instruction from its
1006 /// position, and may either delete it or move it to outside of the loop.
1007 ///
1008 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1009                  const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
1010                  OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
1011   LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1012   ORE->emit([&]() {
1013     return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1014            << "sinking " << ore::NV("Inst", &I);
1015   });
1016   bool Changed = false;
1017   if (isa<LoadInst>(I))
1018     ++NumMovedLoads;
1019   else if (isa<CallInst>(I))
1020     ++NumMovedCalls;
1021   ++NumSunk;
1022 
1023   // Iterate over users to be ready for actual sinking. Replace users via
1024   // unrechable blocks with undef and make all user PHIs trivially replcable.
1025   SmallPtrSet<Instruction *, 8> VisitedUsers;
1026   for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1027     auto *User = cast<Instruction>(*UI);
1028     Use &U = UI.getUse();
1029     ++UI;
1030 
1031     if (VisitedUsers.count(User) || CurLoop->contains(User))
1032       continue;
1033 
1034     if (!DT->isReachableFromEntry(User->getParent())) {
1035       U = UndefValue::get(I.getType());
1036       Changed = true;
1037       continue;
1038     }
1039 
1040     // The user must be a PHI node.
1041     PHINode *PN = cast<PHINode>(User);
1042 
1043     // Surprisingly, instructions can be used outside of loops without any
1044     // exits.  This can only happen in PHI nodes if the incoming block is
1045     // unreachable.
1046     BasicBlock *BB = PN->getIncomingBlock(U);
1047     if (!DT->isReachableFromEntry(BB)) {
1048       U = UndefValue::get(I.getType());
1049       Changed = true;
1050       continue;
1051     }
1052 
1053     VisitedUsers.insert(PN);
1054     if (isTriviallyReplaceablePHI(*PN, I))
1055       continue;
1056 
1057     if (!canSplitPredecessors(PN, SafetyInfo))
1058       return Changed;
1059 
1060     // Split predecessors of the PHI so that we can make users trivially
1061     // replaceable.
1062     splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
1063 
1064     // Should rebuild the iterators, as they may be invalidated by
1065     // splitPredecessorsOfLoopExit().
1066     UI = I.user_begin();
1067     UE = I.user_end();
1068   }
1069 
1070   if (VisitedUsers.empty())
1071     return Changed;
1072 
1073 #ifndef NDEBUG
1074   SmallVector<BasicBlock *, 32> ExitBlocks;
1075   CurLoop->getUniqueExitBlocks(ExitBlocks);
1076   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1077                                              ExitBlocks.end());
1078 #endif
1079 
1080   // Clones of this instruction. Don't create more than one per exit block!
1081   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1082 
1083   // If this instruction is only used outside of the loop, then all users are
1084   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1085   // the instruction.
1086   SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1087   for (auto *UI : Users) {
1088     auto *User = cast<Instruction>(UI);
1089 
1090     if (CurLoop->contains(User))
1091       continue;
1092 
1093     PHINode *PN = cast<PHINode>(User);
1094     assert(ExitBlockSet.count(PN->getParent()) &&
1095            "The LCSSA PHI is not in an exit block!");
1096     // The PHI must be trivially replaceable.
1097     Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies,
1098                                                           SafetyInfo, CurLoop);
1099     PN->replaceAllUsesWith(New);
1100     PN->eraseFromParent();
1101     Changed = true;
1102   }
1103   return Changed;
1104 }
1105 
1106 /// When an instruction is found to only use loop invariant operands that
1107 /// is safe to hoist, this instruction is called to do the dirty work.
1108 ///
1109 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1110                   LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
1111   auto *Preheader = CurLoop->getLoopPreheader();
1112   LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1113                     << "\n");
1114   ORE->emit([&]() {
1115     return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1116                                                          << ore::NV("Inst", &I);
1117   });
1118 
1119   // Metadata can be dependent on conditions we are hoisting above.
1120   // Conservatively strip all metadata on the instruction unless we were
1121   // guaranteed to execute I if we entered the loop, in which case the metadata
1122   // is valid in the loop preheader.
1123   if (I.hasMetadataOtherThanDebugLoc() &&
1124       // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1125       // time in isGuaranteedToExecute if we don't actually have anything to
1126       // drop.  It is a compile time optimization, not required for correctness.
1127       !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1128     I.dropUnknownNonDebugMetadata();
1129 
1130   // Move the new node to the Preheader, before its terminator.
1131   I.moveBefore(Preheader->getTerminator());
1132 
1133   // Do not retain debug locations when we are moving instructions to different
1134   // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1135   // need to retain their debug locs because they may be inlined.
1136   // FIXME: How do we retain source locations without causing poor debugging
1137   // behavior?
1138   if (!isa<CallInst>(I))
1139     I.setDebugLoc(DebugLoc());
1140 
1141   if (isa<LoadInst>(I))
1142     ++NumMovedLoads;
1143   else if (isa<CallInst>(I))
1144     ++NumMovedCalls;
1145   ++NumHoisted;
1146 }
1147 
1148 /// Only sink or hoist an instruction if it is not a trapping instruction,
1149 /// or if the instruction is known not to trap when moved to the preheader.
1150 /// or if it is a trapping instruction and is guaranteed to execute.
1151 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1152                                            const DominatorTree *DT,
1153                                            const Loop *CurLoop,
1154                                            const LoopSafetyInfo *SafetyInfo,
1155                                            OptimizationRemarkEmitter *ORE,
1156                                            const Instruction *CtxI) {
1157   if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1158     return true;
1159 
1160   bool GuaranteedToExecute =
1161       isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1162 
1163   if (!GuaranteedToExecute) {
1164     auto *LI = dyn_cast<LoadInst>(&Inst);
1165     if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1166       ORE->emit([&]() {
1167         return OptimizationRemarkMissed(
1168                    DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1169                << "failed to hoist load with loop-invariant address "
1170                   "because load is conditionally executed";
1171       });
1172   }
1173 
1174   return GuaranteedToExecute;
1175 }
1176 
1177 namespace {
1178 class LoopPromoter : public LoadAndStorePromoter {
1179   Value *SomePtr; // Designated pointer to store to.
1180   const SmallSetVector<Value *, 8> &PointerMustAliases;
1181   SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1182   SmallVectorImpl<Instruction *> &LoopInsertPts;
1183   PredIteratorCache &PredCache;
1184   AliasSetTracker &AST;
1185   LoopInfo &LI;
1186   DebugLoc DL;
1187   int Alignment;
1188   bool UnorderedAtomic;
1189   AAMDNodes AATags;
1190 
1191   Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1192     if (Instruction *I = dyn_cast<Instruction>(V))
1193       if (Loop *L = LI.getLoopFor(I->getParent()))
1194         if (!L->contains(BB)) {
1195           // We need to create an LCSSA PHI node for the incoming value and
1196           // store that.
1197           PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1198                                         I->getName() + ".lcssa", &BB->front());
1199           for (BasicBlock *Pred : PredCache.get(BB))
1200             PN->addIncoming(I, Pred);
1201           return PN;
1202         }
1203     return V;
1204   }
1205 
1206 public:
1207   LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1208                const SmallSetVector<Value *, 8> &PMA,
1209                SmallVectorImpl<BasicBlock *> &LEB,
1210                SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1211                AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
1212                bool UnorderedAtomic, const AAMDNodes &AATags)
1213       : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1214         LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
1215         LI(li), DL(std::move(dl)), Alignment(alignment),
1216         UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
1217 
1218   bool isInstInList(Instruction *I,
1219                     const SmallVectorImpl<Instruction *> &) const override {
1220     Value *Ptr;
1221     if (LoadInst *LI = dyn_cast<LoadInst>(I))
1222       Ptr = LI->getOperand(0);
1223     else
1224       Ptr = cast<StoreInst>(I)->getPointerOperand();
1225     return PointerMustAliases.count(Ptr);
1226   }
1227 
1228   void doExtraRewritesBeforeFinalDeletion() const override {
1229     // Insert stores after in the loop exit blocks.  Each exit block gets a
1230     // store of the live-out values that feed them.  Since we've already told
1231     // the SSA updater about the defs in the loop and the preheader
1232     // definition, it is all set and we can start using it.
1233     for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1234       BasicBlock *ExitBlock = LoopExitBlocks[i];
1235       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1236       LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1237       Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1238       Instruction *InsertPos = LoopInsertPts[i];
1239       StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1240       if (UnorderedAtomic)
1241         NewSI->setOrdering(AtomicOrdering::Unordered);
1242       NewSI->setAlignment(Alignment);
1243       NewSI->setDebugLoc(DL);
1244       if (AATags)
1245         NewSI->setAAMetadata(AATags);
1246     }
1247   }
1248 
1249   void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1250     // Update alias analysis.
1251     AST.copyValue(LI, V);
1252   }
1253   void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1254 };
1255 
1256 
1257 /// Return true iff we can prove that a caller of this function can not inspect
1258 /// the contents of the provided object in a well defined program.
1259 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1260   if (isa<AllocaInst>(Object))
1261     // Since the alloca goes out of scope, we know the caller can't retain a
1262     // reference to it and be well defined.  Thus, we don't need to check for
1263     // capture.
1264     return true;
1265 
1266   // For all other objects we need to know that the caller can't possibly
1267   // have gotten a reference to the object.  There are two components of
1268   // that:
1269   //   1) Object can't be escaped by this function.  This is what
1270   //      PointerMayBeCaptured checks.
1271   //   2) Object can't have been captured at definition site.  For this, we
1272   //      need to know the return value is noalias.  At the moment, we use a
1273   //      weaker condition and handle only AllocLikeFunctions (which are
1274   //      known to be noalias).  TODO
1275   return isAllocLikeFn(Object, TLI) &&
1276     !PointerMayBeCaptured(Object, true, true);
1277 }
1278 
1279 } // namespace
1280 
1281 /// Try to promote memory values to scalars by sinking stores out of the
1282 /// loop and moving loads to before the loop.  We do this by looping over
1283 /// the stores in the loop, looking for stores to Must pointers which are
1284 /// loop invariant.
1285 ///
1286 bool llvm::promoteLoopAccessesToScalars(
1287     const SmallSetVector<Value *, 8> &PointerMustAliases,
1288     SmallVectorImpl<BasicBlock *> &ExitBlocks,
1289     SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1290     LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1291     Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1292     OptimizationRemarkEmitter *ORE) {
1293   // Verify inputs.
1294   assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1295          CurAST != nullptr && SafetyInfo != nullptr &&
1296          "Unexpected Input to promoteLoopAccessesToScalars");
1297 
1298   Value *SomePtr = *PointerMustAliases.begin();
1299   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1300 
1301   // It is not safe to promote a load/store from the loop if the load/store is
1302   // conditional.  For example, turning:
1303   //
1304   //    for () { if (c) *P += 1; }
1305   //
1306   // into:
1307   //
1308   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
1309   //
1310   // is not safe, because *P may only be valid to access if 'c' is true.
1311   //
1312   // The safety property divides into two parts:
1313   // p1) The memory may not be dereferenceable on entry to the loop.  In this
1314   //    case, we can't insert the required load in the preheader.
1315   // p2) The memory model does not allow us to insert a store along any dynamic
1316   //    path which did not originally have one.
1317   //
1318   // If at least one store is guaranteed to execute, both properties are
1319   // satisfied, and promotion is legal.
1320   //
1321   // This, however, is not a necessary condition. Even if no store/load is
1322   // guaranteed to execute, we can still establish these properties.
1323   // We can establish (p1) by proving that hoisting the load into the preheader
1324   // is safe (i.e. proving dereferenceability on all paths through the loop). We
1325   // can use any access within the alias set to prove dereferenceability,
1326   // since they're all must alias.
1327   //
1328   // There are two ways establish (p2):
1329   // a) Prove the location is thread-local. In this case the memory model
1330   // requirement does not apply, and stores are safe to insert.
1331   // b) Prove a store dominates every exit block. In this case, if an exit
1332   // blocks is reached, the original dynamic path would have taken us through
1333   // the store, so inserting a store into the exit block is safe. Note that this
1334   // is different from the store being guaranteed to execute. For instance,
1335   // if an exception is thrown on the first iteration of the loop, the original
1336   // store is never executed, but the exit blocks are not executed either.
1337 
1338   bool DereferenceableInPH = false;
1339   bool SafeToInsertStore = false;
1340 
1341   SmallVector<Instruction *, 64> LoopUses;
1342 
1343   // We start with an alignment of one and try to find instructions that allow
1344   // us to prove better alignment.
1345   unsigned Alignment = 1;
1346   // Keep track of which types of access we see
1347   bool SawUnorderedAtomic = false;
1348   bool SawNotAtomic = false;
1349   AAMDNodes AATags;
1350 
1351   const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1352 
1353   bool IsKnownThreadLocalObject = false;
1354   if (SafetyInfo->anyBlockMayThrow()) {
1355     // If a loop can throw, we have to insert a store along each unwind edge.
1356     // That said, we can't actually make the unwind edge explicit. Therefore,
1357     // we have to prove that the store is dead along the unwind edge.  We do
1358     // this by proving that the caller can't have a reference to the object
1359     // after return and thus can't possibly load from the object.
1360     Value *Object = GetUnderlyingObject(SomePtr, MDL);
1361     if (!isKnownNonEscaping(Object, TLI))
1362       return false;
1363     // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1364     // visible to other threads if captured and used during their lifetimes.
1365     IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1366   }
1367 
1368   // Check that all of the pointers in the alias set have the same type.  We
1369   // cannot (yet) promote a memory location that is loaded and stored in
1370   // different sizes.  While we are at it, collect alignment and AA info.
1371   for (Value *ASIV : PointerMustAliases) {
1372     // Check that all of the pointers in the alias set have the same type.  We
1373     // cannot (yet) promote a memory location that is loaded and stored in
1374     // different sizes.
1375     if (SomePtr->getType() != ASIV->getType())
1376       return false;
1377 
1378     for (User *U : ASIV->users()) {
1379       // Ignore instructions that are outside the loop.
1380       Instruction *UI = dyn_cast<Instruction>(U);
1381       if (!UI || !CurLoop->contains(UI))
1382         continue;
1383 
1384       // If there is an non-load/store instruction in the loop, we can't promote
1385       // it.
1386       if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1387         if (!Load->isUnordered())
1388           return false;
1389 
1390         SawUnorderedAtomic |= Load->isAtomic();
1391         SawNotAtomic |= !Load->isAtomic();
1392 
1393         if (!DereferenceableInPH)
1394           DereferenceableInPH = isSafeToExecuteUnconditionally(
1395               *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
1396       } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1397         // Stores *of* the pointer are not interesting, only stores *to* the
1398         // pointer.
1399         if (UI->getOperand(1) != ASIV)
1400           continue;
1401         if (!Store->isUnordered())
1402           return false;
1403 
1404         SawUnorderedAtomic |= Store->isAtomic();
1405         SawNotAtomic |= !Store->isAtomic();
1406 
1407         // If the store is guaranteed to execute, both properties are satisfied.
1408         // We may want to check if a store is guaranteed to execute even if we
1409         // already know that promotion is safe, since it may have higher
1410         // alignment than any other guaranteed stores, in which case we can
1411         // raise the alignment on the promoted store.
1412         unsigned InstAlignment = Store->getAlignment();
1413         if (!InstAlignment)
1414           InstAlignment =
1415               MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1416 
1417         if (!DereferenceableInPH || !SafeToInsertStore ||
1418             (InstAlignment > Alignment)) {
1419           if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
1420             DereferenceableInPH = true;
1421             SafeToInsertStore = true;
1422             Alignment = std::max(Alignment, InstAlignment);
1423           }
1424         }
1425 
1426         // If a store dominates all exit blocks, it is safe to sink.
1427         // As explained above, if an exit block was executed, a dominating
1428         // store must have been executed at least once, so we are not
1429         // introducing stores on paths that did not have them.
1430         // Note that this only looks at explicit exit blocks. If we ever
1431         // start sinking stores into unwind edges (see above), this will break.
1432         if (!SafeToInsertStore)
1433           SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1434             return DT->dominates(Store->getParent(), Exit);
1435           });
1436 
1437         // If the store is not guaranteed to execute, we may still get
1438         // deref info through it.
1439         if (!DereferenceableInPH) {
1440           DereferenceableInPH = isDereferenceableAndAlignedPointer(
1441               Store->getPointerOperand(), Store->getAlignment(), MDL,
1442               Preheader->getTerminator(), DT);
1443         }
1444       } else
1445         return false; // Not a load or store.
1446 
1447       // Merge the AA tags.
1448       if (LoopUses.empty()) {
1449         // On the first load/store, just take its AA tags.
1450         UI->getAAMetadata(AATags);
1451       } else if (AATags) {
1452         UI->getAAMetadata(AATags, /* Merge = */ true);
1453       }
1454 
1455       LoopUses.push_back(UI);
1456     }
1457   }
1458 
1459   // If we found both an unordered atomic instruction and a non-atomic memory
1460   // access, bail.  We can't blindly promote non-atomic to atomic since we
1461   // might not be able to lower the result.  We can't downgrade since that
1462   // would violate memory model.  Also, align 0 is an error for atomics.
1463   if (SawUnorderedAtomic && SawNotAtomic)
1464     return false;
1465 
1466   // If we couldn't prove we can hoist the load, bail.
1467   if (!DereferenceableInPH)
1468     return false;
1469 
1470   // We know we can hoist the load, but don't have a guaranteed store.
1471   // Check whether the location is thread-local. If it is, then we can insert
1472   // stores along paths which originally didn't have them without violating the
1473   // memory model.
1474   if (!SafeToInsertStore) {
1475     if (IsKnownThreadLocalObject)
1476       SafeToInsertStore = true;
1477     else {
1478       Value *Object = GetUnderlyingObject(SomePtr, MDL);
1479       SafeToInsertStore =
1480           (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1481           !PointerMayBeCaptured(Object, true, true);
1482     }
1483   }
1484 
1485   // If we've still failed to prove we can sink the store, give up.
1486   if (!SafeToInsertStore)
1487     return false;
1488 
1489   // Otherwise, this is safe to promote, lets do it!
1490   LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1491                     << '\n');
1492   ORE->emit([&]() {
1493     return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1494                               LoopUses[0])
1495            << "Moving accesses to memory location out of the loop";
1496   });
1497   ++NumPromoted;
1498 
1499   // Grab a debug location for the inserted loads/stores; given that the
1500   // inserted loads/stores have little relation to the original loads/stores,
1501   // this code just arbitrarily picks a location from one, since any debug
1502   // location is better than none.
1503   DebugLoc DL = LoopUses[0]->getDebugLoc();
1504 
1505   // We use the SSAUpdater interface to insert phi nodes as required.
1506   SmallVector<PHINode *, 16> NewPHIs;
1507   SSAUpdater SSA(&NewPHIs);
1508   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1509                         InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1510                         SawUnorderedAtomic, AATags);
1511 
1512   // Set up the preheader to have a definition of the value.  It is the live-out
1513   // value from the preheader that uses in the loop will use.
1514   LoadInst *PreheaderLoad = new LoadInst(
1515       SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1516   if (SawUnorderedAtomic)
1517     PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1518   PreheaderLoad->setAlignment(Alignment);
1519   PreheaderLoad->setDebugLoc(DL);
1520   if (AATags)
1521     PreheaderLoad->setAAMetadata(AATags);
1522   SSA.AddAvailableValue(Preheader, PreheaderLoad);
1523 
1524   // Rewrite all the loads in the loop and remember all the definitions from
1525   // stores in the loop.
1526   Promoter.run(LoopUses);
1527 
1528   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1529   if (PreheaderLoad->use_empty())
1530     PreheaderLoad->eraseFromParent();
1531 
1532   return true;
1533 }
1534 
1535 /// Returns an owning pointer to an alias set which incorporates aliasing info
1536 /// from L and all subloops of L.
1537 /// FIXME: In new pass manager, there is no helper function to handle loop
1538 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
1539 /// from scratch for every loop. Hook up with the helper functions when
1540 /// available in the new pass manager to avoid redundant computation.
1541 std::unique_ptr<AliasSetTracker>
1542 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1543                                                  AliasAnalysis *AA) {
1544   std::unique_ptr<AliasSetTracker> CurAST;
1545   SmallVector<Loop *, 4> RecomputeLoops;
1546   auto mergeLoop = [&CurAST](Loop *L) {
1547     // Loop over the body of this loop, looking for calls, invokes, and stores.
1548     for (BasicBlock *BB : L->blocks())
1549       CurAST->add(*BB); // Incorporate the specified basic block
1550   };
1551   for (Loop *InnerL : L->getSubLoops()) {
1552     auto MapI = LoopToAliasSetMap.find(InnerL);
1553     // If the AST for this inner loop is missing it may have been merged into
1554     // some other loop's AST and then that loop unrolled, and so we need to
1555     // recompute it.
1556     if (MapI == LoopToAliasSetMap.end()) {
1557       RecomputeLoops.push_back(InnerL);
1558       continue;
1559     }
1560     std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
1561 
1562     if (CurAST) {
1563       // What if InnerLoop was modified by other passes ?
1564       // Once we've incorporated the inner loop's AST into ours, we don't need
1565       // the subloop's anymore.
1566       CurAST->add(*InnerAST);
1567     } else {
1568       CurAST = std::move(InnerAST);
1569     }
1570     LoopToAliasSetMap.erase(MapI);
1571   }
1572   if (!CurAST)
1573     CurAST = make_unique<AliasSetTracker>(*AA);
1574 
1575   // Add everything from the sub loops that are no longer directly available.
1576   for (Loop *InnerL : RecomputeLoops)
1577     mergeLoop(InnerL);
1578 
1579   // And merge in this loop.
1580   mergeLoop(L);
1581 
1582   return CurAST;
1583 }
1584 
1585 /// Simple analysis hook. Clone alias set info.
1586 ///
1587 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1588                                              Loop *L) {
1589   auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
1590   if (ASTIt == LICM.getLoopToAliasSetMap().end())
1591     return;
1592 
1593   ASTIt->second->copyValue(From, To);
1594 }
1595 
1596 /// Simple Analysis hook. Delete value V from alias set
1597 ///
1598 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1599   auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
1600   if (ASTIt == LICM.getLoopToAliasSetMap().end())
1601     return;
1602 
1603   ASTIt->second->deleteValue(V);
1604 }
1605 
1606 /// Simple Analysis hook. Delete value L from alias set map.
1607 ///
1608 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1609   if (!LICM.getLoopToAliasSetMap().count(L))
1610     return;
1611 
1612   LICM.getLoopToAliasSetMap().erase(L);
1613 }
1614 
1615 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
1616                                      AliasSetTracker *CurAST, Loop *CurLoop,
1617                                      AliasAnalysis *AA) {
1618   // First check to see if any of the basic blocks in CurLoop invalidate *V.
1619   bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
1620 
1621   if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
1622     return isInvalidatedAccordingToAST;
1623 
1624   // Check with a diagnostic analysis if we can refine the information above.
1625   // This is to identify the limitations of using the AST.
1626   // The alias set mechanism used by LICM has a major weakness in that it
1627   // combines all things which may alias into a single set *before* asking
1628   // modref questions. As a result, a single readonly call within a loop will
1629   // collapse all loads and stores into a single alias set and report
1630   // invalidation if the loop contains any store. For example, readonly calls
1631   // with deopt states have this form and create a general alias set with all
1632   // loads and stores.  In order to get any LICM in loops containing possible
1633   // deopt states we need a more precise invalidation of checking the mod ref
1634   // info of each instruction within the loop and LI. This has a complexity of
1635   // O(N^2), so currently, it is used only as a diagnostic tool since the
1636   // default value of LICMN2Threshold is zero.
1637 
1638   // Don't look at nested loops.
1639   if (CurLoop->begin() != CurLoop->end())
1640     return true;
1641 
1642   int N = 0;
1643   for (BasicBlock *BB : CurLoop->getBlocks())
1644     for (Instruction &I : *BB) {
1645       if (N >= LICMN2Theshold) {
1646         LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "
1647                           << *(MemLoc.Ptr) << "\n");
1648         return true;
1649       }
1650       N++;
1651       auto Res = AA->getModRefInfo(&I, MemLoc);
1652       if (isModSet(Res)) {
1653         LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "
1654                           << *(MemLoc.Ptr) << "\n");
1655         return true;
1656       }
1657     }
1658   LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n");
1659   return false;
1660 }
1661 
1662 /// Little predicate that returns true if the specified basic block is in
1663 /// a subloop of the current one, not the current one itself.
1664 ///
1665 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1666   assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1667   return LI->getLoopFor(BB) != CurLoop;
1668 }
1669