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