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