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