1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible.  It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe.  This pass also promotes must-aliased memory locations in the loop to
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
15 //
16 // This pass uses alias analysis for two purposes:
17 //
18 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
19 //     that a load or call inside of a loop never aliases anything stored to,
20 //     we can hoist it or sink it like any other instruction.
21 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
22 //     the loop, we try to move the store to happen AFTER the loop instead of
23 //     inside of the loop.  This can only happen if a few conditions are true:
24 //       A. The pointer stored through is loop invariant
25 //       B. There are no stores or loads in the loop which _may_ alias the
26 //          pointer.  There are no calls in the loop which mod/ref the pointer.
27 //     If these conditions are true, we can promote the loads and stores in the
28 //     loop of the pointer to use a temporary alloca'd variable.  We then use
29 //     the SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32 
33 #include "llvm/Transforms/Scalar/LICM.h"
34 #include "llvm/ADT/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/Loads.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/LoopPass.h"
44 #include "llvm/Analysis/MemoryBuiltins.h"
45 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
46 #include "llvm/Analysis/ScalarEvolution.h"
47 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/IR/CFG.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/PredIteratorCache.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Scalar/LoopPassManager.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include "llvm/Transforms/Utils/LoopUtils.h"
67 #include "llvm/Transforms/Utils/SSAUpdater.h"
68 #include <algorithm>
69 #include <utility>
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "licm"
73 
74 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
75 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
76 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
77 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
78 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
79 
80 /// Memory promotion is enabled by default.
81 static cl::opt<bool>
82     DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
83                      cl::desc("Disable memory promotion in LICM pass"));
84 
85 static cl::opt<uint32_t> MaxNumUsesTraversed(
86     "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
87     cl::desc("Max num uses visited for identifying load "
88              "invariance in loop using invariant start (default = 8)"));
89 
90 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
91 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
92                             const LoopSafetyInfo *SafetyInfo);
93 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
94                   const LoopSafetyInfo *SafetyInfo,
95                   OptimizationRemarkEmitter *ORE);
96 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
97                  const Loop *CurLoop, AliasSetTracker *CurAST,
98                  const LoopSafetyInfo *SafetyInfo,
99                  OptimizationRemarkEmitter *ORE);
100 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
101                                            const DominatorTree *DT,
102                                            const Loop *CurLoop,
103                                            const LoopSafetyInfo *SafetyInfo,
104                                            OptimizationRemarkEmitter *ORE,
105                                            const Instruction *CtxI = nullptr);
106 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
107                                      const AAMDNodes &AAInfo,
108                                      AliasSetTracker *CurAST);
109 static Instruction *
110 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
111                             const LoopInfo *LI,
112                             const LoopSafetyInfo *SafetyInfo);
113 
114 namespace {
115 struct LoopInvariantCodeMotion {
116   bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
117                  TargetLibraryInfo *TLI, ScalarEvolution *SE,
118                  OptimizationRemarkEmitter *ORE, bool DeleteAST);
119 
120   DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
121     return LoopToAliasSetMap;
122   }
123 
124 private:
125   DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
126 
127   AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
128                                            AliasAnalysis *AA);
129 };
130 
131 struct LegacyLICMPass : public LoopPass {
132   static char ID; // Pass identification, replacement for typeid
133   LegacyLICMPass() : LoopPass(ID) {
134     initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
135   }
136 
137   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
138     if (skipLoop(L)) {
139       // If we have run LICM on a previous loop but now we are skipping
140       // (because we've hit the opt-bisect limit), we need to clear the
141       // loop alias information.
142       for (auto &LTAS : LICM.getLoopToAliasSetMap())
143         delete LTAS.second;
144       LICM.getLoopToAliasSetMap().clear();
145       return false;
146     }
147 
148     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
149     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
150     // pass.  Function analyses need to be preserved across loop transformations
151     // but ORE cannot be preserved (see comment before the pass definition).
152     OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
153     return LICM.runOnLoop(L,
154                           &getAnalysis<AAResultsWrapperPass>().getAAResults(),
155                           &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
156                           &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
157                           &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
158                           SE ? &SE->getSE() : nullptr, &ORE, false);
159   }
160 
161   /// This transformation requires natural loop information & requires that
162   /// loop preheaders be inserted into the CFG...
163   ///
164   void getAnalysisUsage(AnalysisUsage &AU) const override {
165     AU.setPreservesCFG();
166     AU.addRequired<TargetLibraryInfoWrapperPass>();
167     getLoopAnalysisUsage(AU);
168   }
169 
170   using llvm::Pass::doFinalization;
171 
172   bool doFinalization() override {
173     assert(LICM.getLoopToAliasSetMap().empty() &&
174            "Didn't free loop alias sets");
175     return false;
176   }
177 
178 private:
179   LoopInvariantCodeMotion LICM;
180 
181   /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
182   void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
183                                Loop *L) override;
184 
185   /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
186   /// set.
187   void deleteAnalysisValue(Value *V, Loop *L) override;
188 
189   /// Simple Analysis hook. Delete loop L from alias set map.
190   void deleteAnalysisLoop(Loop *L) override;
191 };
192 }
193 
194 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
195                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
196   const auto &FAM =
197       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
198   Function *F = L.getHeader()->getParent();
199 
200   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
201   // FIXME: This should probably be optional rather than required.
202   if (!ORE)
203     report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
204                        "cached at a higher level");
205 
206   LoopInvariantCodeMotion LICM;
207   if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, ORE, true))
208     return PreservedAnalyses::all();
209 
210   auto PA = getLoopPassPreservedAnalyses();
211   PA.preserveSet<CFGAnalyses>();
212   return PA;
213 }
214 
215 char LegacyLICMPass::ID = 0;
216 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
217                       false, false)
218 INITIALIZE_PASS_DEPENDENCY(LoopPass)
219 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
220 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
221                     false)
222 
223 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
224 
225 /// Hoist expressions out of the specified loop. Note, alias info for inner
226 /// loop is not preserved so it is not a good idea to run LICM multiple
227 /// times on one loop.
228 /// We should delete AST for inner loops in the new pass manager to avoid
229 /// memory leak.
230 ///
231 bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
232                                         LoopInfo *LI, DominatorTree *DT,
233                                         TargetLibraryInfo *TLI,
234                                         ScalarEvolution *SE,
235                                         OptimizationRemarkEmitter *ORE,
236                                         bool DeleteAST) {
237   bool Changed = false;
238 
239   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
240 
241   AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
242 
243   // Get the preheader block to move instructions into...
244   BasicBlock *Preheader = L->getLoopPreheader();
245 
246   // Compute loop safety information.
247   LoopSafetyInfo SafetyInfo;
248   computeLoopSafetyInfo(&SafetyInfo, L);
249 
250   // We want to visit all of the instructions in this loop... that are not parts
251   // of our subloops (they have already had their invariants hoisted out of
252   // their loop, into this loop, so there is no need to process the BODIES of
253   // the subloops).
254   //
255   // Traverse the body of the loop in depth first order on the dominator tree so
256   // that we are guaranteed to see definitions before we see uses.  This allows
257   // us to sink instructions in one pass, without iteration.  After sinking
258   // instructions, we perform another pass to hoist them out of the loop.
259   //
260   if (L->hasDedicatedExits())
261     Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
262                           CurAST, &SafetyInfo, ORE);
263   if (Preheader)
264     Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
265                            CurAST, &SafetyInfo, ORE);
266 
267   // Now that all loop invariants have been removed from the loop, promote any
268   // memory references to scalars that we can.
269   // Don't sink stores from loops without dedicated block exits. Exits
270   // containing indirect branches are not transformed by loop simplify,
271   // make sure we catch that. An additional load may be generated in the
272   // preheader for SSA updater, so also avoid sinking when no preheader
273   // is available.
274   if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
275     // Figure out the loop exits and their insertion points
276     SmallVector<BasicBlock *, 8> ExitBlocks;
277     L->getUniqueExitBlocks(ExitBlocks);
278 
279     // We can't insert into a catchswitch.
280     bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
281       return isa<CatchSwitchInst>(Exit->getTerminator());
282     });
283 
284     if (!HasCatchSwitch) {
285       SmallVector<Instruction *, 8> InsertPts;
286       InsertPts.reserve(ExitBlocks.size());
287       for (BasicBlock *ExitBlock : ExitBlocks)
288         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
289 
290       PredIteratorCache PIC;
291 
292       bool Promoted = false;
293 
294       // Loop over all of the alias sets in the tracker object.
295       for (AliasSet &AS : *CurAST)
296         Promoted |=
297             promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT,
298                                          TLI, L, CurAST, &SafetyInfo, ORE);
299 
300       // Once we have promoted values across the loop body we have to
301       // recursively reform LCSSA as any nested loop may now have values defined
302       // within the loop used in the outer loop.
303       // FIXME: This is really heavy handed. It would be a bit better to use an
304       // SSAUpdater strategy during promotion that was LCSSA aware and reformed
305       // it as it went.
306       if (Promoted)
307         formLCSSARecursively(*L, *DT, LI, SE);
308 
309       Changed |= Promoted;
310     }
311   }
312 
313   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
314   // specifically moving instructions across the loop boundary and so it is
315   // especially in need of sanity checking here.
316   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
317   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
318          "Parent loop not left in LCSSA form after LICM!");
319 
320   // If this loop is nested inside of another one, save the alias information
321   // for when we process the outer loop.
322   if (L->getParentLoop() && !DeleteAST)
323     LoopToAliasSetMap[L] = CurAST;
324   else
325     delete CurAST;
326 
327   if (Changed && SE)
328     SE->forgetLoopDispositions(L);
329   return Changed;
330 }
331 
332 /// Walk the specified region of the CFG (defined by all blocks dominated by
333 /// the specified block, and that are in the current loop) in reverse depth
334 /// first order w.r.t the DominatorTree.  This allows us to visit uses before
335 /// definitions, allowing us to sink a loop body in one pass without iteration.
336 ///
337 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
338                       DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
339                       AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
340                       OptimizationRemarkEmitter *ORE) {
341 
342   // Verify inputs.
343   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
344          CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
345          "Unexpected input to sinkRegion");
346 
347   BasicBlock *BB = N->getBlock();
348   // If this subregion is not in the top level loop at all, exit.
349   if (!CurLoop->contains(BB))
350     return false;
351 
352   // We are processing blocks in reverse dfo, so process children first.
353   bool Changed = false;
354   const std::vector<DomTreeNode *> &Children = N->getChildren();
355   for (DomTreeNode *Child : Children)
356     Changed |=
357         sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE);
358 
359   // Only need to process the contents of this block if it is not part of a
360   // subloop (which would already have been processed).
361   if (inSubLoop(BB, CurLoop, LI))
362     return Changed;
363 
364   for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
365     Instruction &I = *--II;
366 
367     // If the instruction is dead, we would try to sink it because it isn't used
368     // in the loop, instead, just delete it.
369     if (isInstructionTriviallyDead(&I, TLI)) {
370       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
371       ++II;
372       CurAST->deleteValue(&I);
373       I.eraseFromParent();
374       Changed = true;
375       continue;
376     }
377 
378     // Check to see if we can sink this instruction to the exit blocks
379     // of the loop.  We can do this if the all users of the instruction are
380     // outside of the loop.  In this case, it doesn't even matter if the
381     // operands of the instruction are loop invariant.
382     //
383     if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
384         canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
385       ++II;
386       Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo, ORE);
387     }
388   }
389   return Changed;
390 }
391 
392 /// Walk the specified region of the CFG (defined by all blocks dominated by
393 /// the specified block, and that are in the current loop) in depth first
394 /// order w.r.t the DominatorTree.  This allows us to visit definitions before
395 /// uses, allowing us to hoist a loop body in one pass without iteration.
396 ///
397 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
398                        DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
399                        AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
400                        OptimizationRemarkEmitter *ORE) {
401   // Verify inputs.
402   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
403          CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
404          "Unexpected input to hoistRegion");
405 
406   BasicBlock *BB = N->getBlock();
407 
408   // If this subregion is not in the top level loop at all, exit.
409   if (!CurLoop->contains(BB))
410     return false;
411 
412   // Only need to process the contents of this block if it is not part of a
413   // subloop (which would already have been processed).
414   bool Changed = false;
415   if (!inSubLoop(BB, CurLoop, LI))
416     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
417       Instruction &I = *II++;
418       // Try constant folding this instruction.  If all the operands are
419       // constants, it is technically hoistable, but it would be better to just
420       // fold it.
421       if (Constant *C = ConstantFoldInstruction(
422               &I, I.getModule()->getDataLayout(), TLI)) {
423         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
424         CurAST->copyValue(&I, C);
425         I.replaceAllUsesWith(C);
426         if (isInstructionTriviallyDead(&I, TLI)) {
427           CurAST->deleteValue(&I);
428           I.eraseFromParent();
429         }
430         Changed = true;
431         continue;
432       }
433 
434       // Try hoisting the instruction out to the preheader.  We can only do this
435       // if all of the operands of the instruction are loop invariant and if it
436       // is safe to hoist the instruction.
437       //
438       if (CurLoop->hasLoopInvariantOperands(&I) &&
439           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
440           isSafeToExecuteUnconditionally(
441               I, DT, CurLoop, SafetyInfo, ORE,
442               CurLoop->getLoopPreheader()->getTerminator()))
443         Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
444     }
445 
446   const std::vector<DomTreeNode *> &Children = N->getChildren();
447   for (DomTreeNode *Child : Children)
448     Changed |=
449         hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE);
450   return Changed;
451 }
452 
453 /// Computes loop safety information, checks loop body & header
454 /// for the possibility of may throw exception.
455 ///
456 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
457   assert(CurLoop != nullptr && "CurLoop cant be null");
458   BasicBlock *Header = CurLoop->getHeader();
459   // Setting default safety values.
460   SafetyInfo->MayThrow = false;
461   SafetyInfo->HeaderMayThrow = false;
462   // Iterate over header and compute safety info.
463   for (BasicBlock::iterator I = Header->begin(), E = Header->end();
464        (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
465     SafetyInfo->HeaderMayThrow |=
466         !isGuaranteedToTransferExecutionToSuccessor(&*I);
467 
468   SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
469   // Iterate over loop instructions and compute safety info.
470   // Skip header as it has been computed and stored in HeaderMayThrow.
471   // The first block in loopinfo.Blocks is guaranteed to be the header.
472   assert(Header == *CurLoop->getBlocks().begin() && "First block must be header");
473   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
474                             BBE = CurLoop->block_end();
475        (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
476     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
477          (I != E) && !SafetyInfo->MayThrow; ++I)
478       SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
479 
480   // Compute funclet colors if we might sink/hoist in a function with a funclet
481   // personality routine.
482   Function *Fn = CurLoop->getHeader()->getParent();
483   if (Fn->hasPersonalityFn())
484     if (Constant *PersonalityFn = Fn->getPersonalityFn())
485       if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
486         SafetyInfo->BlockColors = colorEHFunclets(*Fn);
487 }
488 
489 // Return true if LI is invariant within scope of the loop. LI is invariant if
490 // CurLoop is dominated by an invariant.start representing the same memory location
491 // and size as the memory location LI loads from, and also the invariant.start
492 // has no uses.
493 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
494                                   Loop *CurLoop) {
495   Value *Addr = LI->getOperand(0);
496   const DataLayout &DL = LI->getModule()->getDataLayout();
497   const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
498       cast<PointerType>(Addr->getType())->getElementType());
499 
500   // if the type is i8 addrspace(x)*, we know this is the type of
501   // llvm.invariant.start operand
502   auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
503                                      LI->getPointerAddressSpace());
504   unsigned BitcastsVisited = 0;
505   // Look through bitcasts until we reach the i8* type (this is invariant.start
506   // operand type).
507   while (Addr->getType() != PtrInt8Ty) {
508     auto *BC = dyn_cast<BitCastInst>(Addr);
509     // Avoid traversing high number of bitcast uses.
510     if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
511       return false;
512     Addr = BC->getOperand(0);
513   }
514 
515   unsigned UsesVisited = 0;
516   // Traverse all uses of the load operand value, to see if invariant.start is
517   // one of the uses, and whether it dominates the load instruction.
518   for (auto *U : Addr->users()) {
519     // Avoid traversing for Load operand with high number of users.
520     if (++UsesVisited > MaxNumUsesTraversed)
521       return false;
522     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
523     // If there are escaping uses of invariant.start instruction, the load maybe
524     // non-invariant.
525     if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
526         II->hasNUsesOrMore(1))
527       continue;
528     unsigned InvariantSizeInBits =
529         cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
530     // Confirm the invariant.start location size contains the load operand size
531     // in bits. Also, the invariant.start should dominate the load, and we
532     // should not hoist the load out of a loop that contains this dominating
533     // invariant.start.
534     if (LocSizeInBits <= InvariantSizeInBits &&
535         DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
536       return true;
537   }
538 
539   return false;
540 }
541 
542 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
543                               Loop *CurLoop, AliasSetTracker *CurAST,
544                               LoopSafetyInfo *SafetyInfo,
545                               OptimizationRemarkEmitter *ORE) {
546   // Loads have extra constraints we have to verify before we can hoist them.
547   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
548     if (!LI->isUnordered())
549       return false; // Don't hoist volatile/atomic loads!
550 
551     // Loads from constant memory are always safe to move, even if they end up
552     // in the same alias set as something that ends up being modified.
553     if (AA->pointsToConstantMemory(LI->getOperand(0)))
554       return true;
555     if (LI->getMetadata(LLVMContext::MD_invariant_load))
556       return true;
557 
558     // This checks for an invariant.start dominating the load.
559     if (isLoadInvariantInLoop(LI, DT, CurLoop))
560       return true;
561 
562     // Don't hoist loads which have may-aliased stores in loop.
563     uint64_t Size = 0;
564     if (LI->getType()->isSized())
565       Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
566 
567     AAMDNodes AAInfo;
568     LI->getAAMetadata(AAInfo);
569 
570     bool Invalidated =
571         pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
572     // Check loop-invariant address because this may also be a sinkable load
573     // whose address is not necessarily loop-invariant.
574     if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
575       ORE->emit(OptimizationRemarkMissed(
576                     DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
577                 << "failed to move load with loop-invariant address "
578                    "because the loop may invalidate its value");
579 
580     return !Invalidated;
581   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
582     // Don't sink or hoist dbg info; it's legal, but not useful.
583     if (isa<DbgInfoIntrinsic>(I))
584       return false;
585 
586     // Don't sink calls which can throw.
587     if (CI->mayThrow())
588       return false;
589 
590     // Handle simple cases by querying alias analysis.
591     FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
592     if (Behavior == FMRB_DoesNotAccessMemory)
593       return true;
594     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
595       // A readonly argmemonly function only reads from memory pointed to by
596       // it's arguments with arbitrary offsets.  If we can prove there are no
597       // writes to this memory in the loop, we can hoist or sink.
598       if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
599         for (Value *Op : CI->arg_operands())
600           if (Op->getType()->isPointerTy() &&
601               pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
602                                        AAMDNodes(), CurAST))
603             return false;
604         return true;
605       }
606       // If this call only reads from memory and there are no writes to memory
607       // in the loop, we can hoist or sink the call as appropriate.
608       bool FoundMod = false;
609       for (AliasSet &AS : *CurAST) {
610         if (!AS.isForwardingAliasSet() && AS.isMod()) {
611           FoundMod = true;
612           break;
613         }
614       }
615       if (!FoundMod)
616         return true;
617     }
618 
619     // FIXME: This should use mod/ref information to see if we can hoist or
620     // sink the call.
621 
622     return false;
623   }
624 
625   // Only these instructions are hoistable/sinkable.
626   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
627       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
628       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
629       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
630       !isa<InsertValueInst>(I))
631     return false;
632 
633   // SafetyInfo is nullptr if we are checking for sinking from preheader to
634   // loop body. It will be always safe as there is no speculative execution.
635   if (!SafetyInfo)
636     return true;
637 
638   // TODO: Plumb the context instruction through to make hoisting and sinking
639   // more powerful. Hoisting of loads already works due to the special casing
640   // above.
641   return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
642 }
643 
644 /// Returns true if a PHINode is a trivially replaceable with an
645 /// Instruction.
646 /// This is true when all incoming values are that instruction.
647 /// This pattern occurs most often with LCSSA PHI nodes.
648 ///
649 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
650   for (const Value *IncValue : PN.incoming_values())
651     if (IncValue != &I)
652       return false;
653 
654   return true;
655 }
656 
657 /// Return true if the only users of this instruction are outside of
658 /// the loop. If this is true, we can sink the instruction to the exit
659 /// blocks of the loop.
660 ///
661 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
662                             const LoopSafetyInfo *SafetyInfo) {
663   const auto &BlockColors = SafetyInfo->BlockColors;
664   for (const User *U : I.users()) {
665     const Instruction *UI = cast<Instruction>(U);
666     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
667       const BasicBlock *BB = PN->getParent();
668       // We cannot sink uses in catchswitches.
669       if (isa<CatchSwitchInst>(BB->getTerminator()))
670         return false;
671 
672       // We need to sink a callsite to a unique funclet.  Avoid sinking if the
673       // phi use is too muddled.
674       if (isa<CallInst>(I))
675         if (!BlockColors.empty() &&
676             BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
677           return false;
678 
679       // A PHI node where all of the incoming values are this instruction are
680       // special -- they can just be RAUW'ed with the instruction and thus
681       // don't require a use in the predecessor. This is a particular important
682       // special case because it is the pattern found in LCSSA form.
683       if (isTriviallyReplacablePHI(*PN, I)) {
684         if (CurLoop->contains(PN))
685           return false;
686         else
687           continue;
688       }
689 
690       // Otherwise, PHI node uses occur in predecessor blocks if the incoming
691       // values. Check for such a use being inside the loop.
692       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
693         if (PN->getIncomingValue(i) == &I)
694           if (CurLoop->contains(PN->getIncomingBlock(i)))
695             return false;
696 
697       continue;
698     }
699 
700     if (CurLoop->contains(UI))
701       return false;
702   }
703   return true;
704 }
705 
706 static Instruction *
707 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
708                             const LoopInfo *LI,
709                             const LoopSafetyInfo *SafetyInfo) {
710   Instruction *New;
711   if (auto *CI = dyn_cast<CallInst>(&I)) {
712     const auto &BlockColors = SafetyInfo->BlockColors;
713 
714     // Sinking call-sites need to be handled differently from other
715     // instructions.  The cloned call-site needs a funclet bundle operand
716     // appropriate for it's location in the CFG.
717     SmallVector<OperandBundleDef, 1> OpBundles;
718     for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
719          BundleIdx != BundleEnd; ++BundleIdx) {
720       OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
721       if (Bundle.getTagID() == LLVMContext::OB_funclet)
722         continue;
723 
724       OpBundles.emplace_back(Bundle);
725     }
726 
727     if (!BlockColors.empty()) {
728       const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
729       assert(CV.size() == 1 && "non-unique color for exit block!");
730       BasicBlock *BBColor = CV.front();
731       Instruction *EHPad = BBColor->getFirstNonPHI();
732       if (EHPad->isEHPad())
733         OpBundles.emplace_back("funclet", EHPad);
734     }
735 
736     New = CallInst::Create(CI, OpBundles);
737   } else {
738     New = I.clone();
739   }
740 
741   ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
742   if (!I.getName().empty())
743     New->setName(I.getName() + ".le");
744 
745   // Build LCSSA PHI nodes for any in-loop operands. Note that this is
746   // particularly cheap because we can rip off the PHI node that we're
747   // replacing for the number and blocks of the predecessors.
748   // OPT: If this shows up in a profile, we can instead finish sinking all
749   // invariant instructions, and then walk their operands to re-establish
750   // LCSSA. That will eliminate creating PHI nodes just to nuke them when
751   // sinking bottom-up.
752   for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
753        ++OI)
754     if (Instruction *OInst = dyn_cast<Instruction>(*OI))
755       if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
756         if (!OLoop->contains(&PN)) {
757           PHINode *OpPN =
758               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
759                               OInst->getName() + ".lcssa", &ExitBlock.front());
760           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
761             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
762           *OI = OpPN;
763         }
764   return New;
765 }
766 
767 /// When an instruction is found to only be used outside of the loop, this
768 /// function moves it to the exit blocks and patches up SSA form as needed.
769 /// This method is guaranteed to remove the original instruction from its
770 /// position, and may either delete it or move it to outside of the loop.
771 ///
772 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
773                  const Loop *CurLoop, AliasSetTracker *CurAST,
774                  const LoopSafetyInfo *SafetyInfo,
775                  OptimizationRemarkEmitter *ORE) {
776   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
777   ORE->emit(OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
778             << "sinking " << ore::NV("Inst", &I));
779   bool Changed = false;
780   if (isa<LoadInst>(I))
781     ++NumMovedLoads;
782   else if (isa<CallInst>(I))
783     ++NumMovedCalls;
784   ++NumSunk;
785   Changed = true;
786 
787 #ifndef NDEBUG
788   SmallVector<BasicBlock *, 32> ExitBlocks;
789   CurLoop->getUniqueExitBlocks(ExitBlocks);
790   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
791                                              ExitBlocks.end());
792 #endif
793 
794   // Clones of this instruction. Don't create more than one per exit block!
795   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
796 
797   // If this instruction is only used outside of the loop, then all users are
798   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
799   // the instruction.
800   while (!I.use_empty()) {
801     Value::user_iterator UI = I.user_begin();
802     auto *User = cast<Instruction>(*UI);
803     if (!DT->isReachableFromEntry(User->getParent())) {
804       User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
805       continue;
806     }
807     // The user must be a PHI node.
808     PHINode *PN = cast<PHINode>(User);
809 
810     // Surprisingly, instructions can be used outside of loops without any
811     // exits.  This can only happen in PHI nodes if the incoming block is
812     // unreachable.
813     Use &U = UI.getUse();
814     BasicBlock *BB = PN->getIncomingBlock(U);
815     if (!DT->isReachableFromEntry(BB)) {
816       U = UndefValue::get(I.getType());
817       continue;
818     }
819 
820     BasicBlock *ExitBlock = PN->getParent();
821     assert(ExitBlockSet.count(ExitBlock) &&
822            "The LCSSA PHI is not in an exit block!");
823 
824     Instruction *New;
825     auto It = SunkCopies.find(ExitBlock);
826     if (It != SunkCopies.end())
827       New = It->second;
828     else
829       New = SunkCopies[ExitBlock] =
830           CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
831 
832     PN->replaceAllUsesWith(New);
833     PN->eraseFromParent();
834   }
835 
836   CurAST->deleteValue(&I);
837   I.eraseFromParent();
838   return Changed;
839 }
840 
841 /// When an instruction is found to only use loop invariant operands that
842 /// is safe to hoist, this instruction is called to do the dirty work.
843 ///
844 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
845                   const LoopSafetyInfo *SafetyInfo,
846                   OptimizationRemarkEmitter *ORE) {
847   auto *Preheader = CurLoop->getLoopPreheader();
848   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
849                << "\n");
850   ORE->emit(OptimizationRemark(DEBUG_TYPE, "Hoisted", &I)
851             << "hoisting " << ore::NV("Inst", &I));
852 
853   // Metadata can be dependent on conditions we are hoisting above.
854   // Conservatively strip all metadata on the instruction unless we were
855   // guaranteed to execute I if we entered the loop, in which case the metadata
856   // is valid in the loop preheader.
857   if (I.hasMetadataOtherThanDebugLoc() &&
858       // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
859       // time in isGuaranteedToExecute if we don't actually have anything to
860       // drop.  It is a compile time optimization, not required for correctness.
861       !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
862     I.dropUnknownNonDebugMetadata();
863 
864   // Move the new node to the Preheader, before its terminator.
865   I.moveBefore(Preheader->getTerminator());
866 
867   // Do not retain debug locations when we are moving instructions to different
868   // basic blocks, because we want to avoid jumpy line tables. Calls, however,
869   // need to retain their debug locs because they may be inlined.
870   // FIXME: How do we retain source locations without causing poor debugging
871   // behavior?
872   if (!isa<CallInst>(I))
873     I.setDebugLoc(DebugLoc());
874 
875   if (isa<LoadInst>(I))
876     ++NumMovedLoads;
877   else if (isa<CallInst>(I))
878     ++NumMovedCalls;
879   ++NumHoisted;
880   return true;
881 }
882 
883 /// Only sink or hoist an instruction if it is not a trapping instruction,
884 /// or if the instruction is known not to trap when moved to the preheader.
885 /// or if it is a trapping instruction and is guaranteed to execute.
886 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
887                                            const DominatorTree *DT,
888                                            const Loop *CurLoop,
889                                            const LoopSafetyInfo *SafetyInfo,
890                                            OptimizationRemarkEmitter *ORE,
891                                            const Instruction *CtxI) {
892   if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
893     return true;
894 
895   bool GuaranteedToExecute =
896       isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
897 
898   if (!GuaranteedToExecute) {
899     auto *LI = dyn_cast<LoadInst>(&Inst);
900     if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
901       ORE->emit(OptimizationRemarkMissed(
902                     DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
903                 << "failed to hoist load with loop-invariant address "
904                    "because load is conditionally executed");
905   }
906 
907   return GuaranteedToExecute;
908 }
909 
910 namespace {
911 class LoopPromoter : public LoadAndStorePromoter {
912   Value *SomePtr; // Designated pointer to store to.
913   SmallPtrSetImpl<Value *> &PointerMustAliases;
914   SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
915   SmallVectorImpl<Instruction *> &LoopInsertPts;
916   PredIteratorCache &PredCache;
917   AliasSetTracker &AST;
918   LoopInfo &LI;
919   DebugLoc DL;
920   int Alignment;
921   bool UnorderedAtomic;
922   AAMDNodes AATags;
923 
924   Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
925     if (Instruction *I = dyn_cast<Instruction>(V))
926       if (Loop *L = LI.getLoopFor(I->getParent()))
927         if (!L->contains(BB)) {
928           // We need to create an LCSSA PHI node for the incoming value and
929           // store that.
930           PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
931                                         I->getName() + ".lcssa", &BB->front());
932           for (BasicBlock *Pred : PredCache.get(BB))
933             PN->addIncoming(I, Pred);
934           return PN;
935         }
936     return V;
937   }
938 
939 public:
940   LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
941                SmallPtrSetImpl<Value *> &PMA,
942                SmallVectorImpl<BasicBlock *> &LEB,
943                SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
944                AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
945                bool UnorderedAtomic, const AAMDNodes &AATags)
946       : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
947         LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
948         LI(li), DL(std::move(dl)), Alignment(alignment),
949         UnorderedAtomic(UnorderedAtomic),AATags(AATags) {}
950 
951   bool isInstInList(Instruction *I,
952                     const SmallVectorImpl<Instruction *> &) const override {
953     Value *Ptr;
954     if (LoadInst *LI = dyn_cast<LoadInst>(I))
955       Ptr = LI->getOperand(0);
956     else
957       Ptr = cast<StoreInst>(I)->getPointerOperand();
958     return PointerMustAliases.count(Ptr);
959   }
960 
961   void doExtraRewritesBeforeFinalDeletion() const override {
962     // Insert stores after in the loop exit blocks.  Each exit block gets a
963     // store of the live-out values that feed them.  Since we've already told
964     // the SSA updater about the defs in the loop and the preheader
965     // definition, it is all set and we can start using it.
966     for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
967       BasicBlock *ExitBlock = LoopExitBlocks[i];
968       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
969       LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
970       Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
971       Instruction *InsertPos = LoopInsertPts[i];
972       StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
973       if (UnorderedAtomic)
974         NewSI->setOrdering(AtomicOrdering::Unordered);
975       NewSI->setAlignment(Alignment);
976       NewSI->setDebugLoc(DL);
977       if (AATags)
978         NewSI->setAAMetadata(AATags);
979     }
980   }
981 
982   void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
983     // Update alias analysis.
984     AST.copyValue(LI, V);
985   }
986   void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
987 };
988 } // end anon namespace
989 
990 /// Try to promote memory values to scalars by sinking stores out of the
991 /// loop and moving loads to before the loop.  We do this by looping over
992 /// the stores in the loop, looking for stores to Must pointers which are
993 /// loop invariant.
994 ///
995 bool llvm::promoteLoopAccessesToScalars(
996     AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
997     SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
998     LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
999     Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1000     OptimizationRemarkEmitter *ORE) {
1001   // Verify inputs.
1002   assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1003          CurAST != nullptr && SafetyInfo != nullptr &&
1004          "Unexpected Input to promoteLoopAccessesToScalars");
1005 
1006   // We can promote this alias set if it has a store, if it is a "Must" alias
1007   // set, if the pointer is loop invariant, and if we are not eliminating any
1008   // volatile loads or stores.
1009   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
1010       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
1011     return false;
1012 
1013   assert(!AS.empty() &&
1014          "Must alias set should have at least one pointer element in it!");
1015 
1016   Value *SomePtr = AS.begin()->getValue();
1017   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1018 
1019   // It isn't safe to promote a load/store from the loop if the load/store is
1020   // conditional.  For example, turning:
1021   //
1022   //    for () { if (c) *P += 1; }
1023   //
1024   // into:
1025   //
1026   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
1027   //
1028   // is not safe, because *P may only be valid to access if 'c' is true.
1029   //
1030   // The safety property divides into two parts:
1031   // p1) The memory may not be dereferenceable on entry to the loop.  In this
1032   //    case, we can't insert the required load in the preheader.
1033   // p2) The memory model does not allow us to insert a store along any dynamic
1034   //    path which did not originally have one.
1035   //
1036   // If at least one store is guaranteed to execute, both properties are
1037   // satisfied, and promotion is legal.
1038   //
1039   // This, however, is not a necessary condition. Even if no store/load is
1040   // guaranteed to execute, we can still establish these properties.
1041   // We can establish (p1) by proving that hoisting the load into the preheader
1042   // is safe (i.e. proving dereferenceability on all paths through the loop). We
1043   // can use any access within the alias set to prove dereferenceability,
1044   // since they're all must alias.
1045   //
1046   // There are two ways establish (p2):
1047   // a) Prove the location is thread-local. In this case the memory model
1048   // requirement does not apply, and stores are safe to insert.
1049   // b) Prove a store dominates every exit block. In this case, if an exit
1050   // blocks is reached, the original dynamic path would have taken us through
1051   // the store, so inserting a store into the exit block is safe. Note that this
1052   // is different from the store being guaranteed to execute. For instance,
1053   // if an exception is thrown on the first iteration of the loop, the original
1054   // store is never executed, but the exit blocks are not executed either.
1055 
1056   bool DereferenceableInPH = false;
1057   bool SafeToInsertStore = false;
1058 
1059   SmallVector<Instruction *, 64> LoopUses;
1060   SmallPtrSet<Value *, 4> PointerMustAliases;
1061 
1062   // We start with an alignment of one and try to find instructions that allow
1063   // us to prove better alignment.
1064   unsigned Alignment = 1;
1065   // Keep track of which types of access we see
1066   bool SawUnorderedAtomic = false;
1067   bool SawNotAtomic = false;
1068   AAMDNodes AATags;
1069 
1070   const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1071 
1072   // Do we know this object does not escape ?
1073   bool IsKnownNonEscapingObject = false;
1074   if (SafetyInfo->MayThrow) {
1075     // If a loop can throw, we have to insert a store along each unwind edge.
1076     // That said, we can't actually make the unwind edge explicit. Therefore,
1077     // we have to prove that the store is dead along the unwind edge.
1078     //
1079     // If the underlying object is not an alloca, nor a pointer that does not
1080     // escape, then we can not effectively prove that the store is dead along
1081     // the unwind edge. i.e. the caller of this function could have ways to
1082     // access the pointed object.
1083     Value *Object = GetUnderlyingObject(SomePtr, MDL);
1084     // If this is a base pointer we do not understand, simply bail.
1085     // We only handle alloca and return value from alloc-like fn right now.
1086     if (!isa<AllocaInst>(Object)) {
1087         if (!isAllocLikeFn(Object, TLI))
1088           return false;
1089       // If this is an alloc like fn. There are more constraints we need to verify.
1090       // More specifically, we must make sure that the pointer can not escape.
1091       //
1092       // NOTE: PointerMayBeCaptured is not enough as the pointer may have escaped
1093       // even though its not captured by the enclosing function. Standard allocation
1094       // functions like malloc, calloc, and operator new return values which can
1095       // be assumed not to have previously escaped.
1096       if (PointerMayBeCaptured(Object, true, true))
1097         return false;
1098       IsKnownNonEscapingObject = true;
1099     }
1100   }
1101 
1102   // Check that all of the pointers in the alias set have the same type.  We
1103   // cannot (yet) promote a memory location that is loaded and stored in
1104   // different sizes.  While we are at it, collect alignment and AA info.
1105   for (const auto &ASI : AS) {
1106     Value *ASIV = ASI.getValue();
1107     PointerMustAliases.insert(ASIV);
1108 
1109     // Check that all of the pointers in the alias set have the same type.  We
1110     // cannot (yet) promote a memory location that is loaded and stored in
1111     // different sizes.
1112     if (SomePtr->getType() != ASIV->getType())
1113       return false;
1114 
1115     for (User *U : ASIV->users()) {
1116       // Ignore instructions that are outside the loop.
1117       Instruction *UI = dyn_cast<Instruction>(U);
1118       if (!UI || !CurLoop->contains(UI))
1119         continue;
1120 
1121       // If there is an non-load/store instruction in the loop, we can't promote
1122       // it.
1123       if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1124         assert(!Load->isVolatile() && "AST broken");
1125         if (!Load->isUnordered())
1126           return false;
1127 
1128         SawUnorderedAtomic |= Load->isAtomic();
1129         SawNotAtomic |= !Load->isAtomic();
1130 
1131         if (!DereferenceableInPH)
1132           DereferenceableInPH = isSafeToExecuteUnconditionally(
1133               *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
1134       } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1135         // Stores *of* the pointer are not interesting, only stores *to* the
1136         // pointer.
1137         if (UI->getOperand(1) != ASIV)
1138           continue;
1139         assert(!Store->isVolatile() && "AST broken");
1140         if (!Store->isUnordered())
1141           return false;
1142 
1143         SawUnorderedAtomic |= Store->isAtomic();
1144         SawNotAtomic |= !Store->isAtomic();
1145 
1146         // If the store is guaranteed to execute, both properties are satisfied.
1147         // We may want to check if a store is guaranteed to execute even if we
1148         // already know that promotion is safe, since it may have higher
1149         // alignment than any other guaranteed stores, in which case we can
1150         // raise the alignment on the promoted store.
1151         unsigned InstAlignment = Store->getAlignment();
1152         if (!InstAlignment)
1153           InstAlignment =
1154               MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1155 
1156         if (!DereferenceableInPH || !SafeToInsertStore ||
1157             (InstAlignment > Alignment)) {
1158           if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
1159             DereferenceableInPH = true;
1160             SafeToInsertStore = true;
1161             Alignment = std::max(Alignment, InstAlignment);
1162           }
1163         }
1164 
1165         // If a store dominates all exit blocks, it is safe to sink.
1166         // As explained above, if an exit block was executed, a dominating
1167         // store must have been been executed at least once, so we are not
1168         // introducing stores on paths that did not have them.
1169         // Note that this only looks at explicit exit blocks. If we ever
1170         // start sinking stores into unwind edges (see above), this will break.
1171         if (!SafeToInsertStore)
1172           SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1173             return DT->dominates(Store->getParent(), Exit);
1174           });
1175 
1176         // If the store is not guaranteed to execute, we may still get
1177         // deref info through it.
1178         if (!DereferenceableInPH) {
1179           DereferenceableInPH = isDereferenceableAndAlignedPointer(
1180               Store->getPointerOperand(), Store->getAlignment(), MDL,
1181               Preheader->getTerminator(), DT);
1182         }
1183       } else
1184         return false; // Not a load or store.
1185 
1186       // Merge the AA tags.
1187       if (LoopUses.empty()) {
1188         // On the first load/store, just take its AA tags.
1189         UI->getAAMetadata(AATags);
1190       } else if (AATags) {
1191         UI->getAAMetadata(AATags, /* Merge = */ true);
1192       }
1193 
1194       LoopUses.push_back(UI);
1195     }
1196   }
1197 
1198   // If we found both an unordered atomic instruction and a non-atomic memory
1199   // access, bail.  We can't blindly promote non-atomic to atomic since we
1200   // might not be able to lower the result.  We can't downgrade since that
1201   // would violate memory model.  Also, align 0 is an error for atomics.
1202   if (SawUnorderedAtomic && SawNotAtomic)
1203     return false;
1204 
1205   // If we couldn't prove we can hoist the load, bail.
1206   if (!DereferenceableInPH)
1207     return false;
1208 
1209   // We know we can hoist the load, but don't have a guaranteed store.
1210   // Check whether the location is thread-local. If it is, then we can insert
1211   // stores along paths which originally didn't have them without violating the
1212   // memory model.
1213   if (!SafeToInsertStore) {
1214     // If this is a known non-escaping object, it is safe to insert the stores.
1215     if (IsKnownNonEscapingObject)
1216       SafeToInsertStore = true;
1217     else {
1218       Value *Object = GetUnderlyingObject(SomePtr, MDL);
1219       SafeToInsertStore =
1220         (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1221         !PointerMayBeCaptured(Object, true, true);
1222     }
1223   }
1224 
1225   // If we've still failed to prove we can sink the store, give up.
1226   if (!SafeToInsertStore)
1227     return false;
1228 
1229   // Otherwise, this is safe to promote, lets do it!
1230   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1231                << '\n');
1232   ORE->emit(
1233       OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", LoopUses[0])
1234       << "Moving accesses to memory location out of the loop");
1235   ++NumPromoted;
1236 
1237   // Grab a debug location for the inserted loads/stores; given that the
1238   // inserted loads/stores have little relation to the original loads/stores,
1239   // this code just arbitrarily picks a location from one, since any debug
1240   // location is better than none.
1241   DebugLoc DL = LoopUses[0]->getDebugLoc();
1242 
1243   // We use the SSAUpdater interface to insert phi nodes as required.
1244   SmallVector<PHINode *, 16> NewPHIs;
1245   SSAUpdater SSA(&NewPHIs);
1246   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1247                         InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1248                         SawUnorderedAtomic, AATags);
1249 
1250   // Set up the preheader to have a definition of the value.  It is the live-out
1251   // value from the preheader that uses in the loop will use.
1252   LoadInst *PreheaderLoad = new LoadInst(
1253       SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1254   if (SawUnorderedAtomic)
1255     PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1256   PreheaderLoad->setAlignment(Alignment);
1257   PreheaderLoad->setDebugLoc(DL);
1258   if (AATags)
1259     PreheaderLoad->setAAMetadata(AATags);
1260   SSA.AddAvailableValue(Preheader, PreheaderLoad);
1261 
1262   // Rewrite all the loads in the loop and remember all the definitions from
1263   // stores in the loop.
1264   Promoter.run(LoopUses);
1265 
1266   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1267   if (PreheaderLoad->use_empty())
1268     PreheaderLoad->eraseFromParent();
1269 
1270   return true;
1271 }
1272 
1273 /// Returns an owning pointer to an alias set which incorporates aliasing info
1274 /// from L and all subloops of L.
1275 /// FIXME: In new pass manager, there is no helper function to handle loop
1276 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
1277 /// from scratch for every loop. Hook up with the helper functions when
1278 /// available in the new pass manager to avoid redundant computation.
1279 AliasSetTracker *
1280 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1281                                                  AliasAnalysis *AA) {
1282   AliasSetTracker *CurAST = nullptr;
1283   SmallVector<Loop *, 4> RecomputeLoops;
1284   for (Loop *InnerL : L->getSubLoops()) {
1285     auto MapI = LoopToAliasSetMap.find(InnerL);
1286     // If the AST for this inner loop is missing it may have been merged into
1287     // some other loop's AST and then that loop unrolled, and so we need to
1288     // recompute it.
1289     if (MapI == LoopToAliasSetMap.end()) {
1290       RecomputeLoops.push_back(InnerL);
1291       continue;
1292     }
1293     AliasSetTracker *InnerAST = MapI->second;
1294 
1295     if (CurAST != nullptr) {
1296       // What if InnerLoop was modified by other passes ?
1297       CurAST->add(*InnerAST);
1298 
1299       // Once we've incorporated the inner loop's AST into ours, we don't need
1300       // the subloop's anymore.
1301       delete InnerAST;
1302     } else {
1303       CurAST = InnerAST;
1304     }
1305     LoopToAliasSetMap.erase(MapI);
1306   }
1307   if (CurAST == nullptr)
1308     CurAST = new AliasSetTracker(*AA);
1309 
1310   auto mergeLoop = [&](Loop *L) {
1311     // Loop over the body of this loop, looking for calls, invokes, and stores.
1312     for (BasicBlock *BB : L->blocks())
1313         CurAST->add(*BB);          // Incorporate the specified basic block
1314   };
1315 
1316   // Add everything from the sub loops that are no longer directly available.
1317   for (Loop *InnerL : RecomputeLoops)
1318     mergeLoop(InnerL);
1319 
1320   // And merge in this loop.
1321   mergeLoop(L);
1322 
1323   return CurAST;
1324 }
1325 
1326 /// Simple analysis hook. Clone alias set info.
1327 ///
1328 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1329                                              Loop *L) {
1330   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1331   if (!AST)
1332     return;
1333 
1334   AST->copyValue(From, To);
1335 }
1336 
1337 /// Simple Analysis hook. Delete value V from alias set
1338 ///
1339 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1340   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1341   if (!AST)
1342     return;
1343 
1344   AST->deleteValue(V);
1345 }
1346 
1347 /// Simple Analysis hook. Delete value L from alias set map.
1348 ///
1349 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1350   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1351   if (!AST)
1352     return;
1353 
1354   delete AST;
1355   LICM.getLoopToAliasSetMap().erase(L);
1356 }
1357 
1358 /// Return true if the body of this loop may store into the memory
1359 /// location pointed to by V.
1360 ///
1361 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1362                                      const AAMDNodes &AAInfo,
1363                                      AliasSetTracker *CurAST) {
1364   // Check to see if any of the basic blocks in CurLoop invalidate *V.
1365   return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1366 }
1367 
1368 /// Little predicate that returns true if the specified basic block is in
1369 /// a subloop of the current one, not the current one itself.
1370 ///
1371 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1372   assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1373   return LI->getLoopFor(BB) != CurLoop;
1374 }
1375