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