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