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