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