Loop exit sets are no longer explicitly held, they are dynamically computed on demand.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 out of loops.  If we can determine that a
19 //     load inside of a loop never aliases anything stored to, we can hoist it
20 //     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 mem2reg functionality to construct the appropriate SSA form for the
30 //     variable.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Analysis/AliasSetTracker.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Support/CFG.h"
45 #include "Support/CommandLine.h"
46 #include "Support/Debug.h"
47 #include "Support/Statistic.h"
48 #include "llvm/Assembly/Writer.h"
49 #include <algorithm>
50 using namespace llvm;
51
52 namespace {
53   cl::opt<bool>
54   DisablePromotion("disable-licm-promotion", cl::Hidden,
55                    cl::desc("Disable memory promotion in LICM pass"));
56
57   Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
58   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
59   Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
60   Statistic<> NumMovedCalls("licm", "Number of call insts hoisted or sunk");
61   Statistic<> NumPromoted("licm",
62                           "Number of memory locations promoted to registers");
63
64   struct LICM : public FunctionPass {
65     virtual bool runOnFunction(Function &F);
66
67     /// This transformation requires natural loop information & requires that
68     /// loop preheaders be inserted into the CFG...
69     ///
70     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71       AU.setPreservesCFG();
72       AU.addRequiredID(LoopSimplifyID);
73       AU.addRequired<LoopInfo>();
74       AU.addRequired<DominatorTree>();
75       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
76       AU.addRequired<AliasAnalysis>();
77     }
78
79   private:
80     // Various analyses that we use...
81     AliasAnalysis *AA;       // Current AliasAnalysis information
82     LoopInfo      *LI;       // Current LoopInfo
83     DominatorTree *DT;       // Dominator Tree for the current Loop...
84     DominanceFrontier *DF;   // Current Dominance Frontier
85
86     // State that is updated as we process loops
87     bool Changed;            // Set to true when we change anything.
88     BasicBlock *Preheader;   // The preheader block of the current loop...
89     Loop *CurLoop;           // The current loop we are working on...
90     AliasSetTracker *CurAST; // AliasSet information for the current loop...
91
92     /// visitLoop - Hoist expressions out of the specified loop...    
93     ///
94     void visitLoop(Loop *L, AliasSetTracker &AST);
95
96     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
97     /// dominated by the specified block, and that are in the current loop) in
98     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
99     /// visit uses before definitions, allowing us to sink a loop body in one
100     /// pass without iteration.
101     ///
102     void SinkRegion(DominatorTree::Node *N);
103
104     /// HoistRegion - Walk the specified region of the CFG (defined by all
105     /// blocks dominated by the specified block, and that are in the current
106     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
107     /// visit definitions before uses, allowing us to hoist a loop body in one
108     /// pass without iteration.
109     ///
110     void HoistRegion(DominatorTree::Node *N);
111
112     /// inSubLoop - Little predicate that returns true if the specified basic
113     /// block is in a subloop of the current one, not the current one itself.
114     ///
115     bool inSubLoop(BasicBlock *BB) {
116       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
117       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
118         if ((*I)->contains(BB))
119           return true;  // A subloop actually contains this block!
120       return false;
121     }
122
123     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
124     /// specified exit block of the loop is dominated by the specified block
125     /// that is in the body of the loop.  We use these constraints to
126     /// dramatically limit the amount of the dominator tree that needs to be
127     /// searched.
128     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
129                                            BasicBlock *BlockInLoop) const {
130       // If the block in the loop is the loop header, it must be dominated!
131       BasicBlock *LoopHeader = CurLoop->getHeader();
132       if (BlockInLoop == LoopHeader)
133         return true;
134       
135       DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
136       DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
137     
138       // Because the exit block is not in the loop, we know we have to get _at
139       // least_ it's immediate dominator.
140       do {
141         // Get next Immediate Dominator.
142         IDom = IDom->getIDom();
143         
144         // If we have got to the header of the loop, then the instructions block
145         // did not dominate the exit node, so we can't hoist it.
146         if (IDom->getBlock() == LoopHeader)
147           return false;
148         
149       } while (IDom != BlockInLoopNode);
150
151       return true;
152     }
153
154     /// sink - When an instruction is found to only be used outside of the loop,
155     /// this function moves it to the exit blocks and patches up SSA form as
156     /// needed.
157     ///
158     void sink(Instruction &I);
159
160     /// hoist - When an instruction is found to only use loop invariant operands
161     /// that is safe to hoist, this instruction is called to do the dirty work.
162     ///
163     void hoist(Instruction &I);
164
165     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
166     /// is not a trapping instruction or if it is a trapping instruction and is
167     /// guaranteed to execute.
168     ///
169     bool isSafeToExecuteUnconditionally(Instruction &I);
170
171     /// pointerInvalidatedByLoop - Return true if the body of this loop may
172     /// store into the memory location pointed to by V.
173     /// 
174     bool pointerInvalidatedByLoop(Value *V) {
175       // Check to see if any of the basic blocks in CurLoop invalidate *V.
176       return CurAST->getAliasSetForPointer(V, 0).isMod();
177     }
178
179     /// isLoopInvariant - Return true if the specified value is loop invariant
180     ///
181     inline bool isLoopInvariant(Value *V) {
182       if (Instruction *I = dyn_cast<Instruction>(V))
183         return !CurLoop->contains(I->getParent());
184       return true;  // All non-instructions are loop invariant
185     }
186
187     bool canSinkOrHoistInst(Instruction &I);
188     bool isLoopInvariantInst(Instruction &I);
189     bool isNotUsedInLoop(Instruction &I);
190
191     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
192     /// to scalars as we can.
193     ///
194     void PromoteValuesInLoop();
195
196     /// findPromotableValuesInLoop - Check the current loop for stores to
197     /// definite pointers, which are not loaded and stored through may aliases.
198     /// If these are found, create an alloca for the value, add it to the
199     /// PromotedValues list, and keep track of the mapping from value to
200     /// alloca...
201     ///
202     void findPromotableValuesInLoop(
203                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
204                                     std::map<Value*, AllocaInst*> &Val2AlMap);
205   };
206
207   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
208 }
209
210 FunctionPass *llvm::createLICMPass() { return new LICM(); }
211
212 /// runOnFunction - For LICM, this simply traverses the loop structure of the
213 /// function, hoisting expressions out of loops if possible.
214 ///
215 bool LICM::runOnFunction(Function &) {
216   Changed = false;
217
218   // Get our Loop and Alias Analysis information...
219   LI = &getAnalysis<LoopInfo>();
220   AA = &getAnalysis<AliasAnalysis>();
221   DF = &getAnalysis<DominanceFrontier>();
222   DT = &getAnalysis<DominatorTree>();
223
224   // Hoist expressions out of all of the top-level loops.
225   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
226     AliasSetTracker AST(*AA);
227     visitLoop(*I, AST);
228   }
229   return Changed;
230 }
231
232
233 /// visitLoop - Hoist expressions out of the specified loop...    
234 ///
235 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
236   // Recurse through all subloops before we process this loop...
237   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
238     AliasSetTracker SubAST(*AA);
239     visitLoop(*I, SubAST);
240
241     // Incorporate information about the subloops into this loop...
242     AST.add(SubAST);
243   }
244   CurLoop = L;
245   CurAST = &AST;
246
247   // Get the preheader block to move instructions into...
248   Preheader = L->getLoopPreheader();
249   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
250
251   // Loop over the body of this loop, looking for calls, invokes, and stores.
252   // Because subloops have already been incorporated into AST, we skip blocks in
253   // subloops.
254   //
255   for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
256          E = L->getBlocks().end(); I != E; ++I)
257     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
258       AST.add(**I);                     // Incorporate the specified basic block
259
260   // We want to visit all of the instructions in this loop... that are not parts
261   // of our subloops (they have already had their invariants hoisted out of
262   // their loop, into this loop, so there is no need to process the BODIES of
263   // the subloops).
264   //
265   // Traverse the body of the loop in depth first order on the dominator tree so
266   // that we are guaranteed to see definitions before we see uses.  This allows
267   // us to sink instructions in one pass, without iteration.  AFter sinking
268   // instructions, we perform another pass to hoist them out of the loop.
269   //
270   SinkRegion(DT->getNode(L->getHeader()));
271   HoistRegion(DT->getNode(L->getHeader()));
272
273   // Now that all loop invariants have been removed from the loop, promote any
274   // memory references to scalars that we can...
275   if (!DisablePromotion)
276     PromoteValuesInLoop();
277
278   // Clear out loops state information for the next iteration
279   CurLoop = 0;
280   Preheader = 0;
281 }
282
283 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
284 /// dominated by the specified block, and that are in the current loop) in
285 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
286 /// uses before definitions, allowing us to sink a loop body in one pass without
287 /// iteration.
288 ///
289 void LICM::SinkRegion(DominatorTree::Node *N) {
290   assert(N != 0 && "Null dominator tree node?");
291   BasicBlock *BB = N->getBlock();
292
293   // If this subregion is not in the top level loop at all, exit.
294   if (!CurLoop->contains(BB)) return;
295
296   // We are processing blocks in reverse dfo, so process children first...
297   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
298   for (unsigned i = 0, e = Children.size(); i != e; ++i)
299     SinkRegion(Children[i]);
300
301   // Only need to process the contents of this block if it is not part of a
302   // subloop (which would already have been processed).
303   if (inSubLoop(BB)) return;
304
305   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
306     Instruction &I = *--II;
307     
308     // Check to see if we can sink this instruction to the exit blocks
309     // of the loop.  We can do this if the all users of the instruction are
310     // outside of the loop.  In this case, it doesn't even matter if the
311     // operands of the instruction are loop invariant.
312     //
313     if (canSinkOrHoistInst(I) && isNotUsedInLoop(I)) {
314       ++II;
315       sink(I);
316     }
317   }
318 }
319
320
321 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
322 /// dominated by the specified block, and that are in the current loop) in depth
323 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
324 /// before uses, allowing us to hoist a loop body in one pass without iteration.
325 ///
326 void LICM::HoistRegion(DominatorTree::Node *N) {
327   assert(N != 0 && "Null dominator tree node?");
328   BasicBlock *BB = N->getBlock();
329
330   // If this subregion is not in the top level loop at all, exit.
331   if (!CurLoop->contains(BB)) return;
332
333   // Only need to process the contents of this block if it is not part of a
334   // subloop (which would already have been processed).
335   if (!inSubLoop(BB))
336     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
337       Instruction &I = *II++;
338       
339       // Try hoisting the instruction out to the preheader.  We can only do this
340       // if all of the operands of the instruction are loop invariant and if it
341       // is safe to hoist the instruction.
342       //
343       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) && 
344           isSafeToExecuteUnconditionally(I))
345           hoist(I);
346       }
347
348   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
349   for (unsigned i = 0, e = Children.size(); i != e; ++i)
350     HoistRegion(Children[i]);
351 }
352
353 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
354 /// instruction.
355 ///
356 bool LICM::canSinkOrHoistInst(Instruction &I) {
357   // Loads have extra constraints we have to verify before we can hoist them.
358   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
359     if (LI->isVolatile())
360       return false;        // Don't hoist volatile loads!
361
362     // Don't hoist loads which have may-aliased stores in loop.
363     return !pointerInvalidatedByLoop(LI->getOperand(0));
364   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
365     // Handle obvious cases efficiently.
366     if (Function *Callee = CI->getCalledFunction()) {
367       if (AA->doesNotAccessMemory(Callee))
368         return true;
369       else if (AA->onlyReadsMemory(Callee)) {
370         // If this call only reads from memory and there are no writes to memory
371         // in the loop, we can hoist or sink the call as appropriate.
372         bool FoundMod = false;
373         for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
374              I != E; ++I) {
375           AliasSet &AS = *I;
376           if (!AS.isForwardingAliasSet() && AS.isMod()) {
377             FoundMod = true;
378             break;
379           }
380         }
381         if (!FoundMod) return true;
382       }
383     }
384
385     // FIXME: This should use mod/ref information to see if we can hoist or sink
386     // the call.
387     
388     return false;
389   }
390
391   return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) || 
392          isa<SelectInst>(I) ||
393          isa<GetElementPtrInst>(I) || isa<VANextInst>(I) || isa<VAArgInst>(I);
394 }
395
396 /// isNotUsedInLoop - Return true if the only users of this instruction are
397 /// outside of the loop.  If this is true, we can sink the instruction to the
398 /// exit blocks of the loop.
399 ///
400 bool LICM::isNotUsedInLoop(Instruction &I) {
401   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
402     Instruction *User = cast<Instruction>(*UI);
403     if (PHINode *PN = dyn_cast<PHINode>(User)) {
404       // PHI node uses occur in predecessor blocks!
405       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
406         if (PN->getIncomingValue(i) == &I)
407           if (CurLoop->contains(PN->getIncomingBlock(i)))
408             return false;
409     } else if (CurLoop->contains(User->getParent())) {
410       return false;
411     }
412   }
413   return true;
414 }
415
416
417 /// isLoopInvariantInst - Return true if all operands of this instruction are
418 /// loop invariant.  We also filter out non-hoistable instructions here just for
419 /// efficiency.
420 ///
421 bool LICM::isLoopInvariantInst(Instruction &I) {
422   // The instruction is loop invariant if all of its operands are loop-invariant
423   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
424     if (!isLoopInvariant(I.getOperand(i)))
425       return false;
426
427   // If we got this far, the instruction is loop invariant!
428   return true;
429 }
430
431 /// sink - When an instruction is found to only be used outside of the loop,
432 /// this function moves it to the exit blocks and patches up SSA form as needed.
433 /// This method is guaranteed to remove the original instruction from its
434 /// position, and may either delete it or move it to outside of the loop.
435 ///
436 void LICM::sink(Instruction &I) {
437   DEBUG(std::cerr << "LICM sinking instruction: " << I);
438
439   std::vector<BasicBlock*> ExitBlocks;
440   CurLoop->getExitBlocks(ExitBlocks);
441
442   if (isa<LoadInst>(I)) ++NumMovedLoads;
443   else if (isa<CallInst>(I)) ++NumMovedCalls;
444   ++NumSunk;
445   Changed = true;
446
447   // The case where there is only a single exit node of this loop is common
448   // enough that we handle it as a special (more efficient) case.  It is more
449   // efficient to handle because there are no PHI nodes that need to be placed.
450   if (ExitBlocks.size() == 1) {
451     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
452       // Instruction is not used, just delete it.
453       CurAST->remove(&I);
454       I.getParent()->getInstList().erase(&I);
455     } else {
456       // Move the instruction to the start of the exit block, after any PHI
457       // nodes in it.
458       I.getParent()->getInstList().remove(&I);
459       
460       BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
461       while (isa<PHINode>(InsertPt)) ++InsertPt;
462       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
463     }
464   } else if (ExitBlocks.size() == 0) {
465     // The instruction is actually dead if there ARE NO exit blocks.
466     CurAST->remove(&I);
467     I.getParent()->getInstList().erase(&I);
468   } else {
469     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
470     // do all of the hard work of inserting PHI nodes as necessary.  We convert
471     // the value into a stack object to get it to do this.
472
473     // Firstly, we create a stack object to hold the value...
474     AllocaInst *AI = new AllocaInst(I.getType(), 0, I.getName(),
475                                    I.getParent()->getParent()->front().begin());
476
477     // Secondly, insert load instructions for each use of the instruction
478     // outside of the loop.
479     while (!I.use_empty()) {
480       Instruction *U = cast<Instruction>(I.use_back());
481
482       // If the user is a PHI Node, we actually have to insert load instructions
483       // in all predecessor blocks, not in the PHI block itself!
484       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
485         // Only insert into each predecessor once, so that we don't have
486         // different incoming values from the same block!
487         std::map<BasicBlock*, Value*> InsertedBlocks;
488         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
489           if (UPN->getIncomingValue(i) == &I) {
490             BasicBlock *Pred = UPN->getIncomingBlock(i);
491             Value *&PredVal = InsertedBlocks[Pred];
492             if (!PredVal) {
493               // Insert a new load instruction right before the terminator in
494               // the predecessor block.
495               PredVal = new LoadInst(AI, "", Pred->getTerminator());
496             }
497
498             UPN->setIncomingValue(i, PredVal);
499           }
500
501       } else {
502         LoadInst *L = new LoadInst(AI, "", U);
503         U->replaceUsesOfWith(&I, L);
504       }
505     }
506
507     // Thirdly, insert a copy of the instruction in each exit block of the loop
508     // that is dominated by the instruction, storing the result into the memory
509     // location.  Be careful not to insert the instruction into any particular
510     // basic block more than once.
511     std::set<BasicBlock*> InsertedBlocks;
512     BasicBlock *InstOrigBB = I.getParent();
513
514     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
515       BasicBlock *ExitBlock = ExitBlocks[i];
516
517       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
518         // If we haven't already processed this exit block, do so now.
519         if (InsertedBlocks.insert(ExitBlock).second) {
520           // Insert the code after the last PHI node...
521           BasicBlock::iterator InsertPt = ExitBlock->begin();
522           while (isa<PHINode>(InsertPt)) ++InsertPt;
523           
524           // If this is the first exit block processed, just move the original
525           // instruction, otherwise clone the original instruction and insert
526           // the copy.
527           Instruction *New;
528           if (InsertedBlocks.size() == 1) {
529             I.getParent()->getInstList().remove(&I);
530             ExitBlock->getInstList().insert(InsertPt, &I);
531             New = &I;
532           } else {
533             New = I.clone();
534             New->setName(I.getName()+".le");
535             ExitBlock->getInstList().insert(InsertPt, New);
536           }
537           
538           // Now that we have inserted the instruction, store it into the alloca
539           new StoreInst(New, AI, InsertPt);
540         }
541       }
542     }
543
544     // If the instruction doesn't dominate any exit blocks, it must be dead.
545     if (InsertedBlocks.empty()) {
546       CurAST->remove(&I);
547       I.getParent()->getInstList().erase(&I);
548     }
549       
550     // Finally, promote the fine value to SSA form.
551     std::vector<AllocaInst*> Allocas;
552     Allocas.push_back(AI);
553     PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData());
554   }
555 }
556
557 /// hoist - When an instruction is found to only use loop invariant operands
558 /// that is safe to hoist, this instruction is called to do the dirty work.
559 ///
560 void LICM::hoist(Instruction &I) {
561   DEBUG(std::cerr << "LICM hoisting to";
562         WriteAsOperand(std::cerr, Preheader, false);
563         std::cerr << ": " << I);
564
565   // Remove the instruction from its current basic block... but don't delete the
566   // instruction.
567   I.getParent()->getInstList().remove(&I);
568
569   // Insert the new node in Preheader, before the terminator.
570   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
571   
572   if (isa<LoadInst>(I)) ++NumMovedLoads;
573   else if (isa<CallInst>(I)) ++NumMovedCalls;
574   ++NumHoisted;
575   Changed = true;
576 }
577
578 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
579 /// not a trapping instruction or if it is a trapping instruction and is
580 /// guaranteed to execute.
581 ///
582 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
583   // If it is not a trapping instruction, it is always safe to hoist.
584   if (!Inst.isTrapping()) return true;
585   
586   // Otherwise we have to check to make sure that the instruction dominates all
587   // of the exit blocks.  If it doesn't, then there is a path out of the loop
588   // which does not execute this instruction, so we can't hoist it.
589
590   // If the instruction is in the header block for the loop (which is very
591   // common), it is always guaranteed to dominate the exit blocks.  Since this
592   // is a common case, and can save some work, check it now.
593   if (Inst.getParent() == CurLoop->getHeader())
594     return true;
595
596   // Get the exit blocks for the current loop.
597   std::vector<BasicBlock*> ExitBlocks;
598   CurLoop->getExitBlocks(ExitBlocks);
599
600   // For each exit block, get the DT node and walk up the DT until the
601   // instruction's basic block is found or we exit the loop.
602   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
603     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
604       return false;
605   
606   return true;
607 }
608
609
610 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
611 /// stores out of the loop and moving loads to before the loop.  We do this by
612 /// looping over the stores in the loop, looking for stores to Must pointers
613 /// which are loop invariant.  We promote these memory locations to use allocas
614 /// instead.  These allocas can easily be raised to register values by the
615 /// PromoteMem2Reg functionality.
616 ///
617 void LICM::PromoteValuesInLoop() {
618   // PromotedValues - List of values that are promoted out of the loop.  Each
619   // value has an alloca instruction for it, and a canonical version of the
620   // pointer.
621   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
622   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
623
624   findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
625   if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
626
627   Changed = true;
628   NumPromoted += PromotedValues.size();
629
630   // Emit a copy from the value into the alloca'd value in the loop preheader
631   TerminatorInst *LoopPredInst = Preheader->getTerminator();
632   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
633     // Load from the memory we are promoting...
634     LoadInst *LI = new LoadInst(PromotedValues[i].second, 
635                                 PromotedValues[i].second->getName()+".promoted",
636                                 LoopPredInst);
637     // Store into the temporary alloca...
638     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
639   }
640   
641   // Scan the basic blocks in the loop, replacing uses of our pointers with
642   // uses of the allocas in question.
643   //
644   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
645   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
646          E = LoopBBs.end(); I != E; ++I) {
647     // Rewrite all loads and stores in the block of the pointer...
648     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
649          II != E; ++II) {
650       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
651         std::map<Value*, AllocaInst*>::iterator
652           I = ValueToAllocaMap.find(L->getOperand(0));
653         if (I != ValueToAllocaMap.end())
654           L->setOperand(0, I->second);    // Rewrite load instruction...
655       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
656         std::map<Value*, AllocaInst*>::iterator
657           I = ValueToAllocaMap.find(S->getOperand(1));
658         if (I != ValueToAllocaMap.end())
659           S->setOperand(1, I->second);    // Rewrite store instruction...
660       }
661     }
662   }
663
664   // Now that the body of the loop uses the allocas instead of the original
665   // memory locations, insert code to copy the alloca value back into the
666   // original memory location on all exits from the loop.  Note that we only
667   // want to insert one copy of the code in each exit block, though the loop may
668   // exit to the same block more than once.
669   //
670   std::set<BasicBlock*> ProcessedBlocks;
671
672   std::vector<BasicBlock*> ExitBlocks;
673   CurLoop->getExitBlocks(ExitBlocks);
674   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
675     if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
676       // Copy all of the allocas into their memory locations...
677       BasicBlock::iterator BI = ExitBlocks[i]->begin();
678       while (isa<PHINode>(*BI))
679         ++BI;             // Skip over all of the phi nodes in the block...
680       Instruction *InsertPos = BI;
681       for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
682         // Load from the alloca...
683         LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
684         // Store into the memory we promoted...
685         new StoreInst(LI, PromotedValues[i].second, InsertPos);
686       }
687     }
688
689   // Now that we have done the deed, use the mem2reg functionality to promote
690   // all of the new allocas we just created into real SSA registers...
691   //
692   std::vector<AllocaInst*> PromotedAllocas;
693   PromotedAllocas.reserve(PromotedValues.size());
694   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
695     PromotedAllocas.push_back(PromotedValues[i].first);
696   PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData());
697 }
698
699 /// findPromotableValuesInLoop - Check the current loop for stores to definite
700 /// pointers, which are not loaded and stored through may aliases.  If these are
701 /// found, create an alloca for the value, add it to the PromotedValues list,
702 /// and keep track of the mapping from value to alloca...
703 ///
704 void LICM::findPromotableValuesInLoop(
705                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
706                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
707   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
708
709   // Loop over all of the alias sets in the tracker object...
710   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
711        I != E; ++I) {
712     AliasSet &AS = *I;
713     // We can promote this alias set if it has a store, if it is a "Must" alias
714     // set, if the pointer is loop invariant, if if we are not eliminating any
715     // volatile loads or stores.
716     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
717         !AS.isVolatile() && isLoopInvariant(AS.begin()->first)) {
718       assert(AS.begin() != AS.end() &&
719              "Must alias set should have at least one pointer element in it!");
720       Value *V = AS.begin()->first;
721
722       // Check that all of the pointers in the alias set have the same type.  We
723       // cannot (yet) promote a memory location that is loaded and stored in
724       // different sizes.
725       bool PointerOk = true;
726       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
727         if (V->getType() != I->first->getType()) {
728           PointerOk = false;
729           break;
730         }
731
732       if (PointerOk) {
733         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
734         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
735         PromotedValues.push_back(std::make_pair(AI, V));
736         
737         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
738           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
739         
740         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
741       }
742     }
743   }
744 }