1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
16 // This pass uses alias analysis for two purposes:
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 mem2reg functionality to construct the appropriate SSA form for the
32 //===----------------------------------------------------------------------===//
34 #define DEBUG_TYPE "licm"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/LoopPass.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/AliasSetTracker.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
46 #include "llvm/Support/CFG.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/ADT/Statistic.h"
54 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
55 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
56 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
57 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
58 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
62 DisablePromotion("disable-licm-promotion", cl::Hidden,
63 cl::desc("Disable memory promotion in LICM pass"));
65 struct VISIBILITY_HIDDEN LICM : public LoopPass {
66 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequiredID(LoopSimplifyID);
74 AU.addRequired<LoopInfo>();
75 AU.addRequired<ETForest>();
76 AU.addRequired<DominatorTree>(); // For scalar promotion (mem2reg)
77 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
78 AU.addRequired<AliasAnalysis>();
81 bool doFinalization() {
82 LoopToAliasMap.clear();
87 // Various analyses that we use...
88 AliasAnalysis *AA; // Current AliasAnalysis information
89 LoopInfo *LI; // Current LoopInfo
90 ETForest *ET; // ETForest for the current Loop...
91 DominatorTree *DT; // Dominator Tree for the current Loop...
92 DominanceFrontier *DF; // Current Dominance Frontier
94 // State that is updated as we process loops
95 bool Changed; // Set to true when we change anything.
96 BasicBlock *Preheader; // The preheader block of the current loop...
97 Loop *CurLoop; // The current loop we are working on...
98 AliasSetTracker *CurAST; // AliasSet information for the current loop...
99 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
101 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
102 /// dominated by the specified block, and that are in the current loop) in
103 /// reverse depth first order w.r.t the ETForest. This allows us to
104 /// visit uses before definitions, allowing us to sink a loop body in one
105 /// pass without iteration.
107 void SinkRegion(BasicBlock *BB);
109 /// HoistRegion - Walk the specified region of the CFG (defined by all
110 /// blocks dominated by the specified block, and that are in the current
111 /// loop) in depth first order w.r.t the ETForest. This allows us to
112 /// visit definitions before uses, allowing us to hoist a loop body in one
113 /// pass without iteration.
115 void HoistRegion(BasicBlock *BB);
117 /// inSubLoop - Little predicate that returns true if the specified basic
118 /// block is in a subloop of the current one, not the current one itself.
120 bool inSubLoop(BasicBlock *BB) {
121 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
122 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
123 if ((*I)->contains(BB))
124 return true; // A subloop actually contains this block!
128 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
129 /// specified exit block of the loop is dominated by the specified block
130 /// that is in the body of the loop. We use these constraints to
131 /// dramatically limit the amount of the dominator tree that needs to be
133 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
134 BasicBlock *BlockInLoop) const {
135 // If the block in the loop is the loop header, it must be dominated!
136 BasicBlock *LoopHeader = CurLoop->getHeader();
137 if (BlockInLoop == LoopHeader)
140 BasicBlock *IDom = ExitBlock;
142 // Because the exit block is not in the loop, we know we have to get _at
143 // least_ its immediate dominator.
145 // Get next Immediate Dominator.
146 IDom = ET->getIDom(IDom);
148 // If we have got to the header of the loop, then the instructions block
149 // did not dominate the exit node, so we can't hoist it.
150 if (IDom == LoopHeader)
153 } while (IDom != BlockInLoop);
158 /// sink - When an instruction is found to only be used outside of the loop,
159 /// this function moves it to the exit blocks and patches up SSA form as
162 void sink(Instruction &I);
164 /// hoist - When an instruction is found to only use loop invariant operands
165 /// that is safe to hoist, this instruction is called to do the dirty work.
167 void hoist(Instruction &I);
169 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
170 /// is not a trapping instruction or if it is a trapping instruction and is
171 /// guaranteed to execute.
173 bool isSafeToExecuteUnconditionally(Instruction &I);
175 /// pointerInvalidatedByLoop - Return true if the body of this loop may
176 /// store into the memory location pointed to by V.
178 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
179 // Check to see if any of the basic blocks in CurLoop invalidate *V.
180 return CurAST->getAliasSetForPointer(V, Size).isMod();
183 bool canSinkOrHoistInst(Instruction &I);
184 bool isLoopInvariantInst(Instruction &I);
185 bool isNotUsedInLoop(Instruction &I);
187 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
188 /// to scalars as we can.
190 void PromoteValuesInLoop();
192 /// FindPromotableValuesInLoop - Check the current loop for stores to
193 /// definite pointers, which are not loaded and stored through may aliases.
194 /// If these are found, create an alloca for the value, add it to the
195 /// PromotedValues list, and keep track of the mapping from value to
198 void FindPromotableValuesInLoop(
199 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
200 std::map<Value*, AllocaInst*> &Val2AlMap);
203 RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
206 LoopPass *llvm::createLICMPass() { return new LICM(); }
208 /// Hoist expressions out of the specified loop...
210 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
213 // Get our Loop and Alias Analysis information...
214 LI = &getAnalysis<LoopInfo>();
215 AA = &getAnalysis<AliasAnalysis>();
216 DF = &getAnalysis<DominanceFrontier>();
217 ET = &getAnalysis<ETForest>();
218 DT = &getAnalysis<DominatorTree>();
220 CurAST = new AliasSetTracker(*AA);
221 // Collect Alias info frmo subloops
222 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
223 LoopItr != LoopItrE; ++LoopItr) {
224 Loop *InnerL = *LoopItr;
225 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
226 assert (InnerAST && "Where is my AST?");
228 // What if InnerLoop was modified by other passes ?
229 CurAST->add(*InnerAST);
234 // Get the preheader block to move instructions into...
235 Preheader = L->getLoopPreheader();
236 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
238 // Loop over the body of this loop, looking for calls, invokes, and stores.
239 // Because subloops have already been incorporated into AST, we skip blocks in
242 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
243 E = L->getBlocks().end(); I != E; ++I)
244 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
245 CurAST->add(**I); // Incorporate the specified basic block
247 // We want to visit all of the instructions in this loop... that are not parts
248 // of our subloops (they have already had their invariants hoisted out of
249 // their loop, into this loop, so there is no need to process the BODIES of
252 // Traverse the body of the loop in depth first order on the dominator tree so
253 // that we are guaranteed to see definitions before we see uses. This allows
254 // us to sink instructions in one pass, without iteration. AFter sinking
255 // instructions, we perform another pass to hoist them out of the loop.
257 SinkRegion(L->getHeader());
258 HoistRegion(L->getHeader());
260 // Now that all loop invariants have been removed from the loop, promote any
261 // memory references to scalars that we can...
262 if (!DisablePromotion)
263 PromoteValuesInLoop();
265 // Clear out loops state information for the next iteration
269 LoopToAliasMap[L] = CurAST;
273 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
274 /// dominated by the specified block, and that are in the current loop) in
275 /// reverse depth first order w.r.t the ETForest. This allows us to visit
276 /// uses before definitions, allowing us to sink a loop body in one pass without
279 void LICM::SinkRegion(BasicBlock *BB) {
280 assert(BB != 0 && "Null sink block?");
282 // If this subregion is not in the top level loop at all, exit.
283 if (!CurLoop->contains(BB)) return;
285 // We are processing blocks in reverse dfo, so process children first...
286 std::vector<BasicBlock*> Children;
287 ET->getChildren(BB, Children);
288 for (unsigned i = 0, e = Children.size(); i != e; ++i)
289 SinkRegion(Children[i]);
291 // Only need to process the contents of this block if it is not part of a
292 // subloop (which would already have been processed).
293 if (inSubLoop(BB)) return;
295 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
296 Instruction &I = *--II;
298 // Check to see if we can sink this instruction to the exit blocks
299 // of the loop. We can do this if the all users of the instruction are
300 // outside of the loop. In this case, it doesn't even matter if the
301 // operands of the instruction are loop invariant.
303 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
311 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
312 /// dominated by the specified block, and that are in the current loop) in depth
313 /// first order w.r.t the DominatorTree. This allows us to visit definitions
314 /// before uses, allowing us to hoist a loop body in one pass without iteration.
316 void LICM::HoistRegion(BasicBlock *BB) {
317 assert(BB != 0 && "Null hoist block?");
319 // If this subregion is not in the top level loop at all, exit.
320 if (!CurLoop->contains(BB)) return;
322 // Only need to process the contents of this block if it is not part of a
323 // subloop (which would already have been processed).
325 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
326 Instruction &I = *II++;
328 // Try hoisting the instruction out to the preheader. We can only do this
329 // if all of the operands of the instruction are loop invariant and if it
330 // is safe to hoist the instruction.
332 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
333 isSafeToExecuteUnconditionally(I))
337 std::vector<BasicBlock*> Children;
338 ET->getChildren(BB, Children);
339 for (unsigned i = 0, e = Children.size(); i != e; ++i)
340 HoistRegion(Children[i]);
343 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
346 bool LICM::canSinkOrHoistInst(Instruction &I) {
347 // Loads have extra constraints we have to verify before we can hoist them.
348 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
349 if (LI->isVolatile())
350 return false; // Don't hoist volatile loads!
352 // Don't hoist loads which have may-aliased stores in loop.
354 if (LI->getType()->isSized())
355 Size = AA->getTargetData().getTypeSize(LI->getType());
356 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
357 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
358 // Handle obvious cases efficiently.
359 if (Function *Callee = CI->getCalledFunction()) {
360 AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
361 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
363 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
364 // If this call only reads from memory and there are no writes to memory
365 // in the loop, we can hoist or sink the call as appropriate.
366 bool FoundMod = false;
367 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
370 if (!AS.isForwardingAliasSet() && AS.isMod()) {
375 if (!FoundMod) return true;
379 // FIXME: This should use mod/ref information to see if we can hoist or sink
385 // Otherwise these instructions are hoistable/sinkable
386 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
387 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I);
390 /// isNotUsedInLoop - Return true if the only users of this instruction are
391 /// outside of the loop. If this is true, we can sink the instruction to the
392 /// exit blocks of the loop.
394 bool LICM::isNotUsedInLoop(Instruction &I) {
395 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
396 Instruction *User = cast<Instruction>(*UI);
397 if (PHINode *PN = dyn_cast<PHINode>(User)) {
398 // PHI node uses occur in predecessor blocks!
399 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
400 if (PN->getIncomingValue(i) == &I)
401 if (CurLoop->contains(PN->getIncomingBlock(i)))
403 } else if (CurLoop->contains(User->getParent())) {
411 /// isLoopInvariantInst - Return true if all operands of this instruction are
412 /// loop invariant. We also filter out non-hoistable instructions here just for
415 bool LICM::isLoopInvariantInst(Instruction &I) {
416 // The instruction is loop invariant if all of its operands are loop-invariant
417 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
418 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
421 // If we got this far, the instruction is loop invariant!
425 /// sink - When an instruction is found to only be used outside of the loop,
426 /// this function moves it to the exit blocks and patches up SSA form as needed.
427 /// This method is guaranteed to remove the original instruction from its
428 /// position, and may either delete it or move it to outside of the loop.
430 void LICM::sink(Instruction &I) {
431 DOUT << "LICM sinking instruction: " << I;
433 std::vector<BasicBlock*> ExitBlocks;
434 CurLoop->getExitBlocks(ExitBlocks);
436 if (isa<LoadInst>(I)) ++NumMovedLoads;
437 else if (isa<CallInst>(I)) ++NumMovedCalls;
441 // The case where there is only a single exit node of this loop is common
442 // enough that we handle it as a special (more efficient) case. It is more
443 // efficient to handle because there are no PHI nodes that need to be placed.
444 if (ExitBlocks.size() == 1) {
445 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
446 // Instruction is not used, just delete it.
447 CurAST->deleteValue(&I);
448 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
449 I.replaceAllUsesWith(UndefValue::get(I.getType()));
452 // Move the instruction to the start of the exit block, after any PHI
454 I.removeFromParent();
456 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
457 while (isa<PHINode>(InsertPt)) ++InsertPt;
458 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
460 } else if (ExitBlocks.size() == 0) {
461 // The instruction is actually dead if there ARE NO exit blocks.
462 CurAST->deleteValue(&I);
463 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
464 I.replaceAllUsesWith(UndefValue::get(I.getType()));
467 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
468 // do all of the hard work of inserting PHI nodes as necessary. We convert
469 // the value into a stack object to get it to do this.
471 // Firstly, we create a stack object to hold the value...
474 if (I.getType() != Type::VoidTy)
475 AI = new AllocaInst(I.getType(), 0, I.getName(),
476 I.getParent()->getParent()->getEntryBlock().begin());
478 // Secondly, insert load instructions for each use of the instruction
479 // outside of the loop.
480 while (!I.use_empty()) {
481 Instruction *U = cast<Instruction>(I.use_back());
483 // If the user is a PHI Node, we actually have to insert load instructions
484 // in all predecessor blocks, not in the PHI block itself!
485 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
486 // Only insert into each predecessor once, so that we don't have
487 // different incoming values from the same block!
488 std::map<BasicBlock*, Value*> InsertedBlocks;
489 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
490 if (UPN->getIncomingValue(i) == &I) {
491 BasicBlock *Pred = UPN->getIncomingBlock(i);
492 Value *&PredVal = InsertedBlocks[Pred];
494 // Insert a new load instruction right before the terminator in
495 // the predecessor block.
496 PredVal = new LoadInst(AI, "", Pred->getTerminator());
499 UPN->setIncomingValue(i, PredVal);
503 LoadInst *L = new LoadInst(AI, "", U);
504 U->replaceUsesOfWith(&I, L);
508 // Thirdly, insert a copy of the instruction in each exit block of the loop
509 // that is dominated by the instruction, storing the result into the memory
510 // location. Be careful not to insert the instruction into any particular
511 // basic block more than once.
512 std::set<BasicBlock*> InsertedBlocks;
513 BasicBlock *InstOrigBB = I.getParent();
515 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
516 BasicBlock *ExitBlock = ExitBlocks[i];
518 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
519 // If we haven't already processed this exit block, do so now.
520 if (InsertedBlocks.insert(ExitBlock).second) {
521 // Insert the code after the last PHI node...
522 BasicBlock::iterator InsertPt = ExitBlock->begin();
523 while (isa<PHINode>(InsertPt)) ++InsertPt;
525 // If this is the first exit block processed, just move the original
526 // instruction, otherwise clone the original instruction and insert
529 if (InsertedBlocks.size() == 1) {
530 I.removeFromParent();
531 ExitBlock->getInstList().insert(InsertPt, &I);
535 CurAST->copyValue(&I, New);
536 if (!I.getName().empty())
537 New->setName(I.getName()+".le");
538 ExitBlock->getInstList().insert(InsertPt, New);
541 // Now that we have inserted the instruction, store it into the alloca
542 if (AI) new StoreInst(New, AI, InsertPt);
547 // If the instruction doesn't dominate any exit blocks, it must be dead.
548 if (InsertedBlocks.empty()) {
549 CurAST->deleteValue(&I);
553 // Finally, promote the fine value to SSA form.
555 std::vector<AllocaInst*> Allocas;
556 Allocas.push_back(AI);
557 PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
562 /// hoist - When an instruction is found to only use loop invariant operands
563 /// that is safe to hoist, this instruction is called to do the dirty work.
565 void LICM::hoist(Instruction &I) {
566 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
568 // Remove the instruction from its current basic block... but don't delete the
570 I.removeFromParent();
572 // Insert the new node in Preheader, before the terminator.
573 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
575 if (isa<LoadInst>(I)) ++NumMovedLoads;
576 else if (isa<CallInst>(I)) ++NumMovedCalls;
581 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
582 /// not a trapping instruction or if it is a trapping instruction and is
583 /// guaranteed to execute.
585 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
586 // If it is not a trapping instruction, it is always safe to hoist.
587 if (!Inst.isTrapping()) return true;
589 // Otherwise we have to check to make sure that the instruction dominates all
590 // of the exit blocks. If it doesn't, then there is a path out of the loop
591 // which does not execute this instruction, so we can't hoist it.
593 // If the instruction is in the header block for the loop (which is very
594 // common), it is always guaranteed to dominate the exit blocks. Since this
595 // is a common case, and can save some work, check it now.
596 if (Inst.getParent() == CurLoop->getHeader())
599 // It's always safe to load from a global or alloca.
600 if (isa<LoadInst>(Inst))
601 if (isa<AllocationInst>(Inst.getOperand(0)) ||
602 isa<GlobalVariable>(Inst.getOperand(0)))
605 // Get the exit blocks for the current loop.
606 std::vector<BasicBlock*> ExitBlocks;
607 CurLoop->getExitBlocks(ExitBlocks);
609 // For each exit block, walk up the ET until the
610 // instruction's basic block is found or we exit the loop.
611 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
612 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
619 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
620 /// stores out of the loop and moving loads to before the loop. We do this by
621 /// looping over the stores in the loop, looking for stores to Must pointers
622 /// which are loop invariant. We promote these memory locations to use allocas
623 /// instead. These allocas can easily be raised to register values by the
624 /// PromoteMem2Reg functionality.
626 void LICM::PromoteValuesInLoop() {
627 // PromotedValues - List of values that are promoted out of the loop. Each
628 // value has an alloca instruction for it, and a canonical version of the
630 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
631 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
633 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
634 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
637 NumPromoted += PromotedValues.size();
639 std::vector<Value*> PointerValueNumbers;
641 // Emit a copy from the value into the alloca'd value in the loop preheader
642 TerminatorInst *LoopPredInst = Preheader->getTerminator();
643 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
644 Value *Ptr = PromotedValues[i].second;
646 // If we are promoting a pointer value, update alias information for the
648 Value *LoadValue = 0;
649 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
650 // Locate a load or store through the pointer, and assign the same value
651 // to LI as we are loading or storing. Since we know that the value is
652 // stored in this loop, this will always succeed.
653 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
655 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
658 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
659 if (SI->getOperand(1) == Ptr) {
660 LoadValue = SI->getOperand(0);
664 assert(LoadValue && "No store through the pointer found!");
665 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
668 // Load from the memory we are promoting.
669 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
671 if (LoadValue) CurAST->copyValue(LoadValue, LI);
673 // Store into the temporary alloca.
674 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
677 // Scan the basic blocks in the loop, replacing uses of our pointers with
678 // uses of the allocas in question.
680 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
681 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
682 E = LoopBBs.end(); I != E; ++I) {
683 // Rewrite all loads and stores in the block of the pointer...
684 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
686 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
687 std::map<Value*, AllocaInst*>::iterator
688 I = ValueToAllocaMap.find(L->getOperand(0));
689 if (I != ValueToAllocaMap.end())
690 L->setOperand(0, I->second); // Rewrite load instruction...
691 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
692 std::map<Value*, AllocaInst*>::iterator
693 I = ValueToAllocaMap.find(S->getOperand(1));
694 if (I != ValueToAllocaMap.end())
695 S->setOperand(1, I->second); // Rewrite store instruction...
700 // Now that the body of the loop uses the allocas instead of the original
701 // memory locations, insert code to copy the alloca value back into the
702 // original memory location on all exits from the loop. Note that we only
703 // want to insert one copy of the code in each exit block, though the loop may
704 // exit to the same block more than once.
706 std::set<BasicBlock*> ProcessedBlocks;
708 std::vector<BasicBlock*> ExitBlocks;
709 CurLoop->getExitBlocks(ExitBlocks);
710 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
711 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
712 // Copy all of the allocas into their memory locations.
713 BasicBlock::iterator BI = ExitBlocks[i]->begin();
714 while (isa<PHINode>(*BI))
715 ++BI; // Skip over all of the phi nodes in the block.
716 Instruction *InsertPos = BI;
718 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
719 // Load from the alloca.
720 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
722 // If this is a pointer type, update alias info appropriately.
723 if (isa<PointerType>(LI->getType()))
724 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
726 // Store into the memory we promoted.
727 new StoreInst(LI, PromotedValues[i].second, InsertPos);
731 // Now that we have done the deed, use the mem2reg functionality to promote
732 // all of the new allocas we just created into real SSA registers.
734 std::vector<AllocaInst*> PromotedAllocas;
735 PromotedAllocas.reserve(PromotedValues.size());
736 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
737 PromotedAllocas.push_back(PromotedValues[i].first);
738 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
741 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
742 /// pointers, which are not loaded and stored through may aliases. If these are
743 /// found, create an alloca for the value, add it to the PromotedValues list,
744 /// and keep track of the mapping from value to alloca.
746 void LICM::FindPromotableValuesInLoop(
747 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
748 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
749 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
751 // Loop over all of the alias sets in the tracker object.
752 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
755 // We can promote this alias set if it has a store, if it is a "Must" alias
756 // set, if the pointer is loop invariant, and if we are not eliminating any
757 // volatile loads or stores.
758 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
759 !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
760 assert(AS.begin() != AS.end() &&
761 "Must alias set should have at least one pointer element in it!");
762 Value *V = AS.begin()->first;
764 // Check that all of the pointers in the alias set have the same type. We
765 // cannot (yet) promote a memory location that is loaded and stored in
767 bool PointerOk = true;
768 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
769 if (V->getType() != I->first->getType()) {
775 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
776 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
777 PromotedValues.push_back(std::make_pair(AI, V));
779 // Update the AST and alias analysis.
780 CurAST->copyValue(V, AI);
782 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
783 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
785 DOUT << "LICM: Promoting value: " << *V << "\n";