1193323Sed//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This pass performs loop invariant code motion, attempting to remove as much 11193323Sed// code from the body of a loop as possible. It does this by either hoisting 12193323Sed// code into the preheader block, or by sinking code to the exit blocks if it is 13193323Sed// safe. This pass also promotes must-aliased memory locations in the loop to 14193323Sed// live in registers, thus hoisting and sinking "invariant" loads and stores. 15193323Sed// 16193323Sed// This pass uses alias analysis for two purposes: 17193323Sed// 18193323Sed// 1. Moving loop invariant loads and calls out of loops. If we can determine 19193323Sed// that a load or call inside of a loop never aliases anything stored to, 20193323Sed// we can hoist it or sink it like any other instruction. 21193323Sed// 2. Scalar Promotion of Memory - If there is a store instruction inside of 22193323Sed// the loop, we try to move the store to happen AFTER the loop instead of 23193323Sed// inside of the loop. This can only happen if a few conditions are true: 24193323Sed// A. The pointer stored through is loop invariant 25193323Sed// B. There are no stores or loads in the loop which _may_ alias the 26193323Sed// pointer. There are no calls in the loop which mod/ref the pointer. 27193323Sed// If these conditions are true, we can promote the loads and stores in the 28193323Sed// loop of the pointer to use a temporary alloca'd variable. We then use 29212904Sdim// the SSAUpdater to construct the appropriate SSA form for the value. 30193323Sed// 31193323Sed//===----------------------------------------------------------------------===// 32193323Sed 33193323Sed#define DEBUG_TYPE "licm" 34193323Sed#include "llvm/Transforms/Scalar.h" 35252723Sdim#include "llvm/ADT/Statistic.h" 36212904Sdim#include "llvm/Analysis/AliasAnalysis.h" 37212904Sdim#include "llvm/Analysis/AliasSetTracker.h" 38212904Sdim#include "llvm/Analysis/ConstantFolding.h" 39252723Sdim#include "llvm/Analysis/Dominators.h" 40193323Sed#include "llvm/Analysis/LoopInfo.h" 41193323Sed#include "llvm/Analysis/LoopPass.h" 42235633Sdim#include "llvm/Analysis/ValueTracking.h" 43252723Sdim#include "llvm/IR/Constants.h" 44252723Sdim#include "llvm/IR/DataLayout.h" 45252723Sdim#include "llvm/IR/DerivedTypes.h" 46252723Sdim#include "llvm/IR/Instructions.h" 47252723Sdim#include "llvm/IR/IntrinsicInst.h" 48252723Sdim#include "llvm/IR/LLVMContext.h" 49252723Sdim#include "llvm/IR/Metadata.h" 50193323Sed#include "llvm/Support/CFG.h" 51193323Sed#include "llvm/Support/CommandLine.h" 52252723Sdim#include "llvm/Support/Debug.h" 53198090Srdivacky#include "llvm/Support/raw_ostream.h" 54252723Sdim#include "llvm/Target/TargetLibraryInfo.h" 55252723Sdim#include "llvm/Transforms/Utils/Local.h" 56252723Sdim#include "llvm/Transforms/Utils/SSAUpdater.h" 57193323Sed#include <algorithm> 58193323Sedusing namespace llvm; 59193323Sed 60193323SedSTATISTIC(NumSunk , "Number of instructions sunk out of loop"); 61193323SedSTATISTIC(NumHoisted , "Number of instructions hoisted out of loop"); 62193323SedSTATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 63193323SedSTATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 64193323SedSTATISTIC(NumPromoted , "Number of memory locations promoted to registers"); 65193323Sed 66193323Sedstatic cl::opt<bool> 67193323SedDisablePromotion("disable-licm-promotion", cl::Hidden, 68193323Sed cl::desc("Disable memory promotion in LICM pass")); 69193323Sed 70193323Sednamespace { 71198090Srdivacky struct LICM : public LoopPass { 72193323Sed static char ID; // Pass identification, replacement for typeid 73218893Sdim LICM() : LoopPass(ID) { 74218893Sdim initializeLICMPass(*PassRegistry::getPassRegistry()); 75218893Sdim } 76193323Sed 77193323Sed virtual bool runOnLoop(Loop *L, LPPassManager &LPM); 78193323Sed 79193323Sed /// This transformation requires natural loop information & requires that 80193323Sed /// loop preheaders be inserted into the CFG... 81193323Sed /// 82193323Sed virtual void getAnalysisUsage(AnalysisUsage &AU) const { 83193323Sed AU.setPreservesCFG(); 84212904Sdim AU.addRequired<DominatorTree>(); 85212904Sdim AU.addRequired<LoopInfo>(); 86193323Sed AU.addRequiredID(LoopSimplifyID); 87193323Sed AU.addRequired<AliasAnalysis>(); 88212904Sdim AU.addPreserved<AliasAnalysis>(); 89218893Sdim AU.addPreserved("scalar-evolution"); 90198090Srdivacky AU.addPreservedID(LoopSimplifyID); 91235633Sdim AU.addRequired<TargetLibraryInfo>(); 92193323Sed } 93193323Sed 94252723Sdim using llvm::Pass::doFinalization; 95252723Sdim 96193323Sed bool doFinalization() { 97212904Sdim assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets"); 98193323Sed return false; 99193323Sed } 100193323Sed 101193323Sed private: 102193323Sed AliasAnalysis *AA; // Current AliasAnalysis information 103193323Sed LoopInfo *LI; // Current LoopInfo 104212904Sdim DominatorTree *DT; // Dominator Tree for the current Loop. 105193323Sed 106245431Sdim DataLayout *TD; // DataLayout for constant folding. 107235633Sdim TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding. 108235633Sdim 109212904Sdim // State that is updated as we process loops. 110193323Sed bool Changed; // Set to true when we change anything. 111193323Sed BasicBlock *Preheader; // The preheader block of the current loop... 112193323Sed Loop *CurLoop; // The current loop we are working on... 113193323Sed AliasSetTracker *CurAST; // AliasSet information for the current loop... 114245431Sdim bool MayThrow; // The current loop contains an instruction which 115245431Sdim // may throw, thus preventing code motion of 116245431Sdim // instructions with side effects. 117212904Sdim DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap; 118193323Sed 119193323Sed /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 120193323Sed void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L); 121193323Sed 122193323Sed /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 123193323Sed /// set. 124193323Sed void deleteAnalysisValue(Value *V, Loop *L); 125193323Sed 126193323Sed /// SinkRegion - Walk the specified region of the CFG (defined by all blocks 127193323Sed /// dominated by the specified block, and that are in the current loop) in 128193323Sed /// reverse depth first order w.r.t the DominatorTree. This allows us to 129193323Sed /// visit uses before definitions, allowing us to sink a loop body in one 130193323Sed /// pass without iteration. 131193323Sed /// 132193323Sed void SinkRegion(DomTreeNode *N); 133193323Sed 134193323Sed /// HoistRegion - Walk the specified region of the CFG (defined by all 135193323Sed /// blocks dominated by the specified block, and that are in the current 136193323Sed /// loop) in depth first order w.r.t the DominatorTree. This allows us to 137193323Sed /// visit definitions before uses, allowing us to hoist a loop body in one 138193323Sed /// pass without iteration. 139193323Sed /// 140193323Sed void HoistRegion(DomTreeNode *N); 141193323Sed 142193323Sed /// inSubLoop - Little predicate that returns true if the specified basic 143193323Sed /// block is in a subloop of the current one, not the current one itself. 144193323Sed /// 145193323Sed bool inSubLoop(BasicBlock *BB) { 146193323Sed assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 147218893Sdim return LI->getLoopFor(BB) != CurLoop; 148193323Sed } 149193323Sed 150193323Sed /// sink - When an instruction is found to only be used outside of the loop, 151193323Sed /// this function moves it to the exit blocks and patches up SSA form as 152193323Sed /// needed. 153193323Sed /// 154193323Sed void sink(Instruction &I); 155193323Sed 156193323Sed /// hoist - When an instruction is found to only use loop invariant operands 157193323Sed /// that is safe to hoist, this instruction is called to do the dirty work. 158193323Sed /// 159193323Sed void hoist(Instruction &I); 160193323Sed 161193323Sed /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it 162193323Sed /// is not a trapping instruction or if it is a trapping instruction and is 163193323Sed /// guaranteed to execute. 164193323Sed /// 165193323Sed bool isSafeToExecuteUnconditionally(Instruction &I); 166193323Sed 167226890Sdim /// isGuaranteedToExecute - Check that the instruction is guaranteed to 168226890Sdim /// execute. 169226890Sdim /// 170226890Sdim bool isGuaranteedToExecute(Instruction &I); 171226890Sdim 172193323Sed /// pointerInvalidatedByLoop - Return true if the body of this loop may 173193323Sed /// store into the memory location pointed to by V. 174193323Sed /// 175218893Sdim bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 176218893Sdim const MDNode *TBAAInfo) { 177193323Sed // Check to see if any of the basic blocks in CurLoop invalidate *V. 178218893Sdim return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod(); 179193323Sed } 180193323Sed 181193323Sed bool canSinkOrHoistInst(Instruction &I); 182193323Sed bool isNotUsedInLoop(Instruction &I); 183193323Sed 184245431Sdim void PromoteAliasSet(AliasSet &AS, 185245431Sdim SmallVectorImpl<BasicBlock*> &ExitBlocks, 186245431Sdim SmallVectorImpl<Instruction*> &InsertPts); 187193323Sed }; 188193323Sed} 189193323Sed 190193323Sedchar LICM::ID = 0; 191218893SdimINITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false) 192218893SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree) 193218893SdimINITIALIZE_PASS_DEPENDENCY(LoopInfo) 194218893SdimINITIALIZE_PASS_DEPENDENCY(LoopSimplify) 195235633SdimINITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 196218893SdimINITIALIZE_AG_DEPENDENCY(AliasAnalysis) 197218893SdimINITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false) 198193323Sed 199193323SedPass *llvm::createLICMPass() { return new LICM(); } 200193323Sed 201193323Sed/// Hoist expressions out of the specified loop. Note, alias info for inner 202224145Sdim/// loop is not preserved so it is not a good idea to run LICM multiple 203193323Sed/// times on one loop. 204193323Sed/// 205193323Sedbool LICM::runOnLoop(Loop *L, LPPassManager &LPM) { 206193323Sed Changed = false; 207193323Sed 208193323Sed // Get our Loop and Alias Analysis information... 209193323Sed LI = &getAnalysis<LoopInfo>(); 210193323Sed AA = &getAnalysis<AliasAnalysis>(); 211193323Sed DT = &getAnalysis<DominatorTree>(); 212193323Sed 213245431Sdim TD = getAnalysisIfAvailable<DataLayout>(); 214235633Sdim TLI = &getAnalysis<TargetLibraryInfo>(); 215235633Sdim 216193323Sed CurAST = new AliasSetTracker(*AA); 217212904Sdim // Collect Alias info from subloops. 218193323Sed for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end(); 219193323Sed LoopItr != LoopItrE; ++LoopItr) { 220193323Sed Loop *InnerL = *LoopItr; 221212904Sdim AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL]; 222212904Sdim assert(InnerAST && "Where is my AST?"); 223193323Sed 224193323Sed // What if InnerLoop was modified by other passes ? 225193323Sed CurAST->add(*InnerAST); 226224145Sdim 227212904Sdim // Once we've incorporated the inner loop's AST into ours, we don't need the 228212904Sdim // subloop's anymore. 229212904Sdim delete InnerAST; 230212904Sdim LoopToAliasSetMap.erase(InnerL); 231193323Sed } 232224145Sdim 233193323Sed CurLoop = L; 234193323Sed 235193323Sed // Get the preheader block to move instructions into... 236193323Sed Preheader = L->getLoopPreheader(); 237193323Sed 238193323Sed // Loop over the body of this loop, looking for calls, invokes, and stores. 239193323Sed // Because subloops have already been incorporated into AST, we skip blocks in 240193323Sed // subloops. 241193323Sed // 242193323Sed for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 243193323Sed I != E; ++I) { 244193323Sed BasicBlock *BB = *I; 245212904Sdim if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops. 246193323Sed CurAST->add(*BB); // Incorporate the specified basic block 247193323Sed } 248193323Sed 249245431Sdim MayThrow = false; 250245431Sdim // TODO: We've already searched for instructions which may throw in subloops. 251245431Sdim // We may want to reuse this information. 252245431Sdim for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end(); 253245431Sdim (BB != BBE) && !MayThrow ; ++BB) 254245431Sdim for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); 255245431Sdim (I != E) && !MayThrow; ++I) 256245431Sdim MayThrow |= I->mayThrow(); 257245431Sdim 258193323Sed // We want to visit all of the instructions in this loop... that are not parts 259193323Sed // of our subloops (they have already had their invariants hoisted out of 260193323Sed // their loop, into this loop, so there is no need to process the BODIES of 261193323Sed // the subloops). 262193323Sed // 263193323Sed // Traverse the body of the loop in depth first order on the dominator tree so 264193323Sed // that we are guaranteed to see definitions before we see uses. This allows 265193323Sed // us to sink instructions in one pass, without iteration. After sinking 266193323Sed // instructions, we perform another pass to hoist them out of the loop. 267193323Sed // 268199481Srdivacky if (L->hasDedicatedExits()) 269199481Srdivacky SinkRegion(DT->getNode(L->getHeader())); 270199481Srdivacky if (Preheader) 271199481Srdivacky HoistRegion(DT->getNode(L->getHeader())); 272193323Sed 273193323Sed // Now that all loop invariants have been removed from the loop, promote any 274212904Sdim // memory references to scalars that we can. 275212904Sdim if (!DisablePromotion && Preheader && L->hasDedicatedExits()) { 276245431Sdim SmallVector<BasicBlock *, 8> ExitBlocks; 277245431Sdim SmallVector<Instruction *, 8> InsertPts; 278245431Sdim 279212904Sdim // Loop over all of the alias sets in the tracker object. 280212904Sdim for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 281212904Sdim I != E; ++I) 282245431Sdim PromoteAliasSet(*I, ExitBlocks, InsertPts); 283212904Sdim } 284224145Sdim 285193323Sed // Clear out loops state information for the next iteration 286193323Sed CurLoop = 0; 287193323Sed Preheader = 0; 288193323Sed 289212904Sdim // If this loop is nested inside of another one, save the alias information 290212904Sdim // for when we process the outer loop. 291212904Sdim if (L->getParentLoop()) 292212904Sdim LoopToAliasSetMap[L] = CurAST; 293212904Sdim else 294212904Sdim delete CurAST; 295193323Sed return Changed; 296193323Sed} 297193323Sed 298193323Sed/// SinkRegion - Walk the specified region of the CFG (defined by all blocks 299193323Sed/// dominated by the specified block, and that are in the current loop) in 300193323Sed/// reverse depth first order w.r.t the DominatorTree. This allows us to visit 301193323Sed/// uses before definitions, allowing us to sink a loop body in one pass without 302193323Sed/// iteration. 303193323Sed/// 304193323Sedvoid LICM::SinkRegion(DomTreeNode *N) { 305193323Sed assert(N != 0 && "Null dominator tree node?"); 306193323Sed BasicBlock *BB = N->getBlock(); 307193323Sed 308193323Sed // If this subregion is not in the top level loop at all, exit. 309193323Sed if (!CurLoop->contains(BB)) return; 310193323Sed 311212904Sdim // We are processing blocks in reverse dfo, so process children first. 312193323Sed const std::vector<DomTreeNode*> &Children = N->getChildren(); 313193323Sed for (unsigned i = 0, e = Children.size(); i != e; ++i) 314193323Sed SinkRegion(Children[i]); 315193323Sed 316193323Sed // Only need to process the contents of this block if it is not part of a 317193323Sed // subloop (which would already have been processed). 318193323Sed if (inSubLoop(BB)) return; 319193323Sed 320193323Sed for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) { 321193323Sed Instruction &I = *--II; 322224145Sdim 323212904Sdim // If the instruction is dead, we would try to sink it because it isn't used 324212904Sdim // in the loop, instead, just delete it. 325245431Sdim if (isInstructionTriviallyDead(&I, TLI)) { 326212904Sdim DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 327212904Sdim ++II; 328212904Sdim CurAST->deleteValue(&I); 329212904Sdim I.eraseFromParent(); 330212904Sdim Changed = true; 331212904Sdim continue; 332212904Sdim } 333193323Sed 334193323Sed // Check to see if we can sink this instruction to the exit blocks 335193323Sed // of the loop. We can do this if the all users of the instruction are 336193323Sed // outside of the loop. In this case, it doesn't even matter if the 337193323Sed // operands of the instruction are loop invariant. 338193323Sed // 339193323Sed if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) { 340193323Sed ++II; 341193323Sed sink(I); 342193323Sed } 343193323Sed } 344193323Sed} 345193323Sed 346193323Sed/// HoistRegion - Walk the specified region of the CFG (defined by all blocks 347193323Sed/// dominated by the specified block, and that are in the current loop) in depth 348193323Sed/// first order w.r.t the DominatorTree. This allows us to visit definitions 349193323Sed/// before uses, allowing us to hoist a loop body in one pass without iteration. 350193323Sed/// 351193323Sedvoid LICM::HoistRegion(DomTreeNode *N) { 352193323Sed assert(N != 0 && "Null dominator tree node?"); 353193323Sed BasicBlock *BB = N->getBlock(); 354193323Sed 355193323Sed // If this subregion is not in the top level loop at all, exit. 356193323Sed if (!CurLoop->contains(BB)) return; 357193323Sed 358193323Sed // Only need to process the contents of this block if it is not part of a 359193323Sed // subloop (which would already have been processed). 360193323Sed if (!inSubLoop(BB)) 361193323Sed for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) { 362193323Sed Instruction &I = *II++; 363193323Sed 364212904Sdim // Try constant folding this instruction. If all the operands are 365212904Sdim // constants, it is technically hoistable, but it would be better to just 366212904Sdim // fold it. 367235633Sdim if (Constant *C = ConstantFoldInstruction(&I, TD, TLI)) { 368212904Sdim DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'); 369212904Sdim CurAST->copyValue(&I, C); 370212904Sdim CurAST->deleteValue(&I); 371212904Sdim I.replaceAllUsesWith(C); 372212904Sdim I.eraseFromParent(); 373212904Sdim continue; 374212904Sdim } 375224145Sdim 376193323Sed // Try hoisting the instruction out to the preheader. We can only do this 377193323Sed // if all of the operands of the instruction are loop invariant and if it 378193323Sed // is safe to hoist the instruction. 379193323Sed // 380218893Sdim if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) && 381193323Sed isSafeToExecuteUnconditionally(I)) 382193323Sed hoist(I); 383212904Sdim } 384193323Sed 385193323Sed const std::vector<DomTreeNode*> &Children = N->getChildren(); 386193323Sed for (unsigned i = 0, e = Children.size(); i != e; ++i) 387193323Sed HoistRegion(Children[i]); 388193323Sed} 389193323Sed 390193323Sed/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this 391193323Sed/// instruction. 392193323Sed/// 393193323Sedbool LICM::canSinkOrHoistInst(Instruction &I) { 394193323Sed // Loads have extra constraints we have to verify before we can hoist them. 395193323Sed if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 396226890Sdim if (!LI->isUnordered()) 397226890Sdim return false; // Don't hoist volatile/atomic loads! 398193323Sed 399193323Sed // Loads from constant memory are always safe to move, even if they end up 400193323Sed // in the same alias set as something that ends up being modified. 401199989Srdivacky if (AA->pointsToConstantMemory(LI->getOperand(0))) 402193323Sed return true; 403235633Sdim if (LI->getMetadata("invariant.load")) 404235633Sdim return true; 405224145Sdim 406193323Sed // Don't hoist loads which have may-aliased stores in loop. 407218893Sdim uint64_t Size = 0; 408193323Sed if (LI->getType()->isSized()) 409198090Srdivacky Size = AA->getTypeStoreSize(LI->getType()); 410218893Sdim return !pointerInvalidatedByLoop(LI->getOperand(0), Size, 411218893Sdim LI->getMetadata(LLVMContext::MD_tbaa)); 412193323Sed } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 413223017Sdim // Don't sink or hoist dbg info; it's legal, but not useful. 414223017Sdim if (isa<DbgInfoIntrinsic>(I)) 415223017Sdim return false; 416223017Sdim 417223017Sdim // Handle simple cases by querying alias analysis. 418193323Sed AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI); 419193323Sed if (Behavior == AliasAnalysis::DoesNotAccessMemory) 420193323Sed return true; 421218893Sdim if (AliasAnalysis::onlyReadsMemory(Behavior)) { 422193323Sed // If this call only reads from memory and there are no writes to memory 423193323Sed // in the loop, we can hoist or sink the call as appropriate. 424193323Sed bool FoundMod = false; 425193323Sed for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 426193323Sed I != E; ++I) { 427193323Sed AliasSet &AS = *I; 428193323Sed if (!AS.isForwardingAliasSet() && AS.isMod()) { 429193323Sed FoundMod = true; 430193323Sed break; 431193323Sed } 432193323Sed } 433193323Sed if (!FoundMod) return true; 434193323Sed } 435193323Sed 436245431Sdim // FIXME: This should use mod/ref information to see if we can hoist or 437245431Sdim // sink the call. 438193323Sed 439193323Sed return false; 440193323Sed } 441193323Sed 442245431Sdim // Only these instructions are hoistable/sinkable. 443252723Sdim if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 444252723Sdim !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 445252723Sdim !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 446252723Sdim !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 447252723Sdim !isa<InsertValueInst>(I)) 448252723Sdim return false; 449245431Sdim 450245431Sdim return isSafeToExecuteUnconditionally(I); 451193323Sed} 452193323Sed 453193323Sed/// isNotUsedInLoop - Return true if the only users of this instruction are 454193323Sed/// outside of the loop. If this is true, we can sink the instruction to the 455193323Sed/// exit blocks of the loop. 456193323Sed/// 457193323Sedbool LICM::isNotUsedInLoop(Instruction &I) { 458193323Sed for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) { 459193323Sed Instruction *User = cast<Instruction>(*UI); 460193323Sed if (PHINode *PN = dyn_cast<PHINode>(User)) { 461193323Sed // PHI node uses occur in predecessor blocks! 462193323Sed for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 463193323Sed if (PN->getIncomingValue(i) == &I) 464193323Sed if (CurLoop->contains(PN->getIncomingBlock(i))) 465193323Sed return false; 466201360Srdivacky } else if (CurLoop->contains(User)) { 467193323Sed return false; 468193323Sed } 469193323Sed } 470193323Sed return true; 471193323Sed} 472193323Sed 473193323Sed 474193323Sed/// sink - When an instruction is found to only be used outside of the loop, 475193323Sed/// this function moves it to the exit blocks and patches up SSA form as needed. 476193323Sed/// This method is guaranteed to remove the original instruction from its 477193323Sed/// position, and may either delete it or move it to outside of the loop. 478193323Sed/// 479193323Sedvoid LICM::sink(Instruction &I) { 480212904Sdim DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 481193323Sed 482193323Sed SmallVector<BasicBlock*, 8> ExitBlocks; 483212904Sdim CurLoop->getUniqueExitBlocks(ExitBlocks); 484193323Sed 485193323Sed if (isa<LoadInst>(I)) ++NumMovedLoads; 486193323Sed else if (isa<CallInst>(I)) ++NumMovedCalls; 487193323Sed ++NumSunk; 488193323Sed Changed = true; 489193323Sed 490193323Sed // The case where there is only a single exit node of this loop is common 491193323Sed // enough that we handle it as a special (more efficient) case. It is more 492193323Sed // efficient to handle because there are no PHI nodes that need to be placed. 493193323Sed if (ExitBlocks.size() == 1) { 494223017Sdim if (!DT->dominates(I.getParent(), ExitBlocks[0])) { 495193323Sed // Instruction is not used, just delete it. 496193323Sed CurAST->deleteValue(&I); 497198090Srdivacky // If I has users in unreachable blocks, eliminate. 498198090Srdivacky // If I is not void type then replaceAllUsesWith undef. 499198090Srdivacky // This allows ValueHandlers and custom metadata to adjust itself. 500212904Sdim if (!I.use_empty()) 501198090Srdivacky I.replaceAllUsesWith(UndefValue::get(I.getType())); 502193323Sed I.eraseFromParent(); 503193323Sed } else { 504193323Sed // Move the instruction to the start of the exit block, after any PHI 505193323Sed // nodes in it. 506226890Sdim I.moveBefore(ExitBlocks[0]->getFirstInsertionPt()); 507212904Sdim 508212904Sdim // This instruction is no longer in the AST for the current loop, because 509212904Sdim // we just sunk it out of the loop. If we just sunk it into an outer 510212904Sdim // loop, we will rediscover the operation when we process it. 511212904Sdim CurAST->deleteValue(&I); 512193323Sed } 513212904Sdim return; 514212904Sdim } 515224145Sdim 516212904Sdim if (ExitBlocks.empty()) { 517193323Sed // The instruction is actually dead if there ARE NO exit blocks. 518193323Sed CurAST->deleteValue(&I); 519198090Srdivacky // If I has users in unreachable blocks, eliminate. 520198090Srdivacky // If I is not void type then replaceAllUsesWith undef. 521198090Srdivacky // This allows ValueHandlers and custom metadata to adjust itself. 522212904Sdim if (!I.use_empty()) 523198090Srdivacky I.replaceAllUsesWith(UndefValue::get(I.getType())); 524193323Sed I.eraseFromParent(); 525212904Sdim return; 526212904Sdim } 527224145Sdim 528212904Sdim // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the 529212904Sdim // hard work of inserting PHI nodes as necessary. 530212904Sdim SmallVector<PHINode*, 8> NewPHIs; 531212904Sdim SSAUpdater SSA(&NewPHIs); 532224145Sdim 533212904Sdim if (!I.use_empty()) 534212904Sdim SSA.Initialize(I.getType(), I.getName()); 535224145Sdim 536212904Sdim // Insert a copy of the instruction in each exit block of the loop that is 537212904Sdim // dominated by the instruction. Each exit block is known to only be in the 538212904Sdim // ExitBlocks list once. 539212904Sdim BasicBlock *InstOrigBB = I.getParent(); 540212904Sdim unsigned NumInserted = 0; 541224145Sdim 542212904Sdim for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 543212904Sdim BasicBlock *ExitBlock = ExitBlocks[i]; 544224145Sdim 545218893Sdim if (!DT->dominates(InstOrigBB, ExitBlock)) 546212904Sdim continue; 547224145Sdim 548212904Sdim // Insert the code after the last PHI node. 549226890Sdim BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt(); 550224145Sdim 551212904Sdim // If this is the first exit block processed, just move the original 552212904Sdim // instruction, otherwise clone the original instruction and insert 553212904Sdim // the copy. 554212904Sdim Instruction *New; 555212904Sdim if (NumInserted++ == 0) { 556212904Sdim I.moveBefore(InsertPt); 557212904Sdim New = &I; 558212904Sdim } else { 559212904Sdim New = I.clone(); 560212904Sdim if (!I.getName().empty()) 561212904Sdim New->setName(I.getName()+".le"); 562212904Sdim ExitBlock->getInstList().insert(InsertPt, New); 563193323Sed } 564224145Sdim 565212904Sdim // Now that we have inserted the instruction, inform SSAUpdater. 566212904Sdim if (!I.use_empty()) 567212904Sdim SSA.AddAvailableValue(ExitBlock, New); 568193323Sed } 569224145Sdim 570212904Sdim // If the instruction doesn't dominate any exit blocks, it must be dead. 571212904Sdim if (NumInserted == 0) { 572212904Sdim CurAST->deleteValue(&I); 573212904Sdim if (!I.use_empty()) 574212904Sdim I.replaceAllUsesWith(UndefValue::get(I.getType())); 575212904Sdim I.eraseFromParent(); 576212904Sdim return; 577212904Sdim } 578224145Sdim 579212904Sdim // Next, rewrite uses of the instruction, inserting PHI nodes as needed. 580212904Sdim for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) { 581212904Sdim // Grab the use before incrementing the iterator. 582212904Sdim Use &U = UI.getUse(); 583212904Sdim // Increment the iterator before removing the use from the list. 584212904Sdim ++UI; 585212904Sdim SSA.RewriteUseAfterInsertions(U); 586212904Sdim } 587224145Sdim 588212904Sdim // Update CurAST for NewPHIs if I had pointer type. 589212904Sdim if (I.getType()->isPointerTy()) 590212904Sdim for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) 591212904Sdim CurAST->copyValue(&I, NewPHIs[i]); 592224145Sdim 593212904Sdim // Finally, remove the instruction from CurAST. It is no longer in the loop. 594212904Sdim CurAST->deleteValue(&I); 595193323Sed} 596193323Sed 597193323Sed/// hoist - When an instruction is found to only use loop invariant operands 598193323Sed/// that is safe to hoist, this instruction is called to do the dirty work. 599193323Sed/// 600193323Sedvoid LICM::hoist(Instruction &I) { 601202375Srdivacky DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " 602198090Srdivacky << I << "\n"); 603193323Sed 604212904Sdim // Move the new node to the Preheader, before its terminator. 605212904Sdim I.moveBefore(Preheader->getTerminator()); 606193323Sed 607193323Sed if (isa<LoadInst>(I)) ++NumMovedLoads; 608193323Sed else if (isa<CallInst>(I)) ++NumMovedCalls; 609193323Sed ++NumHoisted; 610193323Sed Changed = true; 611193323Sed} 612193323Sed 613193323Sed/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is 614193323Sed/// not a trapping instruction or if it is a trapping instruction and is 615193323Sed/// guaranteed to execute. 616193323Sed/// 617193323Sedbool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) { 618193323Sed // If it is not a trapping instruction, it is always safe to hoist. 619235633Sdim if (isSafeToSpeculativelyExecute(&Inst)) 620198090Srdivacky return true; 621193323Sed 622226890Sdim return isGuaranteedToExecute(Inst); 623226890Sdim} 624226890Sdim 625226890Sdimbool LICM::isGuaranteedToExecute(Instruction &Inst) { 626245431Sdim 627245431Sdim // Somewhere in this loop there is an instruction which may throw and make us 628245431Sdim // exit the loop. 629245431Sdim if (MayThrow) 630245431Sdim return false; 631245431Sdim 632193323Sed // Otherwise we have to check to make sure that the instruction dominates all 633193323Sed // of the exit blocks. If it doesn't, then there is a path out of the loop 634193323Sed // which does not execute this instruction, so we can't hoist it. 635193323Sed 636193323Sed // If the instruction is in the header block for the loop (which is very 637193323Sed // common), it is always guaranteed to dominate the exit blocks. Since this 638193323Sed // is a common case, and can save some work, check it now. 639193323Sed if (Inst.getParent() == CurLoop->getHeader()) 640193323Sed return true; 641193323Sed 642193323Sed // Get the exit blocks for the current loop. 643193323Sed SmallVector<BasicBlock*, 8> ExitBlocks; 644193323Sed CurLoop->getExitBlocks(ExitBlocks); 645193323Sed 646218893Sdim // Verify that the block dominates each of the exit blocks of the loop. 647193323Sed for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 648218893Sdim if (!DT->dominates(Inst.getParent(), ExitBlocks[i])) 649193323Sed return false; 650193323Sed 651245431Sdim // As a degenerate case, if the loop is statically infinite then we haven't 652245431Sdim // proven anything since there are no exit blocks. 653245431Sdim if (ExitBlocks.empty()) 654245431Sdim return false; 655245431Sdim 656193323Sed return true; 657193323Sed} 658193323Sed 659218893Sdimnamespace { 660218893Sdim class LoopPromoter : public LoadAndStorePromoter { 661218893Sdim Value *SomePtr; // Designated pointer to store to. 662218893Sdim SmallPtrSet<Value*, 4> &PointerMustAliases; 663218893Sdim SmallVectorImpl<BasicBlock*> &LoopExitBlocks; 664245431Sdim SmallVectorImpl<Instruction*> &LoopInsertPts; 665218893Sdim AliasSetTracker &AST; 666223017Sdim DebugLoc DL; 667224145Sdim int Alignment; 668252723Sdim MDNode *TBAATag; 669218893Sdim public: 670218893Sdim LoopPromoter(Value *SP, 671218893Sdim const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S, 672218893Sdim SmallPtrSet<Value*, 4> &PMA, 673245431Sdim SmallVectorImpl<BasicBlock*> &LEB, 674245431Sdim SmallVectorImpl<Instruction*> &LIP, 675252723Sdim AliasSetTracker &ast, DebugLoc dl, int alignment, 676252723Sdim MDNode *TBAATag) 677224145Sdim : LoadAndStorePromoter(Insts, S), SomePtr(SP), 678245431Sdim PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP), 679252723Sdim AST(ast), DL(dl), Alignment(alignment), TBAATag(TBAATag) {} 680224145Sdim 681218893Sdim virtual bool isInstInList(Instruction *I, 682218893Sdim const SmallVectorImpl<Instruction*> &) const { 683218893Sdim Value *Ptr; 684218893Sdim if (LoadInst *LI = dyn_cast<LoadInst>(I)) 685218893Sdim Ptr = LI->getOperand(0); 686218893Sdim else 687218893Sdim Ptr = cast<StoreInst>(I)->getPointerOperand(); 688218893Sdim return PointerMustAliases.count(Ptr); 689218893Sdim } 690224145Sdim 691218893Sdim virtual void doExtraRewritesBeforeFinalDeletion() const { 692218893Sdim // Insert stores after in the loop exit blocks. Each exit block gets a 693218893Sdim // store of the live-out values that feed them. Since we've already told 694218893Sdim // the SSA updater about the defs in the loop and the preheader 695218893Sdim // definition, it is all set and we can start using it. 696218893Sdim for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 697218893Sdim BasicBlock *ExitBlock = LoopExitBlocks[i]; 698218893Sdim Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 699245431Sdim Instruction *InsertPos = LoopInsertPts[i]; 700223017Sdim StoreInst *NewSI = new StoreInst(LiveInValue, SomePtr, InsertPos); 701224145Sdim NewSI->setAlignment(Alignment); 702223017Sdim NewSI->setDebugLoc(DL); 703252723Sdim if (TBAATag) NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag); 704218893Sdim } 705218893Sdim } 706218893Sdim 707218893Sdim virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const { 708218893Sdim // Update alias analysis. 709218893Sdim AST.copyValue(LI, V); 710218893Sdim } 711218893Sdim virtual void instructionDeleted(Instruction *I) const { 712218893Sdim AST.deleteValue(I); 713218893Sdim } 714218893Sdim }; 715218893Sdim} // end anon namespace 716218893Sdim 717212904Sdim/// PromoteAliasSet - Try to promote memory values to scalars by sinking 718193323Sed/// stores out of the loop and moving loads to before the loop. We do this by 719193323Sed/// looping over the stores in the loop, looking for stores to Must pointers 720212904Sdim/// which are loop invariant. 721193323Sed/// 722245431Sdimvoid LICM::PromoteAliasSet(AliasSet &AS, 723245431Sdim SmallVectorImpl<BasicBlock*> &ExitBlocks, 724245431Sdim SmallVectorImpl<Instruction*> &InsertPts) { 725212904Sdim // We can promote this alias set if it has a store, if it is a "Must" alias 726212904Sdim // set, if the pointer is loop invariant, and if we are not eliminating any 727212904Sdim // volatile loads or stores. 728212904Sdim if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 729212904Sdim AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 730212904Sdim return; 731224145Sdim 732212904Sdim assert(!AS.empty() && 733212904Sdim "Must alias set should have at least one pointer element in it!"); 734212904Sdim Value *SomePtr = AS.begin()->getValue(); 735193323Sed 736212904Sdim // It isn't safe to promote a load/store from the loop if the load/store is 737212904Sdim // conditional. For example, turning: 738193323Sed // 739212904Sdim // for () { if (c) *P += 1; } 740193323Sed // 741212904Sdim // into: 742212904Sdim // 743212904Sdim // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 744212904Sdim // 745212904Sdim // is not safe, because *P may only be valid to access if 'c' is true. 746224145Sdim // 747212904Sdim // It is safe to promote P if all uses are direct load/stores and if at 748212904Sdim // least one is guaranteed to be executed. 749212904Sdim bool GuaranteedToExecute = false; 750224145Sdim 751212904Sdim SmallVector<Instruction*, 64> LoopUses; 752212904Sdim SmallPtrSet<Value*, 4> PointerMustAliases; 753193323Sed 754224145Sdim // We start with an alignment of one and try to find instructions that allow 755224145Sdim // us to prove better alignment. 756224145Sdim unsigned Alignment = 1; 757252723Sdim MDNode *TBAATag = 0; 758224145Sdim 759212904Sdim // Check that all of the pointers in the alias set have the same type. We 760212904Sdim // cannot (yet) promote a memory location that is loaded and stored in 761252723Sdim // different sizes. While we are at it, collect alignment and TBAA info. 762212904Sdim for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) { 763212904Sdim Value *ASIV = ASI->getValue(); 764212904Sdim PointerMustAliases.insert(ASIV); 765224145Sdim 766193323Sed // Check that all of the pointers in the alias set have the same type. We 767193323Sed // cannot (yet) promote a memory location that is loaded and stored in 768193323Sed // different sizes. 769212904Sdim if (SomePtr->getType() != ASIV->getType()) 770212904Sdim return; 771224145Sdim 772212904Sdim for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end(); 773193323Sed UI != UE; ++UI) { 774212904Sdim // Ignore instructions that are outside the loop. 775193323Sed Instruction *Use = dyn_cast<Instruction>(*UI); 776201360Srdivacky if (!Use || !CurLoop->contains(Use)) 777193323Sed continue; 778224145Sdim 779212904Sdim // If there is an non-load/store instruction in the loop, we can't promote 780212904Sdim // it. 781224145Sdim if (LoadInst *load = dyn_cast<LoadInst>(Use)) { 782226890Sdim assert(!load->isVolatile() && "AST broken"); 783226890Sdim if (!load->isSimple()) 784226890Sdim return; 785224145Sdim } else if (StoreInst *store = dyn_cast<StoreInst>(Use)) { 786218893Sdim // Stores *of* the pointer are not interesting, only stores *to* the 787218893Sdim // pointer. 788218893Sdim if (Use->getOperand(1) != ASIV) 789218893Sdim continue; 790226890Sdim assert(!store->isVolatile() && "AST broken"); 791226890Sdim if (!store->isSimple()) 792226890Sdim return; 793226890Sdim 794226890Sdim // Note that we only check GuaranteedToExecute inside the store case 795226890Sdim // so that we do not introduce stores where they did not exist before 796226890Sdim // (which would break the LLVM concurrency model). 797226890Sdim 798226890Sdim // If the alignment of this instruction allows us to specify a more 799226890Sdim // restrictive (and performant) alignment and if we are sure this 800226890Sdim // instruction will be executed, update the alignment. 801226890Sdim // Larger is better, with the exception of 0 being the best alignment. 802226890Sdim unsigned InstAlignment = store->getAlignment(); 803252723Sdim if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0) 804226890Sdim if (isGuaranteedToExecute(*Use)) { 805226890Sdim GuaranteedToExecute = true; 806226890Sdim Alignment = InstAlignment; 807226890Sdim } 808226890Sdim 809226890Sdim if (!GuaranteedToExecute) 810226890Sdim GuaranteedToExecute = isGuaranteedToExecute(*Use); 811226890Sdim 812212904Sdim } else 813212904Sdim return; // Not a load or store. 814224145Sdim 815252723Sdim // Merge the TBAA tags. 816252723Sdim if (LoopUses.empty()) { 817252723Sdim // On the first load/store, just take its TBAA tag. 818252723Sdim TBAATag = Use->getMetadata(LLVMContext::MD_tbaa); 819252723Sdim } else if (TBAATag) { 820252723Sdim TBAATag = MDNode::getMostGenericTBAA(TBAATag, 821252723Sdim Use->getMetadata(LLVMContext::MD_tbaa)); 822252723Sdim } 823252723Sdim 824212904Sdim LoopUses.push_back(Use); 825193323Sed } 826212904Sdim } 827224145Sdim 828212904Sdim // If there isn't a guaranteed-to-execute instruction, we can't promote. 829212904Sdim if (!GuaranteedToExecute) 830212904Sdim return; 831224145Sdim 832212904Sdim // Otherwise, this is safe to promote, lets do it! 833224145Sdim DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n'); 834212904Sdim Changed = true; 835212904Sdim ++NumPromoted; 836193323Sed 837223017Sdim // Grab a debug location for the inserted loads/stores; given that the 838223017Sdim // inserted loads/stores have little relation to the original loads/stores, 839223017Sdim // this code just arbitrarily picks a location from one, since any debug 840223017Sdim // location is better than none. 841223017Sdim DebugLoc DL = LoopUses[0]->getDebugLoc(); 842223017Sdim 843245431Sdim // Figure out the loop exits and their insertion points, if this is the 844245431Sdim // first promotion. 845245431Sdim if (ExitBlocks.empty()) { 846245431Sdim CurLoop->getUniqueExitBlocks(ExitBlocks); 847245431Sdim InsertPts.resize(ExitBlocks.size()); 848245431Sdim for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 849245431Sdim InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt(); 850245431Sdim } 851224145Sdim 852212904Sdim // We use the SSAUpdater interface to insert phi nodes as required. 853212904Sdim SmallVector<PHINode*, 16> NewPHIs; 854212904Sdim SSAUpdater SSA(&NewPHIs); 855218893Sdim LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 856252723Sdim InsertPts, *CurAST, DL, Alignment, TBAATag); 857224145Sdim 858218893Sdim // Set up the preheader to have a definition of the value. It is the live-out 859218893Sdim // value from the preheader that uses in the loop will use. 860218893Sdim LoadInst *PreheaderLoad = 861218893Sdim new LoadInst(SomePtr, SomePtr->getName()+".promoted", 862218893Sdim Preheader->getTerminator()); 863224145Sdim PreheaderLoad->setAlignment(Alignment); 864223017Sdim PreheaderLoad->setDebugLoc(DL); 865252723Sdim if (TBAATag) PreheaderLoad->setMetadata(LLVMContext::MD_tbaa, TBAATag); 866218893Sdim SSA.AddAvailableValue(Preheader, PreheaderLoad); 867212904Sdim 868218893Sdim // Rewrite all the loads in the loop and remember all the definitions from 869218893Sdim // stores in the loop. 870218893Sdim Promoter.run(LoopUses); 871221345Sdim 872221345Sdim // If the SSAUpdater didn't use the load in the preheader, just zap it now. 873221345Sdim if (PreheaderLoad->use_empty()) 874221345Sdim PreheaderLoad->eraseFromParent(); 875193323Sed} 876193323Sed 877212904Sdim 878193323Sed/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 879193323Sedvoid LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) { 880212904Sdim AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 881193323Sed if (!AST) 882193323Sed return; 883193323Sed 884193323Sed AST->copyValue(From, To); 885193323Sed} 886193323Sed 887193323Sed/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 888193323Sed/// set. 889193323Sedvoid LICM::deleteAnalysisValue(Value *V, Loop *L) { 890212904Sdim AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 891193323Sed if (!AST) 892193323Sed return; 893193323Sed 894193323Sed AST->deleteValue(V); 895193323Sed} 896