bcc05c38a04f9f863610fabb59365fa48dfc02c9
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
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.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/ConstantFolding.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/ScalarEvolution.h"
41 #include "llvm/Analysis/TargetLibraryInfo.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Dominators.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/PredIteratorCache.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59 #include <algorithm>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "licm"
63
64 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
65 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
66 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
69
70 static cl::opt<bool>
71 DisablePromotion("disable-licm-promotion", cl::Hidden,
72                  cl::desc("Disable memory promotion in LICM pass"));
73
74 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop);
76 static bool hoist(Instruction &I, BasicBlock *Preheader);
77 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
78                  const Loop *CurLoop, AliasSetTracker *CurAST );
79 static bool isGuaranteedToExecute(const Instruction &Inst,
80                                   const DominatorTree *DT,
81                                   const Loop *CurLoop,
82                                   const LICMSafetyInfo *SafetyInfo);
83 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
84                                            const DominatorTree *DT,
85                                            const TargetLibraryInfo *TLI,
86                                            const Loop *CurLoop,
87                                            const LICMSafetyInfo *SafetyInfo,
88                                            const Instruction *CtxI = nullptr);
89 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
90                                      const AAMDNodes &AAInfo, 
91                                      AliasSetTracker *CurAST);
92 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
93                                                 BasicBlock &ExitBlock,
94                                                 PHINode &PN,
95                                                 const LoopInfo *LI);
96 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
97                                DominatorTree *DT, TargetLibraryInfo *TLI,
98                                Loop *CurLoop, AliasSetTracker *CurAST,
99                                LICMSafetyInfo *SafetyInfo);
100
101 namespace {
102   struct LICM : public LoopPass {
103     static char ID; // Pass identification, replacement for typeid
104     LICM() : LoopPass(ID) {
105       initializeLICMPass(*PassRegistry::getPassRegistry());
106     }
107
108     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
109
110     /// This transformation requires natural loop information & requires that
111     /// loop preheaders be inserted into the CFG...
112     ///
113     void getAnalysisUsage(AnalysisUsage &AU) const override {
114       AU.setPreservesCFG();
115       AU.addRequired<DominatorTreeWrapperPass>();
116       AU.addRequired<LoopInfoWrapperPass>();
117       AU.addRequiredID(LoopSimplifyID);
118       AU.addPreservedID(LoopSimplifyID);
119       AU.addRequiredID(LCSSAID);
120       AU.addPreservedID(LCSSAID);
121       AU.addRequired<AliasAnalysis>();
122       AU.addPreserved<AliasAnalysis>();
123       AU.addPreserved<ScalarEvolution>();
124       AU.addRequired<TargetLibraryInfoWrapperPass>();
125     }
126
127     using llvm::Pass::doFinalization;
128
129     bool doFinalization() override {
130       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
131       return false;
132     }
133
134   private:
135     AliasAnalysis *AA;       // Current AliasAnalysis information
136     LoopInfo      *LI;       // Current LoopInfo
137     DominatorTree *DT;       // Dominator Tree for the current Loop.
138
139     TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
140
141     // State that is updated as we process loops.
142     bool Changed;            // Set to true when we change anything.
143     BasicBlock *Preheader;   // The preheader block of the current loop...
144     Loop *CurLoop;           // The current loop we are working on...
145     AliasSetTracker *CurAST; // AliasSet information for the current loop...
146     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
147
148     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
149     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
150                                  Loop *L) override;
151
152     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
153     /// set.
154     void deleteAnalysisValue(Value *V, Loop *L) override;
155
156     /// Simple Analysis hook. Delete loop L from alias set map.
157     void deleteAnalysisLoop(Loop *L) override;
158   };
159 }
160
161 char LICM::ID = 0;
162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
163 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
164 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
165 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166 INITIALIZE_PASS_DEPENDENCY(LCSSA)
167 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
168 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
169 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
171
172 Pass *llvm::createLICMPass() { return new LICM(); }
173
174 /// Hoist expressions out of the specified loop. Note, alias info for inner
175 /// loop is not preserved so it is not a good idea to run LICM multiple
176 /// times on one loop.
177 ///
178 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
179   if (skipOptnoneFunction(L))
180     return false;
181
182   Changed = false;
183
184   // Get our Loop and Alias Analysis information...
185   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
186   AA = &getAnalysis<AliasAnalysis>();
187   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
188
189   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
190
191   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
192
193   CurAST = new AliasSetTracker(*AA);
194   // Collect Alias info from subloops.
195   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
196        LoopItr != LoopItrE; ++LoopItr) {
197     Loop *InnerL = *LoopItr;
198     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
199     assert(InnerAST && "Where is my AST?");
200
201     // What if InnerLoop was modified by other passes ?
202     CurAST->add(*InnerAST);
203
204     // Once we've incorporated the inner loop's AST into ours, we don't need the
205     // subloop's anymore.
206     delete InnerAST;
207     LoopToAliasSetMap.erase(InnerL);
208   }
209
210   CurLoop = L;
211
212   // Get the preheader block to move instructions into...
213   Preheader = L->getLoopPreheader();
214
215   // Loop over the body of this loop, looking for calls, invokes, and stores.
216   // Because subloops have already been incorporated into AST, we skip blocks in
217   // subloops.
218   //
219   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
220        I != E; ++I) {
221     BasicBlock *BB = *I;
222     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
223       CurAST->add(*BB);                 // Incorporate the specified basic block
224   }
225
226   // Compute loop safety information.
227   LICMSafetyInfo SafetyInfo;
228   computeLICMSafetyInfo(&SafetyInfo, CurLoop);
229
230   // We want to visit all of the instructions in this loop... that are not parts
231   // of our subloops (they have already had their invariants hoisted out of
232   // their loop, into this loop, so there is no need to process the BODIES of
233   // the subloops).
234   //
235   // Traverse the body of the loop in depth first order on the dominator tree so
236   // that we are guaranteed to see definitions before we see uses.  This allows
237   // us to sink instructions in one pass, without iteration.  After sinking
238   // instructions, we perform another pass to hoist them out of the loop.
239   //
240   if (L->hasDedicatedExits())
241     Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
242                           CurAST, &SafetyInfo);
243   if (Preheader)
244     Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
245                            CurLoop, CurAST, &SafetyInfo);
246
247   // Now that all loop invariants have been removed from the loop, promote any
248   // memory references to scalars that we can.
249   if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
250     SmallVector<BasicBlock *, 8> ExitBlocks;
251     SmallVector<Instruction *, 8> InsertPts;
252     PredIteratorCache PIC;
253
254     // Loop over all of the alias sets in the tracker object.
255     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
256          I != E; ++I)
257       Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts, 
258                                               PIC, LI, DT, CurLoop, 
259                                               CurAST, &SafetyInfo);
260
261     // Once we have promoted values across the loop body we have to recursively
262     // reform LCSSA as any nested loop may now have values defined within the
263     // loop used in the outer loop.
264     // FIXME: This is really heavy handed. It would be a bit better to use an
265     // SSAUpdater strategy during promotion that was LCSSA aware and reformed
266     // it as it went.
267     if (Changed)
268       formLCSSARecursively(*L, *DT, LI,
269                            getAnalysisIfAvailable<ScalarEvolution>());
270   }
271
272   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
273   // specifically moving instructions across the loop boundary and so it is
274   // especially in need of sanity checking here.
275   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
276   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
277          "Parent loop not left in LCSSA form after LICM!");
278
279   // Clear out loops state information for the next iteration
280   CurLoop = nullptr;
281   Preheader = nullptr;
282
283   // If this loop is nested inside of another one, save the alias information
284   // for when we process the outer loop.
285   if (L->getParentLoop())
286     LoopToAliasSetMap[L] = CurAST;
287   else
288     delete CurAST;
289   return Changed;
290 }
291
292 /// Walk the specified region of the CFG (defined by all blocks dominated by
293 /// the specified block, and that are in the current loop) in reverse depth 
294 /// first order w.r.t the DominatorTree.  This allows us to visit uses before
295 /// definitions, allowing us to sink a loop body in one pass without iteration.
296 ///
297 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
298                       DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
299                       AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
300
301   // Verify inputs.
302   assert(N != nullptr && AA != nullptr && LI != nullptr && 
303          DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 
304          SafetyInfo != nullptr && "Unexpected input to sinkRegion");
305
306   // Set changed as false.
307   bool Changed = false;
308   // Get basic block
309   BasicBlock *BB = N->getBlock();
310   // If this subregion is not in the top level loop at all, exit.
311   if (!CurLoop->contains(BB)) return Changed;
312
313   // We are processing blocks in reverse dfo, so process children first.
314   const std::vector<DomTreeNode*> &Children = N->getChildren();
315   for (unsigned i = 0, e = Children.size(); i != e; ++i)
316     Changed |=
317         sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
318   // Only need to process the contents of this block if it is not part of a
319   // subloop (which would already have been processed).
320   if (inSubLoop(BB,CurLoop,LI)) return Changed;
321
322   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
323     Instruction &I = *--II;
324
325     // If the instruction is dead, we would try to sink it because it isn't used
326     // in the loop, instead, just delete it.
327     if (isInstructionTriviallyDead(&I, TLI)) {
328       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
329       ++II;
330       CurAST->deleteValue(&I);
331       I.eraseFromParent();
332       Changed = true;
333       continue;
334     }
335
336     // Check to see if we can sink this instruction to the exit blocks
337     // of the loop.  We can do this if the all users of the instruction are
338     // outside of the loop.  In this case, it doesn't even matter if the
339     // operands of the instruction are loop invariant.
340     //
341     if (isNotUsedInLoop(I, CurLoop) &&
342         canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
343       ++II;
344       Changed |= sink(I, LI, DT, CurLoop, CurAST);
345     }
346   }
347   return Changed;
348 }
349
350 /// Walk the specified region of the CFG (defined by all blocks dominated by
351 /// the specified block, and that are in the current loop) in depth first
352 /// order w.r.t the DominatorTree.  This allows us to visit definitions before
353 /// uses, allowing us to hoist a loop body in one pass without iteration.
354 ///
355 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
356                        DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
357                        AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
358   // Verify inputs.
359   assert(N != nullptr && AA != nullptr && LI != nullptr && 
360          DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 
361          SafetyInfo != nullptr && "Unexpected input to hoistRegion");
362   // Set changed as false.
363   bool Changed = false;
364   // Get basic block
365   BasicBlock *BB = N->getBlock();
366   // If this subregion is not in the top level loop at all, exit.
367   if (!CurLoop->contains(BB)) return Changed;
368   // Only need to process the contents of this block if it is not part of a
369   // subloop (which would already have been processed).
370   if (!inSubLoop(BB, CurLoop, LI))
371     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
372       Instruction &I = *II++;
373       // Try constant folding this instruction.  If all the operands are
374       // constants, it is technically hoistable, but it would be better to just
375       // fold it.
376       if (Constant *C = ConstantFoldInstruction(
377               &I, I.getModule()->getDataLayout(), TLI)) {
378         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
379         CurAST->copyValue(&I, C);
380         CurAST->deleteValue(&I);
381         I.replaceAllUsesWith(C);
382         I.eraseFromParent();
383         continue;
384       }
385
386       // Try hoisting the instruction out to the preheader.  We can only do this
387       // if all of the operands of the instruction are loop invariant and if it
388       // is safe to hoist the instruction.
389       //
390       if (CurLoop->hasLoopInvariantOperands(&I) &&
391           canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
392           isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
393                                  CurLoop->getLoopPreheader()->getTerminator()))
394         Changed |= hoist(I, CurLoop->getLoopPreheader());
395     }
396
397   const std::vector<DomTreeNode*> &Children = N->getChildren();
398   for (unsigned i = 0, e = Children.size(); i != e; ++i)
399     Changed |=
400         hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
401   return Changed;
402 }
403
404 /// Computes loop safety information, checks loop body & header
405 /// for the possiblity of may throw exception.
406 ///
407 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
408   assert(CurLoop != nullptr && "CurLoop cant be null");
409   BasicBlock *Header = CurLoop->getHeader();
410   // Setting default safety values.
411   SafetyInfo->MayThrow = false;
412   SafetyInfo->HeaderMayThrow = false;
413   // Iterate over header and compute dafety info.
414   for (BasicBlock::iterator I = Header->begin(), E = Header->end();
415        (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
416     SafetyInfo->HeaderMayThrow |= I->mayThrow();
417   
418   SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
419   // Iterate over loop instructions and compute safety info. 
420   for (Loop::block_iterator BB = CurLoop->block_begin(), 
421        BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
422     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
423          (I != E) && !SafetyInfo->MayThrow; ++I)
424       SafetyInfo->MayThrow |= I->mayThrow();
425 }
426
427 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
428 /// instruction.
429 ///
430 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
431                         TargetLibraryInfo *TLI, Loop *CurLoop,
432                         AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
433   // Loads have extra constraints we have to verify before we can hoist them.
434   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
435     if (!LI->isUnordered())
436       return false;        // Don't hoist volatile/atomic loads!
437
438     // Loads from constant memory are always safe to move, even if they end up
439     // in the same alias set as something that ends up being modified.
440     if (AA->pointsToConstantMemory(LI->getOperand(0)))
441       return true;
442     if (LI->getMetadata(LLVMContext::MD_invariant_load))
443       return true;
444
445     // Don't hoist loads which have may-aliased stores in loop.
446     uint64_t Size = 0;
447     if (LI->getType()->isSized())
448       Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
449
450     AAMDNodes AAInfo;
451     LI->getAAMetadata(AAInfo);
452
453     return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
454   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
455     // Don't sink or hoist dbg info; it's legal, but not useful.
456     if (isa<DbgInfoIntrinsic>(I))
457       return false;
458
459     // Handle simple cases by querying alias analysis.
460     FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
461     if (Behavior == FMRB_DoesNotAccessMemory)
462       return true;
463     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
464       // If this call only reads from memory and there are no writes to memory
465       // in the loop, we can hoist or sink the call as appropriate.
466       bool FoundMod = false;
467       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
468            I != E; ++I) {
469         AliasSet &AS = *I;
470         if (!AS.isForwardingAliasSet() && AS.isMod()) {
471           FoundMod = true;
472           break;
473         }
474       }
475       if (!FoundMod) return true;
476     }
477
478     // FIXME: This should use mod/ref information to see if we can hoist or
479     // sink the call.
480
481     return false;
482   }
483
484   // Only these instructions are hoistable/sinkable.
485   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
486       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
487       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
488       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
489       !isa<InsertValueInst>(I))
490     return false;
491
492   // TODO: Plumb the context instruction through to make hoisting and sinking
493   // more powerful. Hoisting of loads already works due to the special casing
494   // above. 
495   return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
496                                         nullptr);
497 }
498
499 /// Returns true if a PHINode is a trivially replaceable with an
500 /// Instruction.
501 /// This is true when all incoming values are that instruction.
502 /// This pattern occurs most often with LCSSA PHI nodes.
503 ///
504 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
505   for (const Value *IncValue : PN.incoming_values())
506     if (IncValue != &I)
507       return false;
508
509   return true;
510 }
511
512 /// Return true if the only users of this instruction are outside of
513 /// the loop. If this is true, we can sink the instruction to the exit
514 /// blocks of the loop.
515 ///
516 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) {
517   for (const User *U : I.users()) {
518     const Instruction *UI = cast<Instruction>(U);
519     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
520       // A PHI node where all of the incoming values are this instruction are
521       // special -- they can just be RAUW'ed with the instruction and thus
522       // don't require a use in the predecessor. This is a particular important
523       // special case because it is the pattern found in LCSSA form.
524       if (isTriviallyReplacablePHI(*PN, I)) {
525         if (CurLoop->contains(PN))
526           return false;
527         else
528           continue;
529       }
530
531       // Otherwise, PHI node uses occur in predecessor blocks if the incoming
532       // values. Check for such a use being inside the loop.
533       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
534         if (PN->getIncomingValue(i) == &I)
535           if (CurLoop->contains(PN->getIncomingBlock(i)))
536             return false;
537
538       continue;
539     }
540
541     if (CurLoop->contains(UI))
542       return false;
543   }
544   return true;
545 }
546
547 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
548                                                 BasicBlock &ExitBlock,
549                                                 PHINode &PN,
550                                                 const LoopInfo *LI) {
551   Instruction *New = I.clone();
552   ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
553   if (!I.getName().empty()) New->setName(I.getName() + ".le");
554
555   // Build LCSSA PHI nodes for any in-loop operands. Note that this is
556   // particularly cheap because we can rip off the PHI node that we're
557   // replacing for the number and blocks of the predecessors.
558   // OPT: If this shows up in a profile, we can instead finish sinking all
559   // invariant instructions, and then walk their operands to re-establish
560   // LCSSA. That will eliminate creating PHI nodes just to nuke them when
561   // sinking bottom-up.
562   for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
563        ++OI)
564     if (Instruction *OInst = dyn_cast<Instruction>(*OI))
565       if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
566         if (!OLoop->contains(&PN)) {
567           PHINode *OpPN =
568               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
569                               OInst->getName() + ".lcssa", ExitBlock.begin());
570           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
571             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
572           *OI = OpPN;
573         }
574   return New;
575 }
576
577 /// When an instruction is found to only be used outside of the loop, this
578 /// function moves it to the exit blocks and patches up SSA form as needed.
579 /// This method is guaranteed to remove the original instruction from its
580 /// position, and may either delete it or move it to outside of the loop.
581 ///
582 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
583                  const Loop *CurLoop, AliasSetTracker *CurAST ) {
584   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
585   bool Changed = false;
586   if (isa<LoadInst>(I)) ++NumMovedLoads;
587   else if (isa<CallInst>(I)) ++NumMovedCalls;
588   ++NumSunk;
589   Changed = true;
590
591 #ifndef NDEBUG
592   SmallVector<BasicBlock *, 32> ExitBlocks;
593   CurLoop->getUniqueExitBlocks(ExitBlocks);
594   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 
595                                              ExitBlocks.end());
596 #endif
597
598   // Clones of this instruction. Don't create more than one per exit block!
599   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
600
601   // If this instruction is only used outside of the loop, then all users are
602   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
603   // the instruction.
604   while (!I.use_empty()) {
605     Value::user_iterator UI = I.user_begin();
606     auto *User = cast<Instruction>(*UI);
607     if (!DT->isReachableFromEntry(User->getParent())) {
608       User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
609       continue;
610     }
611     // The user must be a PHI node.
612     PHINode *PN = cast<PHINode>(User);
613
614     // Surprisingly, instructions can be used outside of loops without any
615     // exits.  This can only happen in PHI nodes if the incoming block is
616     // unreachable.
617     Use &U = UI.getUse();
618     BasicBlock *BB = PN->getIncomingBlock(U);
619     if (!DT->isReachableFromEntry(BB)) {
620       U = UndefValue::get(I.getType());
621       continue;
622     }
623
624     BasicBlock *ExitBlock = PN->getParent();
625     assert(ExitBlockSet.count(ExitBlock) &&
626            "The LCSSA PHI is not in an exit block!");
627
628     Instruction *New;
629     auto It = SunkCopies.find(ExitBlock);
630     if (It != SunkCopies.end())
631       New = It->second;
632     else
633       New = SunkCopies[ExitBlock] =
634             CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
635
636     PN->replaceAllUsesWith(New);
637     PN->eraseFromParent();
638   }
639
640   CurAST->deleteValue(&I);
641   I.eraseFromParent();
642   return Changed;
643 }
644
645 /// When an instruction is found to only use loop invariant operands that
646 /// is safe to hoist, this instruction is called to do the dirty work.
647 ///
648 static bool hoist(Instruction &I, BasicBlock *Preheader) {
649   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
650         << I << "\n");
651   // Move the new node to the Preheader, before its terminator.
652   I.moveBefore(Preheader->getTerminator());
653
654   if (isa<LoadInst>(I)) ++NumMovedLoads;
655   else if (isa<CallInst>(I)) ++NumMovedCalls;
656   ++NumHoisted;
657   return true;
658 }
659
660 /// Only sink or hoist an instruction if it is not a trapping instruction,
661 /// or if the instruction is known not to trap when moved to the preheader.
662 /// or if it is a trapping instruction and is guaranteed to execute.
663 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 
664                                            const DominatorTree *DT,
665                                            const TargetLibraryInfo *TLI,
666                                            const Loop *CurLoop,
667                                            const LICMSafetyInfo *SafetyInfo,
668                                            const Instruction *CtxI) {
669   if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
670     return true;
671
672   return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
673 }
674
675 static bool isGuaranteedToExecute(const Instruction &Inst,
676                                   const DominatorTree *DT,
677                                   const Loop *CurLoop,
678                                   const LICMSafetyInfo * SafetyInfo) {
679
680   // We have to check to make sure that the instruction dominates all
681   // of the exit blocks.  If it doesn't, then there is a path out of the loop
682   // which does not execute this instruction, so we can't hoist it.
683
684   // If the instruction is in the header block for the loop (which is very
685   // common), it is always guaranteed to dominate the exit blocks.  Since this
686   // is a common case, and can save some work, check it now.
687   if (Inst.getParent() == CurLoop->getHeader())
688     // If there's a throw in the header block, we can't guarantee we'll reach
689     // Inst.
690     return !SafetyInfo->HeaderMayThrow;
691
692   // Somewhere in this loop there is an instruction which may throw and make us
693   // exit the loop.
694   if (SafetyInfo->MayThrow)
695     return false;
696
697   // Get the exit blocks for the current loop.
698   SmallVector<BasicBlock*, 8> ExitBlocks;
699   CurLoop->getExitBlocks(ExitBlocks);
700
701   // Verify that the block dominates each of the exit blocks of the loop.
702   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
703     if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
704       return false;
705
706   // As a degenerate case, if the loop is statically infinite then we haven't
707   // proven anything since there are no exit blocks.
708   if (ExitBlocks.empty())
709     return false;
710
711   return true;
712 }
713
714 namespace {
715   class LoopPromoter : public LoadAndStorePromoter {
716     Value *SomePtr;  // Designated pointer to store to.
717     SmallPtrSetImpl<Value*> &PointerMustAliases;
718     SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
719     SmallVectorImpl<Instruction*> &LoopInsertPts;
720     PredIteratorCache &PredCache;
721     AliasSetTracker &AST;
722     LoopInfo &LI;
723     DebugLoc DL;
724     int Alignment;
725     AAMDNodes AATags;
726
727     Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
728       if (Instruction *I = dyn_cast<Instruction>(V))
729         if (Loop *L = LI.getLoopFor(I->getParent()))
730           if (!L->contains(BB)) {
731             // We need to create an LCSSA PHI node for the incoming value and
732             // store that.
733             PHINode *PN = PHINode::Create(
734                 I->getType(), PredCache.size(BB),
735                 I->getName() + ".lcssa", BB->begin());
736             for (BasicBlock *Pred : PredCache.get(BB))
737               PN->addIncoming(I, Pred);
738             return PN;
739           }
740       return V;
741     }
742
743   public:
744     LoopPromoter(Value *SP,
745                  ArrayRef<const Instruction *> Insts,
746                  SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
747                  SmallVectorImpl<BasicBlock *> &LEB,
748                  SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
749                  AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
750                  const AAMDNodes &AATags)
751         : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
752           LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
753           LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
754
755     bool isInstInList(Instruction *I,
756                       const SmallVectorImpl<Instruction*> &) const override {
757       Value *Ptr;
758       if (LoadInst *LI = dyn_cast<LoadInst>(I))
759         Ptr = LI->getOperand(0);
760       else
761         Ptr = cast<StoreInst>(I)->getPointerOperand();
762       return PointerMustAliases.count(Ptr);
763     }
764
765     void doExtraRewritesBeforeFinalDeletion() const override {
766       // Insert stores after in the loop exit blocks.  Each exit block gets a
767       // store of the live-out values that feed them.  Since we've already told
768       // the SSA updater about the defs in the loop and the preheader
769       // definition, it is all set and we can start using it.
770       for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
771         BasicBlock *ExitBlock = LoopExitBlocks[i];
772         Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
773         LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
774         Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
775         Instruction *InsertPos = LoopInsertPts[i];
776         StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
777         NewSI->setAlignment(Alignment);
778         NewSI->setDebugLoc(DL);
779         if (AATags) NewSI->setAAMetadata(AATags);
780       }
781     }
782
783     void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
784       // Update alias analysis.
785       AST.copyValue(LI, V);
786     }
787     void instructionDeleted(Instruction *I) const override {
788       AST.deleteValue(I);
789     }
790   };
791 } // end anon namespace
792
793 /// Try to promote memory values to scalars by sinking stores out of the
794 /// loop and moving loads to before the loop.  We do this by looping over
795 /// the stores in the loop, looking for stores to Must pointers which are
796 /// loop invariant.
797 ///
798 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
799                                         SmallVectorImpl<BasicBlock*>&ExitBlocks,
800                                         SmallVectorImpl<Instruction*>&InsertPts,
801                                         PredIteratorCache &PIC, LoopInfo *LI, 
802                                         DominatorTree *DT, Loop *CurLoop, 
803                                         AliasSetTracker *CurAST, 
804                                         LICMSafetyInfo * SafetyInfo) { 
805   // Verify inputs.
806   assert(LI != nullptr && DT != nullptr && 
807          CurLoop != nullptr && CurAST != nullptr && 
808          SafetyInfo != nullptr && 
809          "Unexpected Input to promoteLoopAccessesToScalars");
810   // Initially set Changed status to false.
811   bool Changed = false;
812   // We can promote this alias set if it has a store, if it is a "Must" alias
813   // set, if the pointer is loop invariant, and if we are not eliminating any
814   // volatile loads or stores.
815   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
816       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
817     return Changed;
818
819   assert(!AS.empty() &&
820          "Must alias set should have at least one pointer element in it!");
821
822   Value *SomePtr = AS.begin()->getValue();
823   BasicBlock * Preheader = CurLoop->getLoopPreheader();
824
825   // It isn't safe to promote a load/store from the loop if the load/store is
826   // conditional.  For example, turning:
827   //
828   //    for () { if (c) *P += 1; }
829   //
830   // into:
831   //
832   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
833   //
834   // is not safe, because *P may only be valid to access if 'c' is true.
835   //
836   // It is safe to promote P if all uses are direct load/stores and if at
837   // least one is guaranteed to be executed.
838   bool GuaranteedToExecute = false;
839
840   SmallVector<Instruction*, 64> LoopUses;
841   SmallPtrSet<Value*, 4> PointerMustAliases;
842
843   // We start with an alignment of one and try to find instructions that allow
844   // us to prove better alignment.
845   unsigned Alignment = 1;
846   AAMDNodes AATags;
847   bool HasDedicatedExits = CurLoop->hasDedicatedExits();
848
849   // Check that all of the pointers in the alias set have the same type.  We
850   // cannot (yet) promote a memory location that is loaded and stored in
851   // different sizes.  While we are at it, collect alignment and AA info.
852   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
853     Value *ASIV = ASI->getValue();
854     PointerMustAliases.insert(ASIV);
855
856     // Check that all of the pointers in the alias set have the same type.  We
857     // cannot (yet) promote a memory location that is loaded and stored in
858     // different sizes.
859     if (SomePtr->getType() != ASIV->getType())
860       return Changed;
861
862     for (User *U : ASIV->users()) {
863       // Ignore instructions that are outside the loop.
864       Instruction *UI = dyn_cast<Instruction>(U);
865       if (!UI || !CurLoop->contains(UI))
866         continue;
867
868       // If there is an non-load/store instruction in the loop, we can't promote
869       // it.
870       if (const LoadInst *load = dyn_cast<LoadInst>(UI)) {
871         assert(!load->isVolatile() && "AST broken");
872         if (!load->isSimple())
873           return Changed;
874       } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) {
875         // Stores *of* the pointer are not interesting, only stores *to* the
876         // pointer.
877         if (UI->getOperand(1) != ASIV)
878           continue;
879         assert(!store->isVolatile() && "AST broken");
880         if (!store->isSimple())
881           return Changed;
882         // Don't sink stores from loops without dedicated block exits. Exits
883         // containing indirect branches are not transformed by loop simplify,
884         // make sure we catch that. An additional load may be generated in the
885         // preheader for SSA updater, so also avoid sinking when no preheader
886         // is available.
887         if (!HasDedicatedExits || !Preheader)
888           return Changed;
889
890         // Note that we only check GuaranteedToExecute inside the store case
891         // so that we do not introduce stores where they did not exist before
892         // (which would break the LLVM concurrency model).
893
894         // If the alignment of this instruction allows us to specify a more
895         // restrictive (and performant) alignment and if we are sure this
896         // instruction will be executed, update the alignment.
897         // Larger is better, with the exception of 0 being the best alignment.
898         unsigned InstAlignment = store->getAlignment();
899         if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
900           if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
901             GuaranteedToExecute = true;
902             Alignment = InstAlignment;
903           }
904
905         if (!GuaranteedToExecute)
906           GuaranteedToExecute = isGuaranteedToExecute(*UI, DT, 
907                                                       CurLoop, SafetyInfo);
908
909       } else
910         return Changed; // Not a load or store.
911
912       // Merge the AA tags.
913       if (LoopUses.empty()) {
914         // On the first load/store, just take its AA tags.
915         UI->getAAMetadata(AATags);
916       } else if (AATags) {
917         UI->getAAMetadata(AATags, /* Merge = */ true);
918       }
919
920       LoopUses.push_back(UI);
921     }
922   }
923
924   // If there isn't a guaranteed-to-execute instruction, we can't promote.
925   if (!GuaranteedToExecute)
926     return Changed;
927
928   // Otherwise, this is safe to promote, lets do it!
929   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
930   Changed = true;
931   ++NumPromoted;
932
933   // Grab a debug location for the inserted loads/stores; given that the
934   // inserted loads/stores have little relation to the original loads/stores,
935   // this code just arbitrarily picks a location from one, since any debug
936   // location is better than none.
937   DebugLoc DL = LoopUses[0]->getDebugLoc();
938
939   // Figure out the loop exits and their insertion points, if this is the
940   // first promotion.
941   if (ExitBlocks.empty()) {
942     CurLoop->getUniqueExitBlocks(ExitBlocks);
943     InsertPts.resize(ExitBlocks.size());
944     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
945       InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
946   }
947
948   // We use the SSAUpdater interface to insert phi nodes as required.
949   SmallVector<PHINode*, 16> NewPHIs;
950   SSAUpdater SSA(&NewPHIs);
951   LoopPromoter Promoter(SomePtr, LoopUses, SSA,
952                         PointerMustAliases, ExitBlocks,
953                         InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
954
955   // Set up the preheader to have a definition of the value.  It is the live-out
956   // value from the preheader that uses in the loop will use.
957   LoadInst *PreheaderLoad =
958     new LoadInst(SomePtr, SomePtr->getName()+".promoted",
959                  Preheader->getTerminator());
960   PreheaderLoad->setAlignment(Alignment);
961   PreheaderLoad->setDebugLoc(DL);
962   if (AATags) PreheaderLoad->setAAMetadata(AATags);
963   SSA.AddAvailableValue(Preheader, PreheaderLoad);
964
965   // Rewrite all the loads in the loop and remember all the definitions from
966   // stores in the loop.
967   Promoter.run(LoopUses);
968
969   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
970   if (PreheaderLoad->use_empty())
971     PreheaderLoad->eraseFromParent();
972
973   return Changed;
974 }
975
976 /// Simple Analysis hook. Clone alias set info.
977 ///
978 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
979   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
980   if (!AST)
981     return;
982
983   AST->copyValue(From, To);
984 }
985
986 /// Simple Analysis hook. Delete value V from alias set
987 ///
988 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
989   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
990   if (!AST)
991     return;
992
993   AST->deleteValue(V);
994 }
995
996 /// Simple Analysis hook. Delete value L from alias set map.
997 ///
998 void LICM::deleteAnalysisLoop(Loop *L) {
999   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1000   if (!AST)
1001     return;
1002
1003   delete AST;
1004   LoopToAliasSetMap.erase(L);
1005 }
1006
1007
1008 /// Return true if the body of this loop may store into the memory
1009 /// location pointed to by V.
1010 ///
1011 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1012                                      const AAMDNodes &AAInfo, 
1013                                      AliasSetTracker *CurAST) {
1014   // Check to see if any of the basic blocks in CurLoop invalidate *V.
1015   return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1016 }
1017
1018 /// Little predicate that returns true if the specified basic block is in
1019 /// a subloop of the current one, not the current one itself.
1020 ///
1021 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1022   assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1023   return LI->getLoopFor(BB) != CurLoop;
1024 }
1025