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