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