LLVM API Documentation

LICM.cpp

Go to the documentation of this file.
00001 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs loop invariant code motion, attempting to remove as much
00011 // code from the body of a loop as possible.  It does this by either hoisting
00012 // code into the preheader block, or by sinking code to the exit blocks if it is
00013 // safe.  This pass also promotes must-aliased memory locations in the loop to
00014 // live in registers, thus hoisting and sinking "invariant" loads and stores.
00015 //
00016 // This pass uses alias analysis for two purposes:
00017 //
00018 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
00019 //     that a load or call inside of a loop never aliases anything stored to,
00020 //     we can hoist it or sink it like any other instruction.
00021 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
00022 //     the loop, we try to move the store to happen AFTER the loop instead of
00023 //     inside of the loop.  This can only happen if a few conditions are true:
00024 //       A. The pointer stored through is loop invariant
00025 //       B. There are no stores or loads in the loop which _may_ alias the
00026 //          pointer.  There are no calls in the loop which mod/ref the pointer.
00027 //     If these conditions are true, we can promote the loads and stores in the
00028 //     loop of the pointer to use a temporary alloca'd variable.  We then use
00029 //     the mem2reg functionality to construct the appropriate SSA form for the
00030 //     variable.
00031 //
00032 //===----------------------------------------------------------------------===//
00033 
00034 #define DEBUG_TYPE "licm"
00035 #include "llvm/Transforms/Scalar.h"
00036 #include "llvm/DerivedTypes.h"
00037 #include "llvm/Instructions.h"
00038 #include "llvm/Target/TargetData.h"
00039 #include "llvm/Analysis/LoopInfo.h"
00040 #include "llvm/Analysis/AliasAnalysis.h"
00041 #include "llvm/Analysis/AliasSetTracker.h"
00042 #include "llvm/Analysis/Dominators.h"
00043 #include "llvm/Support/CFG.h"
00044 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00045 #include "llvm/Transforms/Utils/Local.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/ADT/Statistic.h"
00049 #include <algorithm>
00050 #include <iostream>
00051 using namespace llvm;
00052 
00053 namespace {
00054   cl::opt<bool>
00055   DisablePromotion("disable-licm-promotion", cl::Hidden,
00056                    cl::desc("Disable memory promotion in LICM pass"));
00057 
00058   Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
00059   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
00060   Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
00061   Statistic<> NumMovedCalls("licm", "Number of call insts hoisted or sunk");
00062   Statistic<> NumPromoted("licm",
00063                           "Number of memory locations promoted to registers");
00064 
00065   struct LICM : public FunctionPass {
00066     virtual bool runOnFunction(Function &F);
00067 
00068     /// This transformation requires natural loop information & requires that
00069     /// loop preheaders be inserted into the CFG...
00070     ///
00071     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00072       AU.setPreservesCFG();
00073       AU.addRequiredID(LoopSimplifyID);
00074       AU.addRequired<LoopInfo>();
00075       AU.addRequired<DominatorTree>();
00076       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
00077       AU.addRequired<AliasAnalysis>();
00078     }
00079 
00080   private:
00081     // Various analyses that we use...
00082     AliasAnalysis *AA;       // Current AliasAnalysis information
00083     LoopInfo      *LI;       // Current LoopInfo
00084     DominatorTree *DT;       // Dominator Tree for the current Loop...
00085     DominanceFrontier *DF;   // Current Dominance Frontier
00086 
00087     // State that is updated as we process loops
00088     bool Changed;            // Set to true when we change anything.
00089     BasicBlock *Preheader;   // The preheader block of the current loop...
00090     Loop *CurLoop;           // The current loop we are working on...
00091     AliasSetTracker *CurAST; // AliasSet information for the current loop...
00092 
00093     /// visitLoop - Hoist expressions out of the specified loop...
00094     ///
00095     void visitLoop(Loop *L, AliasSetTracker &AST);
00096 
00097     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
00098     /// dominated by the specified block, and that are in the current loop) in
00099     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
00100     /// visit uses before definitions, allowing us to sink a loop body in one
00101     /// pass without iteration.
00102     ///
00103     void SinkRegion(DominatorTree::Node *N);
00104 
00105     /// HoistRegion - Walk the specified region of the CFG (defined by all
00106     /// blocks dominated by the specified block, and that are in the current
00107     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
00108     /// visit definitions before uses, allowing us to hoist a loop body in one
00109     /// pass without iteration.
00110     ///
00111     void HoistRegion(DominatorTree::Node *N);
00112 
00113     /// inSubLoop - Little predicate that returns true if the specified basic
00114     /// block is in a subloop of the current one, not the current one itself.
00115     ///
00116     bool inSubLoop(BasicBlock *BB) {
00117       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
00118       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
00119         if ((*I)->contains(BB))
00120           return true;  // A subloop actually contains this block!
00121       return false;
00122     }
00123 
00124     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
00125     /// specified exit block of the loop is dominated by the specified block
00126     /// that is in the body of the loop.  We use these constraints to
00127     /// dramatically limit the amount of the dominator tree that needs to be
00128     /// searched.
00129     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
00130                                            BasicBlock *BlockInLoop) const {
00131       // If the block in the loop is the loop header, it must be dominated!
00132       BasicBlock *LoopHeader = CurLoop->getHeader();
00133       if (BlockInLoop == LoopHeader)
00134         return true;
00135 
00136       DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
00137       DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
00138 
00139       // Because the exit block is not in the loop, we know we have to get _at
00140       // least_ its immediate dominator.
00141       do {
00142         // Get next Immediate Dominator.
00143         IDom = IDom->getIDom();
00144 
00145         // If we have got to the header of the loop, then the instructions block
00146         // did not dominate the exit node, so we can't hoist it.
00147         if (IDom->getBlock() == LoopHeader)
00148           return false;
00149 
00150       } while (IDom != BlockInLoopNode);
00151 
00152       return true;
00153     }
00154 
00155     /// sink - When an instruction is found to only be used outside of the loop,
00156     /// this function moves it to the exit blocks and patches up SSA form as
00157     /// needed.
00158     ///
00159     void sink(Instruction &I);
00160 
00161     /// hoist - When an instruction is found to only use loop invariant operands
00162     /// that is safe to hoist, this instruction is called to do the dirty work.
00163     ///
00164     void hoist(Instruction &I);
00165 
00166     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
00167     /// is not a trapping instruction or if it is a trapping instruction and is
00168     /// guaranteed to execute.
00169     ///
00170     bool isSafeToExecuteUnconditionally(Instruction &I);
00171 
00172     /// pointerInvalidatedByLoop - Return true if the body of this loop may
00173     /// store into the memory location pointed to by V.
00174     ///
00175     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
00176       // Check to see if any of the basic blocks in CurLoop invalidate *V.
00177       return CurAST->getAliasSetForPointer(V, Size).isMod();
00178     }
00179 
00180     bool canSinkOrHoistInst(Instruction &I);
00181     bool isLoopInvariantInst(Instruction &I);
00182     bool isNotUsedInLoop(Instruction &I);
00183 
00184     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
00185     /// to scalars as we can.
00186     ///
00187     void PromoteValuesInLoop();
00188 
00189     /// FindPromotableValuesInLoop - Check the current loop for stores to
00190     /// definite pointers, which are not loaded and stored through may aliases.
00191     /// If these are found, create an alloca for the value, add it to the
00192     /// PromotedValues list, and keep track of the mapping from value to
00193     /// alloca...
00194     ///
00195     void FindPromotableValuesInLoop(
00196                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
00197                                     std::map<Value*, AllocaInst*> &Val2AlMap);
00198   };
00199 
00200   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
00201 }
00202 
00203 FunctionPass *llvm::createLICMPass() { return new LICM(); }
00204 
00205 /// runOnFunction - For LICM, this simply traverses the loop structure of the
00206 /// function, hoisting expressions out of loops if possible.
00207 ///
00208 bool LICM::runOnFunction(Function &) {
00209   Changed = false;
00210 
00211   // Get our Loop and Alias Analysis information...
00212   LI = &getAnalysis<LoopInfo>();
00213   AA = &getAnalysis<AliasAnalysis>();
00214   DF = &getAnalysis<DominanceFrontier>();
00215   DT = &getAnalysis<DominatorTree>();
00216 
00217   // Hoist expressions out of all of the top-level loops.
00218   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
00219     AliasSetTracker AST(*AA);
00220     visitLoop(*I, AST);
00221   }
00222   return Changed;
00223 }
00224 
00225 
00226 /// visitLoop - Hoist expressions out of the specified loop...
00227 ///
00228 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
00229   // Recurse through all subloops before we process this loop...
00230   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
00231     AliasSetTracker SubAST(*AA);
00232     visitLoop(*I, SubAST);
00233 
00234     // Incorporate information about the subloops into this loop...
00235     AST.add(SubAST);
00236   }
00237   CurLoop = L;
00238   CurAST = &AST;
00239 
00240   // Get the preheader block to move instructions into...
00241   Preheader = L->getLoopPreheader();
00242   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
00243 
00244   // Loop over the body of this loop, looking for calls, invokes, and stores.
00245   // Because subloops have already been incorporated into AST, we skip blocks in
00246   // subloops.
00247   //
00248   for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
00249          E = L->getBlocks().end(); I != E; ++I)
00250     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
00251       AST.add(**I);                     // Incorporate the specified basic block
00252 
00253   // We want to visit all of the instructions in this loop... that are not parts
00254   // of our subloops (they have already had their invariants hoisted out of
00255   // their loop, into this loop, so there is no need to process the BODIES of
00256   // the subloops).
00257   //
00258   // Traverse the body of the loop in depth first order on the dominator tree so
00259   // that we are guaranteed to see definitions before we see uses.  This allows
00260   // us to sink instructions in one pass, without iteration.  AFter sinking
00261   // instructions, we perform another pass to hoist them out of the loop.
00262   //
00263   SinkRegion(DT->getNode(L->getHeader()));
00264   HoistRegion(DT->getNode(L->getHeader()));
00265 
00266   // Now that all loop invariants have been removed from the loop, promote any
00267   // memory references to scalars that we can...
00268   if (!DisablePromotion)
00269     PromoteValuesInLoop();
00270 
00271   // Clear out loops state information for the next iteration
00272   CurLoop = 0;
00273   Preheader = 0;
00274 }
00275 
00276 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
00277 /// dominated by the specified block, and that are in the current loop) in
00278 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
00279 /// uses before definitions, allowing us to sink a loop body in one pass without
00280 /// iteration.
00281 ///
00282 void LICM::SinkRegion(DominatorTree::Node *N) {
00283   assert(N != 0 && "Null dominator tree node?");
00284   BasicBlock *BB = N->getBlock();
00285 
00286   // If this subregion is not in the top level loop at all, exit.
00287   if (!CurLoop->contains(BB)) return;
00288 
00289   // We are processing blocks in reverse dfo, so process children first...
00290   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
00291   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00292     SinkRegion(Children[i]);
00293 
00294   // Only need to process the contents of this block if it is not part of a
00295   // subloop (which would already have been processed).
00296   if (inSubLoop(BB)) return;
00297 
00298   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
00299     Instruction &I = *--II;
00300 
00301     // Check to see if we can sink this instruction to the exit blocks
00302     // of the loop.  We can do this if the all users of the instruction are
00303     // outside of the loop.  In this case, it doesn't even matter if the
00304     // operands of the instruction are loop invariant.
00305     //
00306     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
00307       ++II;
00308       sink(I);
00309     }
00310   }
00311 }
00312 
00313 
00314 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
00315 /// dominated by the specified block, and that are in the current loop) in depth
00316 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
00317 /// before uses, allowing us to hoist a loop body in one pass without iteration.
00318 ///
00319 void LICM::HoistRegion(DominatorTree::Node *N) {
00320   assert(N != 0 && "Null dominator tree node?");
00321   BasicBlock *BB = N->getBlock();
00322 
00323   // If this subregion is not in the top level loop at all, exit.
00324   if (!CurLoop->contains(BB)) return;
00325 
00326   // Only need to process the contents of this block if it is not part of a
00327   // subloop (which would already have been processed).
00328   if (!inSubLoop(BB))
00329     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
00330       Instruction &I = *II++;
00331 
00332       // Try hoisting the instruction out to the preheader.  We can only do this
00333       // if all of the operands of the instruction are loop invariant and if it
00334       // is safe to hoist the instruction.
00335       //
00336       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
00337           isSafeToExecuteUnconditionally(I))
00338         hoist(I);
00339       }
00340 
00341   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
00342   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00343     HoistRegion(Children[i]);
00344 }
00345 
00346 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
00347 /// instruction.
00348 ///
00349 bool LICM::canSinkOrHoistInst(Instruction &I) {
00350   // Loads have extra constraints we have to verify before we can hoist them.
00351   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
00352     if (LI->isVolatile())
00353       return false;        // Don't hoist volatile loads!
00354 
00355     // Don't hoist loads which have may-aliased stores in loop.
00356     unsigned Size = 0;
00357     if (LI->getType()->isSized())
00358       Size = AA->getTargetData().getTypeSize(LI->getType());
00359     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
00360   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
00361     // Handle obvious cases efficiently.
00362     if (Function *Callee = CI->getCalledFunction()) {
00363       AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
00364       if (Behavior == AliasAnalysis::DoesNotAccessMemory)
00365         return true;
00366       else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
00367         // If this call only reads from memory and there are no writes to memory
00368         // in the loop, we can hoist or sink the call as appropriate.
00369         bool FoundMod = false;
00370         for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
00371              I != E; ++I) {
00372           AliasSet &AS = *I;
00373           if (!AS.isForwardingAliasSet() && AS.isMod()) {
00374             FoundMod = true;
00375             break;
00376           }
00377         }
00378         if (!FoundMod) return true;
00379       }
00380     }
00381 
00382     // FIXME: This should use mod/ref information to see if we can hoist or sink
00383     // the call.
00384 
00385     return false;
00386   }
00387 
00388   return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
00389          isa<SelectInst>(I) || isa<GetElementPtrInst>(I);
00390 }
00391 
00392 /// isNotUsedInLoop - Return true if the only users of this instruction are
00393 /// outside of the loop.  If this is true, we can sink the instruction to the
00394 /// exit blocks of the loop.
00395 ///
00396 bool LICM::isNotUsedInLoop(Instruction &I) {
00397   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
00398     Instruction *User = cast<Instruction>(*UI);
00399     if (PHINode *PN = dyn_cast<PHINode>(User)) {
00400       // PHI node uses occur in predecessor blocks!
00401       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00402         if (PN->getIncomingValue(i) == &I)
00403           if (CurLoop->contains(PN->getIncomingBlock(i)))
00404             return false;
00405     } else if (CurLoop->contains(User->getParent())) {
00406       return false;
00407     }
00408   }
00409   return true;
00410 }
00411 
00412 
00413 /// isLoopInvariantInst - Return true if all operands of this instruction are
00414 /// loop invariant.  We also filter out non-hoistable instructions here just for
00415 /// efficiency.
00416 ///
00417 bool LICM::isLoopInvariantInst(Instruction &I) {
00418   // The instruction is loop invariant if all of its operands are loop-invariant
00419   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00420     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
00421       return false;
00422 
00423   // If we got this far, the instruction is loop invariant!
00424   return true;
00425 }
00426 
00427 /// sink - When an instruction is found to only be used outside of the loop,
00428 /// this function moves it to the exit blocks and patches up SSA form as needed.
00429 /// This method is guaranteed to remove the original instruction from its
00430 /// position, and may either delete it or move it to outside of the loop.
00431 ///
00432 void LICM::sink(Instruction &I) {
00433   DEBUG(std::cerr << "LICM sinking instruction: " << I);
00434 
00435   std::vector<BasicBlock*> ExitBlocks;
00436   CurLoop->getExitBlocks(ExitBlocks);
00437 
00438   if (isa<LoadInst>(I)) ++NumMovedLoads;
00439   else if (isa<CallInst>(I)) ++NumMovedCalls;
00440   ++NumSunk;
00441   Changed = true;
00442 
00443   // The case where there is only a single exit node of this loop is common
00444   // enough that we handle it as a special (more efficient) case.  It is more
00445   // efficient to handle because there are no PHI nodes that need to be placed.
00446   if (ExitBlocks.size() == 1) {
00447     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
00448       // Instruction is not used, just delete it.
00449       CurAST->deleteValue(&I);
00450       I.eraseFromParent();
00451     } else {
00452       // Move the instruction to the start of the exit block, after any PHI
00453       // nodes in it.
00454       I.removeFromParent();
00455 
00456       BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
00457       while (isa<PHINode>(InsertPt)) ++InsertPt;
00458       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
00459     }
00460   } else if (ExitBlocks.size() == 0) {
00461     // The instruction is actually dead if there ARE NO exit blocks.
00462     CurAST->deleteValue(&I);
00463     I.eraseFromParent();
00464   } else {
00465     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
00466     // do all of the hard work of inserting PHI nodes as necessary.  We convert
00467     // the value into a stack object to get it to do this.
00468 
00469     // Firstly, we create a stack object to hold the value...
00470     AllocaInst *AI = 0;
00471 
00472     if (I.getType() != Type::VoidTy)
00473       AI = new AllocaInst(I.getType(), 0, I.getName(),
00474                           I.getParent()->getParent()->front().begin());
00475 
00476     // Secondly, insert load instructions for each use of the instruction
00477     // outside of the loop.
00478     while (!I.use_empty()) {
00479       Instruction *U = cast<Instruction>(I.use_back());
00480 
00481       // If the user is a PHI Node, we actually have to insert load instructions
00482       // in all predecessor blocks, not in the PHI block itself!
00483       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
00484         // Only insert into each predecessor once, so that we don't have
00485         // different incoming values from the same block!
00486         std::map<BasicBlock*, Value*> InsertedBlocks;
00487         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
00488           if (UPN->getIncomingValue(i) == &I) {
00489             BasicBlock *Pred = UPN->getIncomingBlock(i);
00490             Value *&PredVal = InsertedBlocks[Pred];
00491             if (!PredVal) {
00492               // Insert a new load instruction right before the terminator in
00493               // the predecessor block.
00494               PredVal = new LoadInst(AI, "", Pred->getTerminator());
00495             }
00496 
00497             UPN->setIncomingValue(i, PredVal);
00498           }
00499 
00500       } else {
00501         LoadInst *L = new LoadInst(AI, "", U);
00502         U->replaceUsesOfWith(&I, L);
00503       }
00504     }
00505 
00506     // Thirdly, insert a copy of the instruction in each exit block of the loop
00507     // that is dominated by the instruction, storing the result into the memory
00508     // location.  Be careful not to insert the instruction into any particular
00509     // basic block more than once.
00510     std::set<BasicBlock*> InsertedBlocks;
00511     BasicBlock *InstOrigBB = I.getParent();
00512 
00513     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00514       BasicBlock *ExitBlock = ExitBlocks[i];
00515 
00516       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
00517         // If we haven't already processed this exit block, do so now.
00518         if (InsertedBlocks.insert(ExitBlock).second) {
00519           // Insert the code after the last PHI node...
00520           BasicBlock::iterator InsertPt = ExitBlock->begin();
00521           while (isa<PHINode>(InsertPt)) ++InsertPt;
00522 
00523           // If this is the first exit block processed, just move the original
00524           // instruction, otherwise clone the original instruction and insert
00525           // the copy.
00526           Instruction *New;
00527           if (InsertedBlocks.size() == 1) {
00528             I.removeFromParent();
00529             ExitBlock->getInstList().insert(InsertPt, &I);
00530             New = &I;
00531           } else {
00532             New = I.clone();
00533             CurAST->copyValue(&I, New);
00534             if (!I.getName().empty())
00535               New->setName(I.getName()+".le");
00536             ExitBlock->getInstList().insert(InsertPt, New);
00537           }
00538 
00539           // Now that we have inserted the instruction, store it into the alloca
00540           if (AI) new StoreInst(New, AI, InsertPt);
00541         }
00542       }
00543     }
00544 
00545     // If the instruction doesn't dominate any exit blocks, it must be dead.
00546     if (InsertedBlocks.empty()) {
00547       CurAST->deleteValue(&I);
00548       I.eraseFromParent();
00549     }
00550 
00551     // Finally, promote the fine value to SSA form.
00552     if (AI) {
00553       std::vector<AllocaInst*> Allocas;
00554       Allocas.push_back(AI);
00555       PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
00556     }
00557   }
00558 }
00559 
00560 /// hoist - When an instruction is found to only use loop invariant operands
00561 /// that is safe to hoist, this instruction is called to do the dirty work.
00562 ///
00563 void LICM::hoist(Instruction &I) {
00564   DEBUG(std::cerr << "LICM hoisting to " << Preheader->getName()
00565                   << ": " << I);
00566 
00567   // Remove the instruction from its current basic block... but don't delete the
00568   // instruction.
00569   I.removeFromParent();
00570 
00571   // Insert the new node in Preheader, before the terminator.
00572   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
00573 
00574   if (isa<LoadInst>(I)) ++NumMovedLoads;
00575   else if (isa<CallInst>(I)) ++NumMovedCalls;
00576   ++NumHoisted;
00577   Changed = true;
00578 }
00579 
00580 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
00581 /// not a trapping instruction or if it is a trapping instruction and is
00582 /// guaranteed to execute.
00583 ///
00584 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
00585   // If it is not a trapping instruction, it is always safe to hoist.
00586   if (!Inst.isTrapping()) return true;
00587 
00588   // Otherwise we have to check to make sure that the instruction dominates all
00589   // of the exit blocks.  If it doesn't, then there is a path out of the loop
00590   // which does not execute this instruction, so we can't hoist it.
00591 
00592   // If the instruction is in the header block for the loop (which is very
00593   // common), it is always guaranteed to dominate the exit blocks.  Since this
00594   // is a common case, and can save some work, check it now.
00595   if (Inst.getParent() == CurLoop->getHeader())
00596     return true;
00597 
00598   // It's always safe to load from a global or alloca.
00599   if (isa<LoadInst>(Inst))
00600     if (isa<AllocationInst>(Inst.getOperand(0)) ||
00601         isa<GlobalVariable>(Inst.getOperand(0)))
00602       return true;
00603 
00604   // Get the exit blocks for the current loop.
00605   std::vector<BasicBlock*> ExitBlocks;
00606   CurLoop->getExitBlocks(ExitBlocks);
00607 
00608   // For each exit block, get the DT node and walk up the DT until the
00609   // instruction's basic block is found or we exit the loop.
00610   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00611     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
00612       return false;
00613 
00614   return true;
00615 }
00616 
00617 
00618 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
00619 /// stores out of the loop and moving loads to before the loop.  We do this by
00620 /// looping over the stores in the loop, looking for stores to Must pointers
00621 /// which are loop invariant.  We promote these memory locations to use allocas
00622 /// instead.  These allocas can easily be raised to register values by the
00623 /// PromoteMem2Reg functionality.
00624 ///
00625 void LICM::PromoteValuesInLoop() {
00626   // PromotedValues - List of values that are promoted out of the loop.  Each
00627   // value has an alloca instruction for it, and a canonical version of the
00628   // pointer.
00629   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
00630   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
00631 
00632   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
00633   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
00634 
00635   Changed = true;
00636   NumPromoted += PromotedValues.size();
00637 
00638   std::vector<Value*> PointerValueNumbers;
00639 
00640   // Emit a copy from the value into the alloca'd value in the loop preheader
00641   TerminatorInst *LoopPredInst = Preheader->getTerminator();
00642   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
00643     Value *Ptr = PromotedValues[i].second;
00644 
00645     // If we are promoting a pointer value, update alias information for the
00646     // inserted load.
00647     Value *LoadValue = 0;
00648     if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
00649       // Locate a load or store through the pointer, and assign the same value
00650       // to LI as we are loading or storing.  Since we know that the value is
00651       // stored in this loop, this will always succeed.
00652       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
00653            UI != E; ++UI)
00654         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
00655           LoadValue = LI;
00656           break;
00657         } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
00658           if (SI->getOperand(1) == Ptr) {
00659             LoadValue = SI->getOperand(0);
00660             break;
00661           }
00662         }
00663       assert(LoadValue && "No store through the pointer found!");
00664       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
00665     }
00666 
00667     // Load from the memory we are promoting.
00668     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
00669 
00670     if (LoadValue) CurAST->copyValue(LoadValue, LI);
00671 
00672     // Store into the temporary alloca.
00673     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
00674   }
00675 
00676   // Scan the basic blocks in the loop, replacing uses of our pointers with
00677   // uses of the allocas in question.
00678   //
00679   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
00680   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
00681          E = LoopBBs.end(); I != E; ++I) {
00682     // Rewrite all loads and stores in the block of the pointer...
00683     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
00684          II != E; ++II) {
00685       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
00686         std::map<Value*, AllocaInst*>::iterator
00687           I = ValueToAllocaMap.find(L->getOperand(0));
00688         if (I != ValueToAllocaMap.end())
00689           L->setOperand(0, I->second);    // Rewrite load instruction...
00690       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
00691         std::map<Value*, AllocaInst*>::iterator
00692           I = ValueToAllocaMap.find(S->getOperand(1));
00693         if (I != ValueToAllocaMap.end())
00694           S->setOperand(1, I->second);    // Rewrite store instruction...
00695       }
00696     }
00697   }
00698 
00699   // Now that the body of the loop uses the allocas instead of the original
00700   // memory locations, insert code to copy the alloca value back into the
00701   // original memory location on all exits from the loop.  Note that we only
00702   // want to insert one copy of the code in each exit block, though the loop may
00703   // exit to the same block more than once.
00704   //
00705   std::set<BasicBlock*> ProcessedBlocks;
00706 
00707   std::vector<BasicBlock*> ExitBlocks;
00708   CurLoop->getExitBlocks(ExitBlocks);
00709   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00710     if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
00711       // Copy all of the allocas into their memory locations.
00712       BasicBlock::iterator BI = ExitBlocks[i]->begin();
00713       while (isa<PHINode>(*BI))
00714         ++BI;             // Skip over all of the phi nodes in the block.
00715       Instruction *InsertPos = BI;
00716       unsigned PVN = 0;
00717       for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
00718         // Load from the alloca.
00719         LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
00720 
00721         // If this is a pointer type, update alias info appropriately.
00722         if (isa<PointerType>(LI->getType()))
00723           CurAST->copyValue(PointerValueNumbers[PVN++], LI);
00724 
00725         // Store into the memory we promoted.
00726         new StoreInst(LI, PromotedValues[i].second, InsertPos);
00727       }
00728     }
00729 
00730   // Now that we have done the deed, use the mem2reg functionality to promote
00731   // all of the new allocas we just created into real SSA registers.
00732   //
00733   std::vector<AllocaInst*> PromotedAllocas;
00734   PromotedAllocas.reserve(PromotedValues.size());
00735   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
00736     PromotedAllocas.push_back(PromotedValues[i].first);
00737   PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
00738 }
00739 
00740 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
00741 /// pointers, which are not loaded and stored through may aliases.  If these are
00742 /// found, create an alloca for the value, add it to the PromotedValues list,
00743 /// and keep track of the mapping from value to alloca.
00744 ///
00745 void LICM::FindPromotableValuesInLoop(
00746                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
00747                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
00748   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
00749 
00750   // Loop over all of the alias sets in the tracker object.
00751   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
00752        I != E; ++I) {
00753     AliasSet &AS = *I;
00754     // We can promote this alias set if it has a store, if it is a "Must" alias
00755     // set, if the pointer is loop invariant, and if we are not eliminating any
00756     // volatile loads or stores.
00757     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
00758         !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
00759       assert(AS.begin() != AS.end() &&
00760              "Must alias set should have at least one pointer element in it!");
00761       Value *V = AS.begin()->first;
00762 
00763       // Check that all of the pointers in the alias set have the same type.  We
00764       // cannot (yet) promote a memory location that is loaded and stored in
00765       // different sizes.
00766       bool PointerOk = true;
00767       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
00768         if (V->getType() != I->first->getType()) {
00769           PointerOk = false;
00770           break;
00771         }
00772 
00773       if (PointerOk) {
00774         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
00775         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
00776         PromotedValues.push_back(std::make_pair(AI, V));
00777 
00778         // Update the AST and alias analysis.
00779         CurAST->copyValue(V, AI);
00780 
00781         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
00782           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
00783 
00784         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
00785       }
00786     }
00787   }
00788 }