LICM.cpp revision 8f78a58e14fa754cde827e46ad03f00c7a6ead01
1//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass performs loop invariant code motion, attempting to remove as much 11// code from the body of a loop as possible. It does this by either hoisting 12// code into the preheader block, or by sinking code to the exit blocks if it is 13// safe. This pass also promotes must-aliased memory locations in the loop to 14// live in registers, thus hoisting and sinking "invariant" loads and stores. 15// 16// This pass uses alias analysis for two purposes: 17// 18// 1. Moving loop invariant loads and calls out of loops. If we can determine 19// that a load or call inside of a loop never aliases anything stored to, 20// we can hoist it or sink it like any other instruction. 21// 2. Scalar Promotion of Memory - If there is a store instruction inside of 22// the loop, we try to move the store to happen AFTER the loop instead of 23// inside of the loop. This can only happen if a few conditions are true: 24// A. The pointer stored through is loop invariant 25// B. There are no stores or loads in the loop which _may_ alias the 26// pointer. There are no calls in the loop which mod/ref the pointer. 27// If these conditions are true, we can promote the loads and stores in the 28// loop of the pointer to use a temporary alloca'd variable. We then use 29// the mem2reg functionality to construct the appropriate SSA form for the 30// variable. 31// 32//===----------------------------------------------------------------------===// 33 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/LLVMContext.h" 40#include "llvm/Target/TargetData.h" 41#include "llvm/Analysis/LoopInfo.h" 42#include "llvm/Analysis/LoopPass.h" 43#include "llvm/Analysis/AliasAnalysis.h" 44#include "llvm/Analysis/AliasSetTracker.h" 45#include "llvm/Analysis/Dominators.h" 46#include "llvm/Analysis/ScalarEvolution.h" 47#include "llvm/Transforms/Utils/PromoteMemToReg.h" 48#include "llvm/Support/CFG.h" 49#include "llvm/Support/CommandLine.h" 50#include "llvm/Support/raw_ostream.h" 51#include "llvm/Support/Debug.h" 52#include "llvm/ADT/Statistic.h" 53#include <algorithm> 54using namespace llvm; 55 56STATISTIC(NumSunk , "Number of instructions sunk out of loop"); 57STATISTIC(NumHoisted , "Number of instructions hoisted out of loop"); 58STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 59STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 60STATISTIC(NumPromoted , "Number of memory locations promoted to registers"); 61 62static cl::opt<bool> 63DisablePromotion("disable-licm-promotion", cl::Hidden, 64 cl::desc("Disable memory promotion in LICM pass")); 65 66// This feature is currently disabled by default because CodeGen is not yet 67// capable of rematerializing these constants in PIC mode, so it can lead to 68// degraded performance. Compile test/CodeGen/X86/remat-constant.ll with 69// -relocation-model=pic to see an example of this. 70static cl::opt<bool> 71EnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden, 72 cl::desc("Enable hoisting/sinking of constant " 73 "global variables")); 74 75namespace { 76 struct LICM : public LoopPass { 77 static char ID; // Pass identification, replacement for typeid 78 LICM() : LoopPass(&ID) {} 79 80 virtual bool runOnLoop(Loop *L, LPPassManager &LPM); 81 82 /// This transformation requires natural loop information & requires that 83 /// loop preheaders be inserted into the CFG... 84 /// 85 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 86 AU.setPreservesCFG(); 87 AU.addRequiredID(LoopSimplifyID); 88 AU.addRequired<LoopInfo>(); 89 AU.addRequired<DominatorTree>(); 90 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg) 91 AU.addRequired<AliasAnalysis>(); 92 AU.addPreserved<ScalarEvolution>(); 93 AU.addPreserved<DominanceFrontier>(); 94 } 95 96 bool doFinalization() { 97 // Free the values stored in the map 98 for (std::map<Loop *, AliasSetTracker *>::iterator 99 I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I) 100 delete I->second; 101 102 LoopToAliasMap.clear(); 103 return false; 104 } 105 106 private: 107 // Various analyses that we use... 108 AliasAnalysis *AA; // Current AliasAnalysis information 109 LoopInfo *LI; // Current LoopInfo 110 DominatorTree *DT; // Dominator Tree for the current Loop... 111 DominanceFrontier *DF; // Current Dominance Frontier 112 113 // State that is updated as we process loops 114 bool Changed; // Set to true when we change anything. 115 BasicBlock *Preheader; // The preheader block of the current loop... 116 Loop *CurLoop; // The current loop we are working on... 117 AliasSetTracker *CurAST; // AliasSet information for the current loop... 118 std::map<Loop *, AliasSetTracker *> LoopToAliasMap; 119 120 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 121 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L); 122 123 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 124 /// set. 125 void deleteAnalysisValue(Value *V, Loop *L); 126 127 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks 128 /// dominated by the specified block, and that are in the current loop) in 129 /// reverse depth first order w.r.t the DominatorTree. This allows us to 130 /// visit uses before definitions, allowing us to sink a loop body in one 131 /// pass without iteration. 132 /// 133 void SinkRegion(DomTreeNode *N); 134 135 /// HoistRegion - Walk the specified region of the CFG (defined by all 136 /// blocks dominated by the specified block, and that are in the current 137 /// loop) in depth first order w.r.t the DominatorTree. This allows us to 138 /// visit definitions before uses, allowing us to hoist a loop body in one 139 /// pass without iteration. 140 /// 141 void HoistRegion(DomTreeNode *N); 142 143 /// inSubLoop - Little predicate that returns true if the specified basic 144 /// block is in a subloop of the current one, not the current one itself. 145 /// 146 bool inSubLoop(BasicBlock *BB) { 147 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 148 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I) 149 if ((*I)->contains(BB)) 150 return true; // A subloop actually contains this block! 151 return false; 152 } 153 154 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the 155 /// specified exit block of the loop is dominated by the specified block 156 /// that is in the body of the loop. We use these constraints to 157 /// dramatically limit the amount of the dominator tree that needs to be 158 /// searched. 159 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock, 160 BasicBlock *BlockInLoop) const { 161 // If the block in the loop is the loop header, it must be dominated! 162 BasicBlock *LoopHeader = CurLoop->getHeader(); 163 if (BlockInLoop == LoopHeader) 164 return true; 165 166 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop); 167 DomTreeNode *IDom = DT->getNode(ExitBlock); 168 169 // Because the exit block is not in the loop, we know we have to get _at 170 // least_ its immediate dominator. 171 do { 172 // Get next Immediate Dominator. 173 IDom = IDom->getIDom(); 174 175 // If we have got to the header of the loop, then the instructions block 176 // did not dominate the exit node, so we can't hoist it. 177 if (IDom->getBlock() == LoopHeader) 178 return false; 179 180 } while (IDom != BlockInLoopNode); 181 182 return true; 183 } 184 185 /// sink - When an instruction is found to only be used outside of the loop, 186 /// this function moves it to the exit blocks and patches up SSA form as 187 /// needed. 188 /// 189 void sink(Instruction &I); 190 191 /// hoist - When an instruction is found to only use loop invariant operands 192 /// that is safe to hoist, this instruction is called to do the dirty work. 193 /// 194 void hoist(Instruction &I); 195 196 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it 197 /// is not a trapping instruction or if it is a trapping instruction and is 198 /// guaranteed to execute. 199 /// 200 bool isSafeToExecuteUnconditionally(Instruction &I); 201 202 /// pointerInvalidatedByLoop - Return true if the body of this loop may 203 /// store into the memory location pointed to by V. 204 /// 205 bool pointerInvalidatedByLoop(Value *V, unsigned Size) { 206 // Check to see if any of the basic blocks in CurLoop invalidate *V. 207 return CurAST->getAliasSetForPointer(V, Size).isMod(); 208 } 209 210 bool canSinkOrHoistInst(Instruction &I); 211 bool isLoopInvariantInst(Instruction &I); 212 bool isNotUsedInLoop(Instruction &I); 213 214 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many 215 /// to scalars as we can. 216 /// 217 void PromoteValuesInLoop(); 218 219 /// FindPromotableValuesInLoop - Check the current loop for stores to 220 /// definite pointers, which are not loaded and stored through may aliases. 221 /// If these are found, create an alloca for the value, add it to the 222 /// PromotedValues list, and keep track of the mapping from value to 223 /// alloca... 224 /// 225 void FindPromotableValuesInLoop( 226 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues, 227 std::map<Value*, AllocaInst*> &Val2AlMap); 228 }; 229} 230 231char LICM::ID = 0; 232static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion"); 233 234Pass *llvm::createLICMPass() { return new LICM(); } 235 236/// Hoist expressions out of the specified loop. Note, alias info for inner 237/// loop is not preserved so it is not a good idea to run LICM multiple 238/// times on one loop. 239/// 240bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) { 241 Changed = false; 242 243 // Get our Loop and Alias Analysis information... 244 LI = &getAnalysis<LoopInfo>(); 245 AA = &getAnalysis<AliasAnalysis>(); 246 DF = &getAnalysis<DominanceFrontier>(); 247 DT = &getAnalysis<DominatorTree>(); 248 249 CurAST = new AliasSetTracker(*AA); 250 // Collect Alias info from subloops 251 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end(); 252 LoopItr != LoopItrE; ++LoopItr) { 253 Loop *InnerL = *LoopItr; 254 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL]; 255 assert (InnerAST && "Where is my AST?"); 256 257 // What if InnerLoop was modified by other passes ? 258 CurAST->add(*InnerAST); 259 } 260 261 CurLoop = L; 262 263 // Get the preheader block to move instructions into... 264 Preheader = L->getLoopPreheader(); 265 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!"); 266 267 // Loop over the body of this loop, looking for calls, invokes, and stores. 268 // Because subloops have already been incorporated into AST, we skip blocks in 269 // subloops. 270 // 271 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 272 I != E; ++I) { 273 BasicBlock *BB = *I; 274 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops... 275 CurAST->add(*BB); // Incorporate the specified basic block 276 } 277 278 // We want to visit all of the instructions in this loop... that are not parts 279 // of our subloops (they have already had their invariants hoisted out of 280 // their loop, into this loop, so there is no need to process the BODIES of 281 // the subloops). 282 // 283 // Traverse the body of the loop in depth first order on the dominator tree so 284 // that we are guaranteed to see definitions before we see uses. This allows 285 // us to sink instructions in one pass, without iteration. After sinking 286 // instructions, we perform another pass to hoist them out of the loop. 287 // 288 SinkRegion(DT->getNode(L->getHeader())); 289 HoistRegion(DT->getNode(L->getHeader())); 290 291 // Now that all loop invariants have been removed from the loop, promote any 292 // memory references to scalars that we can... 293 if (!DisablePromotion) 294 PromoteValuesInLoop(); 295 296 // Clear out loops state information for the next iteration 297 CurLoop = 0; 298 Preheader = 0; 299 300 LoopToAliasMap[L] = CurAST; 301 return Changed; 302} 303 304/// SinkRegion - Walk the specified region of the CFG (defined by all blocks 305/// dominated by the specified block, and that are in the current loop) in 306/// reverse depth first order w.r.t the DominatorTree. This allows us to visit 307/// uses before definitions, allowing us to sink a loop body in one pass without 308/// iteration. 309/// 310void LICM::SinkRegion(DomTreeNode *N) { 311 assert(N != 0 && "Null dominator tree node?"); 312 BasicBlock *BB = N->getBlock(); 313 314 // If this subregion is not in the top level loop at all, exit. 315 if (!CurLoop->contains(BB)) return; 316 317 // We are processing blocks in reverse dfo, so process children first... 318 const std::vector<DomTreeNode*> &Children = N->getChildren(); 319 for (unsigned i = 0, e = Children.size(); i != e; ++i) 320 SinkRegion(Children[i]); 321 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). 324 if (inSubLoop(BB)) return; 325 326 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) { 327 Instruction &I = *--II; 328 329 // Check to see if we can sink this instruction to the exit blocks 330 // of the loop. We can do this if the all users of the instruction are 331 // outside of the loop. In this case, it doesn't even matter if the 332 // operands of the instruction are loop invariant. 333 // 334 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) { 335 ++II; 336 sink(I); 337 } 338 } 339} 340 341 342/// HoistRegion - Walk the specified region of the CFG (defined by all blocks 343/// dominated by the specified block, and that are in the current loop) in depth 344/// first order w.r.t the DominatorTree. This allows us to visit definitions 345/// before uses, allowing us to hoist a loop body in one pass without iteration. 346/// 347void LICM::HoistRegion(DomTreeNode *N) { 348 assert(N != 0 && "Null dominator tree node?"); 349 BasicBlock *BB = N->getBlock(); 350 351 // If this subregion is not in the top level loop at all, exit. 352 if (!CurLoop->contains(BB)) return; 353 354 // Only need to process the contents of this block if it is not part of a 355 // subloop (which would already have been processed). 356 if (!inSubLoop(BB)) 357 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) { 358 Instruction &I = *II++; 359 360 // Try hoisting the instruction out to the preheader. We can only do this 361 // if all of the operands of the instruction are loop invariant and if it 362 // is safe to hoist the instruction. 363 // 364 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) && 365 isSafeToExecuteUnconditionally(I)) 366 hoist(I); 367 } 368 369 const std::vector<DomTreeNode*> &Children = N->getChildren(); 370 for (unsigned i = 0, e = Children.size(); i != e; ++i) 371 HoistRegion(Children[i]); 372} 373 374/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this 375/// instruction. 376/// 377bool LICM::canSinkOrHoistInst(Instruction &I) { 378 // Loads have extra constraints we have to verify before we can hoist them. 379 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 380 if (LI->isVolatile()) 381 return false; // Don't hoist volatile loads! 382 383 // Loads from constant memory are always safe to move, even if they end up 384 // in the same alias set as something that ends up being modified. 385 if (EnableLICMConstantMotion && 386 AA->pointsToConstantMemory(LI->getOperand(0))) 387 return true; 388 389 // Don't hoist loads which have may-aliased stores in loop. 390 unsigned Size = 0; 391 if (LI->getType()->isSized()) 392 Size = AA->getTypeStoreSize(LI->getType()); 393 return !pointerInvalidatedByLoop(LI->getOperand(0), Size); 394 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 395 // Handle obvious cases efficiently. 396 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI); 397 if (Behavior == AliasAnalysis::DoesNotAccessMemory) 398 return true; 399 else if (Behavior == AliasAnalysis::OnlyReadsMemory) { 400 // If this call only reads from memory and there are no writes to memory 401 // in the loop, we can hoist or sink the call as appropriate. 402 bool FoundMod = false; 403 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 404 I != E; ++I) { 405 AliasSet &AS = *I; 406 if (!AS.isForwardingAliasSet() && AS.isMod()) { 407 FoundMod = true; 408 break; 409 } 410 } 411 if (!FoundMod) return true; 412 } 413 414 // FIXME: This should use mod/ref information to see if we can hoist or sink 415 // the call. 416 417 return false; 418 } 419 420 // Otherwise these instructions are hoistable/sinkable 421 return isa<BinaryOperator>(I) || isa<CastInst>(I) || 422 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) || 423 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 424 isa<ShuffleVectorInst>(I); 425} 426 427/// isNotUsedInLoop - Return true if the only users of this instruction are 428/// outside of the loop. If this is true, we can sink the instruction to the 429/// exit blocks of the loop. 430/// 431bool LICM::isNotUsedInLoop(Instruction &I) { 432 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) { 433 Instruction *User = cast<Instruction>(*UI); 434 if (PHINode *PN = dyn_cast<PHINode>(User)) { 435 // PHI node uses occur in predecessor blocks! 436 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 437 if (PN->getIncomingValue(i) == &I) 438 if (CurLoop->contains(PN->getIncomingBlock(i))) 439 return false; 440 } else if (CurLoop->contains(User->getParent())) { 441 return false; 442 } 443 } 444 return true; 445} 446 447 448/// isLoopInvariantInst - Return true if all operands of this instruction are 449/// loop invariant. We also filter out non-hoistable instructions here just for 450/// efficiency. 451/// 452bool LICM::isLoopInvariantInst(Instruction &I) { 453 // The instruction is loop invariant if all of its operands are loop-invariant 454 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 455 if (!CurLoop->isLoopInvariant(I.getOperand(i))) 456 return false; 457 458 // If we got this far, the instruction is loop invariant! 459 return true; 460} 461 462/// sink - When an instruction is found to only be used outside of the loop, 463/// this function moves it to the exit blocks and patches up SSA form as needed. 464/// This method is guaranteed to remove the original instruction from its 465/// position, and may either delete it or move it to outside of the loop. 466/// 467void LICM::sink(Instruction &I) { 468 DEBUG(errs() << "LICM sinking instruction: " << I); 469 470 SmallVector<BasicBlock*, 8> ExitBlocks; 471 CurLoop->getExitBlocks(ExitBlocks); 472 473 if (isa<LoadInst>(I)) ++NumMovedLoads; 474 else if (isa<CallInst>(I)) ++NumMovedCalls; 475 ++NumSunk; 476 Changed = true; 477 478 LLVMContext &Context = I.getContext(); 479 480 // The case where there is only a single exit node of this loop is common 481 // enough that we handle it as a special (more efficient) case. It is more 482 // efficient to handle because there are no PHI nodes that need to be placed. 483 if (ExitBlocks.size() == 1) { 484 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) { 485 // Instruction is not used, just delete it. 486 CurAST->deleteValue(&I); 487 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate. 488 I.replaceAllUsesWith(UndefValue::get(I.getType())); 489 I.eraseFromParent(); 490 } else { 491 // Move the instruction to the start of the exit block, after any PHI 492 // nodes in it. 493 I.removeFromParent(); 494 495 BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI(); 496 ExitBlocks[0]->getInstList().insert(InsertPt, &I); 497 } 498 } else if (ExitBlocks.empty()) { 499 // The instruction is actually dead if there ARE NO exit blocks. 500 CurAST->deleteValue(&I); 501 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate. 502 I.replaceAllUsesWith(UndefValue::get(I.getType())); 503 I.eraseFromParent(); 504 } else { 505 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to 506 // do all of the hard work of inserting PHI nodes as necessary. We convert 507 // the value into a stack object to get it to do this. 508 509 // Firstly, we create a stack object to hold the value... 510 AllocaInst *AI = 0; 511 512 if (I.getType() != Type::getVoidTy(I.getContext())) { 513 AI = new AllocaInst(I.getType(), 0, I.getName(), 514 I.getParent()->getParent()->getEntryBlock().begin()); 515 CurAST->add(AI); 516 } 517 518 // Secondly, insert load instructions for each use of the instruction 519 // outside of the loop. 520 while (!I.use_empty()) { 521 Instruction *U = cast<Instruction>(I.use_back()); 522 523 // If the user is a PHI Node, we actually have to insert load instructions 524 // in all predecessor blocks, not in the PHI block itself! 525 if (PHINode *UPN = dyn_cast<PHINode>(U)) { 526 // Only insert into each predecessor once, so that we don't have 527 // different incoming values from the same block! 528 std::map<BasicBlock*, Value*> InsertedBlocks; 529 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i) 530 if (UPN->getIncomingValue(i) == &I) { 531 BasicBlock *Pred = UPN->getIncomingBlock(i); 532 Value *&PredVal = InsertedBlocks[Pred]; 533 if (!PredVal) { 534 // Insert a new load instruction right before the terminator in 535 // the predecessor block. 536 PredVal = new LoadInst(AI, "", Pred->getTerminator()); 537 CurAST->add(cast<LoadInst>(PredVal)); 538 } 539 540 UPN->setIncomingValue(i, PredVal); 541 } 542 543 } else { 544 LoadInst *L = new LoadInst(AI, "", U); 545 U->replaceUsesOfWith(&I, L); 546 CurAST->add(L); 547 } 548 } 549 550 // Thirdly, insert a copy of the instruction in each exit block of the loop 551 // that is dominated by the instruction, storing the result into the memory 552 // location. Be careful not to insert the instruction into any particular 553 // basic block more than once. 554 std::set<BasicBlock*> InsertedBlocks; 555 BasicBlock *InstOrigBB = I.getParent(); 556 557 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 558 BasicBlock *ExitBlock = ExitBlocks[i]; 559 560 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) { 561 // If we haven't already processed this exit block, do so now. 562 if (InsertedBlocks.insert(ExitBlock).second) { 563 // Insert the code after the last PHI node... 564 BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI(); 565 566 // If this is the first exit block processed, just move the original 567 // instruction, otherwise clone the original instruction and insert 568 // the copy. 569 Instruction *New; 570 if (InsertedBlocks.size() == 1) { 571 I.removeFromParent(); 572 ExitBlock->getInstList().insert(InsertPt, &I); 573 New = &I; 574 } else { 575 New = I.clone(Context); 576 CurAST->copyValue(&I, New); 577 if (!I.getName().empty()) 578 New->setName(I.getName()+".le"); 579 ExitBlock->getInstList().insert(InsertPt, New); 580 } 581 582 // Now that we have inserted the instruction, store it into the alloca 583 if (AI) new StoreInst(New, AI, InsertPt); 584 } 585 } 586 } 587 588 // If the instruction doesn't dominate any exit blocks, it must be dead. 589 if (InsertedBlocks.empty()) { 590 CurAST->deleteValue(&I); 591 I.eraseFromParent(); 592 } 593 594 // Finally, promote the fine value to SSA form. 595 if (AI) { 596 std::vector<AllocaInst*> Allocas; 597 Allocas.push_back(AI); 598 PromoteMemToReg(Allocas, *DT, *DF, Context, CurAST); 599 } 600 } 601} 602 603/// hoist - When an instruction is found to only use loop invariant operands 604/// that is safe to hoist, this instruction is called to do the dirty work. 605/// 606void LICM::hoist(Instruction &I) { 607 DEBUG(errs() << "LICM hoisting to " << Preheader->getName() << ": " << I); 608 609 // Remove the instruction from its current basic block... but don't delete the 610 // instruction. 611 I.removeFromParent(); 612 613 // Insert the new node in Preheader, before the terminator. 614 Preheader->getInstList().insert(Preheader->getTerminator(), &I); 615 616 if (isa<LoadInst>(I)) ++NumMovedLoads; 617 else if (isa<CallInst>(I)) ++NumMovedCalls; 618 ++NumHoisted; 619 Changed = true; 620} 621 622/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is 623/// not a trapping instruction or if it is a trapping instruction and is 624/// guaranteed to execute. 625/// 626bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) { 627 // If it is not a trapping instruction, it is always safe to hoist. 628 if (Inst.isSafeToSpeculativelyExecute()) 629 return true; 630 631 // Otherwise we have to check to make sure that the instruction dominates all 632 // of the exit blocks. If it doesn't, then there is a path out of the loop 633 // which does not execute this instruction, so we can't hoist it. 634 635 // If the instruction is in the header block for the loop (which is very 636 // common), it is always guaranteed to dominate the exit blocks. Since this 637 // is a common case, and can save some work, check it now. 638 if (Inst.getParent() == CurLoop->getHeader()) 639 return true; 640 641 // Get the exit blocks for the current loop. 642 SmallVector<BasicBlock*, 8> ExitBlocks; 643 CurLoop->getExitBlocks(ExitBlocks); 644 645 // For each exit block, get the DT node and walk up the DT until the 646 // instruction's basic block is found or we exit the loop. 647 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 648 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent())) 649 return false; 650 651 return true; 652} 653 654 655/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking 656/// stores out of the loop and moving loads to before the loop. We do this by 657/// looping over the stores in the loop, looking for stores to Must pointers 658/// which are loop invariant. We promote these memory locations to use allocas 659/// instead. These allocas can easily be raised to register values by the 660/// PromoteMem2Reg functionality. 661/// 662void LICM::PromoteValuesInLoop() { 663 // PromotedValues - List of values that are promoted out of the loop. Each 664 // value has an alloca instruction for it, and a canonical version of the 665 // pointer. 666 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues; 667 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca 668 669 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap); 670 if (ValueToAllocaMap.empty()) return; // If there are values to promote. 671 672 Changed = true; 673 NumPromoted += PromotedValues.size(); 674 675 std::vector<Value*> PointerValueNumbers; 676 677 // Emit a copy from the value into the alloca'd value in the loop preheader 678 TerminatorInst *LoopPredInst = Preheader->getTerminator(); 679 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) { 680 Value *Ptr = PromotedValues[i].second; 681 682 // If we are promoting a pointer value, update alias information for the 683 // inserted load. 684 Value *LoadValue = 0; 685 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) { 686 // Locate a load or store through the pointer, and assign the same value 687 // to LI as we are loading or storing. Since we know that the value is 688 // stored in this loop, this will always succeed. 689 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end(); 690 UI != E; ++UI) 691 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 692 LoadValue = LI; 693 break; 694 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 695 if (SI->getOperand(1) == Ptr) { 696 LoadValue = SI->getOperand(0); 697 break; 698 } 699 } 700 assert(LoadValue && "No store through the pointer found!"); 701 PointerValueNumbers.push_back(LoadValue); // Remember this for later. 702 } 703 704 // Load from the memory we are promoting. 705 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst); 706 707 if (LoadValue) CurAST->copyValue(LoadValue, LI); 708 709 // Store into the temporary alloca. 710 new StoreInst(LI, PromotedValues[i].first, LoopPredInst); 711 } 712 713 // Scan the basic blocks in the loop, replacing uses of our pointers with 714 // uses of the allocas in question. 715 // 716 for (Loop::block_iterator I = CurLoop->block_begin(), 717 E = CurLoop->block_end(); I != E; ++I) { 718 BasicBlock *BB = *I; 719 // Rewrite all loads and stores in the block of the pointer... 720 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) { 721 if (LoadInst *L = dyn_cast<LoadInst>(II)) { 722 std::map<Value*, AllocaInst*>::iterator 723 I = ValueToAllocaMap.find(L->getOperand(0)); 724 if (I != ValueToAllocaMap.end()) 725 L->setOperand(0, I->second); // Rewrite load instruction... 726 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) { 727 std::map<Value*, AllocaInst*>::iterator 728 I = ValueToAllocaMap.find(S->getOperand(1)); 729 if (I != ValueToAllocaMap.end()) 730 S->setOperand(1, I->second); // Rewrite store instruction... 731 } 732 } 733 } 734 735 // Now that the body of the loop uses the allocas instead of the original 736 // memory locations, insert code to copy the alloca value back into the 737 // original memory location on all exits from the loop. Note that we only 738 // want to insert one copy of the code in each exit block, though the loop may 739 // exit to the same block more than once. 740 // 741 SmallPtrSet<BasicBlock*, 16> ProcessedBlocks; 742 743 SmallVector<BasicBlock*, 8> ExitBlocks; 744 CurLoop->getExitBlocks(ExitBlocks); 745 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 746 if (!ProcessedBlocks.insert(ExitBlocks[i])) 747 continue; 748 749 // Copy all of the allocas into their memory locations. 750 BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI(); 751 Instruction *InsertPos = BI; 752 unsigned PVN = 0; 753 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) { 754 // Load from the alloca. 755 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos); 756 757 // If this is a pointer type, update alias info appropriately. 758 if (isa<PointerType>(LI->getType())) 759 CurAST->copyValue(PointerValueNumbers[PVN++], LI); 760 761 // Store into the memory we promoted. 762 new StoreInst(LI, PromotedValues[i].second, InsertPos); 763 } 764 } 765 766 // Now that we have done the deed, use the mem2reg functionality to promote 767 // all of the new allocas we just created into real SSA registers. 768 // 769 std::vector<AllocaInst*> PromotedAllocas; 770 PromotedAllocas.reserve(PromotedValues.size()); 771 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) 772 PromotedAllocas.push_back(PromotedValues[i].first); 773 PromoteMemToReg(PromotedAllocas, *DT, *DF, Preheader->getContext(), CurAST); 774} 775 776/// FindPromotableValuesInLoop - Check the current loop for stores to definite 777/// pointers, which are not loaded and stored through may aliases and are safe 778/// for promotion. If these are found, create an alloca for the value, add it 779/// to the PromotedValues list, and keep track of the mapping from value to 780/// alloca. 781void LICM::FindPromotableValuesInLoop( 782 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues, 783 std::map<Value*, AllocaInst*> &ValueToAllocaMap) { 784 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin(); 785 786 // Loop over all of the alias sets in the tracker object. 787 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 788 I != E; ++I) { 789 AliasSet &AS = *I; 790 // We can promote this alias set if it has a store, if it is a "Must" alias 791 // set, if the pointer is loop invariant, and if we are not eliminating any 792 // volatile loads or stores. 793 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 794 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 795 continue; 796 797 assert(!AS.empty() && 798 "Must alias set should have at least one pointer element in it!"); 799 Value *V = AS.begin()->getValue(); 800 801 // Check that all of the pointers in the alias set have the same type. We 802 // cannot (yet) promote a memory location that is loaded and stored in 803 // different sizes. 804 { 805 bool PointerOk = true; 806 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I) 807 if (V->getType() != I->getValue()->getType()) { 808 PointerOk = false; 809 break; 810 } 811 if (!PointerOk) 812 continue; 813 } 814 815 // It isn't safe to promote a load/store from the loop if the load/store is 816 // conditional. For example, turning: 817 // 818 // for () { if (c) *P += 1; } 819 // 820 // into: 821 // 822 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 823 // 824 // is not safe, because *P may only be valid to access if 'c' is true. 825 // 826 // It is safe to promote P if all uses are direct load/stores and if at 827 // least one is guaranteed to be executed. 828 bool GuaranteedToExecute = false; 829 bool InvalidInst = false; 830 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); 831 UI != UE; ++UI) { 832 // Ignore instructions not in this loop. 833 Instruction *Use = dyn_cast<Instruction>(*UI); 834 if (!Use || !CurLoop->contains(Use->getParent())) 835 continue; 836 837 if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) { 838 InvalidInst = true; 839 break; 840 } 841 842 if (!GuaranteedToExecute) 843 GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use); 844 } 845 846 // If there is an non-load/store instruction in the loop, we can't promote 847 // it. If there isn't a guaranteed-to-execute instruction, we can't 848 // promote. 849 if (InvalidInst || !GuaranteedToExecute) 850 continue; 851 852 const Type *Ty = cast<PointerType>(V->getType())->getElementType(); 853 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart); 854 PromotedValues.push_back(std::make_pair(AI, V)); 855 856 // Update the AST and alias analysis. 857 CurAST->copyValue(V, AI); 858 859 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I) 860 ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI)); 861 862 DEBUG(errs() << "LICM: Promoting value: " << *V << "\n"); 863 } 864} 865 866/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 867void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) { 868 AliasSetTracker *AST = LoopToAliasMap[L]; 869 if (!AST) 870 return; 871 872 AST->copyValue(From, To); 873} 874 875/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 876/// set. 877void LICM::deleteAnalysisValue(Value *V, Loop *L) { 878 AliasSetTracker *AST = LoopToAliasMap[L]; 879 if (!AST) 880 return; 881 882 AST->deleteValue(V); 883} 884