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