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 SSAUpdater to construct the appropriate SSA form for the value. 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "llvm/Transforms/Scalar.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AliasSetTracker.h" 37 #include "llvm/Analysis/BasicAliasAnalysis.h" 38 #include "llvm/Analysis/ConstantFolding.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/LoopPass.h" 42 #include "llvm/Analysis/ScalarEvolution.h" 43 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 44 #include "llvm/Analysis/TargetLibraryInfo.h" 45 #include "llvm/Analysis/ValueTracking.h" 46 #include "llvm/IR/CFG.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Dominators.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/PredIteratorCache.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include "llvm/Transforms/Utils/LoopUtils.h" 61 #include "llvm/Transforms/Utils/SSAUpdater.h" 62 #include <algorithm> 63 using namespace llvm; 64 65 #define DEBUG_TYPE "licm" 66 67 STATISTIC(NumSunk , "Number of instructions sunk out of loop"); 68 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop"); 69 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 70 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 71 STATISTIC(NumPromoted , "Number of memory locations promoted to registers"); 72 73 static cl::opt<bool> 74 DisablePromotion("disable-licm-promotion", cl::Hidden, 75 cl::desc("Disable memory promotion in LICM pass")); 76 77 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 78 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop); 79 static bool hoist(Instruction &I, BasicBlock *Preheader); 80 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 81 const Loop *CurLoop, AliasSetTracker *CurAST ); 82 static bool isGuaranteedToExecute(const Instruction &Inst, 83 const DominatorTree *DT, 84 const Loop *CurLoop, 85 const LICMSafetyInfo *SafetyInfo); 86 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 87 const DominatorTree *DT, 88 const TargetLibraryInfo *TLI, 89 const Loop *CurLoop, 90 const LICMSafetyInfo *SafetyInfo, 91 const Instruction *CtxI = nullptr); 92 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 93 const AAMDNodes &AAInfo, 94 AliasSetTracker *CurAST); 95 static Instruction *CloneInstructionInExitBlock(const Instruction &I, 96 BasicBlock &ExitBlock, 97 PHINode &PN, 98 const LoopInfo *LI); 99 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, 100 DominatorTree *DT, TargetLibraryInfo *TLI, 101 Loop *CurLoop, AliasSetTracker *CurAST, 102 LICMSafetyInfo *SafetyInfo); 103 104 namespace { 105 struct LICM : public LoopPass { 106 static char ID; // Pass identification, replacement for typeid 107 LICM() : LoopPass(ID) { 108 initializeLICMPass(*PassRegistry::getPassRegistry()); 109 } 110 111 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 112 113 /// This transformation requires natural loop information & requires that 114 /// loop preheaders be inserted into the CFG... 115 /// 116 void getAnalysisUsage(AnalysisUsage &AU) const override { 117 AU.setPreservesCFG(); 118 AU.addRequired<DominatorTreeWrapperPass>(); 119 AU.addRequired<LoopInfoWrapperPass>(); 120 AU.addRequiredID(LoopSimplifyID); 121 AU.addPreservedID(LoopSimplifyID); 122 AU.addRequiredID(LCSSAID); 123 AU.addPreservedID(LCSSAID); 124 AU.addRequired<AAResultsWrapperPass>(); 125 AU.addPreserved<AAResultsWrapperPass>(); 126 AU.addPreserved<BasicAAWrapperPass>(); 127 AU.addPreserved<GlobalsAAWrapperPass>(); 128 AU.addPreserved<ScalarEvolutionWrapperPass>(); 129 AU.addPreserved<SCEVAAWrapperPass>(); 130 AU.addRequired<TargetLibraryInfoWrapperPass>(); 131 } 132 133 using llvm::Pass::doFinalization; 134 135 bool doFinalization() override { 136 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets"); 137 return false; 138 } 139 140 private: 141 AliasAnalysis *AA; // Current AliasAnalysis information 142 LoopInfo *LI; // Current LoopInfo 143 DominatorTree *DT; // Dominator Tree for the current Loop. 144 145 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding. 146 147 // State that is updated as we process loops. 148 bool Changed; // Set to true when we change anything. 149 BasicBlock *Preheader; // The preheader block of the current loop... 150 Loop *CurLoop; // The current loop we are working on... 151 AliasSetTracker *CurAST; // AliasSet information for the current loop... 152 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap; 153 154 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 155 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 156 Loop *L) override; 157 158 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 159 /// set. 160 void deleteAnalysisValue(Value *V, Loop *L) override; 161 162 /// Simple Analysis hook. Delete loop L from alias set map. 163 void deleteAnalysisLoop(Loop *L) override; 164 }; 165 } 166 167 char LICM::ID = 0; 168 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false) 169 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 170 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 171 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 172 INITIALIZE_PASS_DEPENDENCY(LCSSA) 173 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 174 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 175 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 176 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 177 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 178 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 179 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false) 180 181 Pass *llvm::createLICMPass() { return new LICM(); } 182 183 /// Hoist expressions out of the specified loop. Note, alias info for inner 184 /// loop is not preserved so it is not a good idea to run LICM multiple 185 /// times on one loop. 186 /// 187 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) { 188 if (skipOptnoneFunction(L)) 189 return false; 190 191 Changed = false; 192 193 // Get our Loop and Alias Analysis information... 194 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 195 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 196 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 197 198 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 199 200 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 201 202 CurAST = new AliasSetTracker(*AA); 203 // Collect Alias info from subloops. 204 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end(); 205 LoopItr != LoopItrE; ++LoopItr) { 206 Loop *InnerL = *LoopItr; 207 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL]; 208 assert(InnerAST && "Where is my AST?"); 209 210 // What if InnerLoop was modified by other passes ? 211 CurAST->add(*InnerAST); 212 213 // Once we've incorporated the inner loop's AST into ours, we don't need the 214 // subloop's anymore. 215 delete InnerAST; 216 LoopToAliasSetMap.erase(InnerL); 217 } 218 219 CurLoop = L; 220 221 // Get the preheader block to move instructions into... 222 Preheader = L->getLoopPreheader(); 223 224 // Loop over the body of this loop, looking for calls, invokes, and stores. 225 // Because subloops have already been incorporated into AST, we skip blocks in 226 // subloops. 227 // 228 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 229 I != E; ++I) { 230 BasicBlock *BB = *I; 231 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops. 232 CurAST->add(*BB); // Incorporate the specified basic block 233 } 234 235 // Compute loop safety information. 236 LICMSafetyInfo SafetyInfo; 237 computeLICMSafetyInfo(&SafetyInfo, CurLoop); 238 239 // We want to visit all of the instructions in this loop... that are not parts 240 // of our subloops (they have already had their invariants hoisted out of 241 // their loop, into this loop, so there is no need to process the BODIES of 242 // the subloops). 243 // 244 // Traverse the body of the loop in depth first order on the dominator tree so 245 // that we are guaranteed to see definitions before we see uses. This allows 246 // us to sink instructions in one pass, without iteration. After sinking 247 // instructions, we perform another pass to hoist them out of the loop. 248 // 249 if (L->hasDedicatedExits()) 250 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop, 251 CurAST, &SafetyInfo); 252 if (Preheader) 253 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, 254 CurLoop, CurAST, &SafetyInfo); 255 256 // Now that all loop invariants have been removed from the loop, promote any 257 // memory references to scalars that we can. 258 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) { 259 SmallVector<BasicBlock *, 8> ExitBlocks; 260 SmallVector<Instruction *, 8> InsertPts; 261 PredIteratorCache PIC; 262 263 // Loop over all of the alias sets in the tracker object. 264 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 265 I != E; ++I) 266 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts, 267 PIC, LI, DT, CurLoop, 268 CurAST, &SafetyInfo); 269 270 // Once we have promoted values across the loop body we have to recursively 271 // reform LCSSA as any nested loop may now have values defined within the 272 // loop used in the outer loop. 273 // FIXME: This is really heavy handed. It would be a bit better to use an 274 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 275 // it as it went. 276 if (Changed) { 277 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 278 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr); 279 } 280 } 281 282 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 283 // specifically moving instructions across the loop boundary and so it is 284 // especially in need of sanity checking here. 285 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 286 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 287 "Parent loop not left in LCSSA form after LICM!"); 288 289 // Clear out loops state information for the next iteration 290 CurLoop = nullptr; 291 Preheader = nullptr; 292 293 // If this loop is nested inside of another one, save the alias information 294 // for when we process the outer loop. 295 if (L->getParentLoop()) 296 LoopToAliasSetMap[L] = CurAST; 297 else 298 delete CurAST; 299 return Changed; 300 } 301 302 /// Walk the specified region of the CFG (defined by all blocks dominated by 303 /// the specified block, and that are in the current loop) in reverse depth 304 /// first order w.r.t the DominatorTree. This allows us to visit uses before 305 /// definitions, allowing us to sink a loop body in one pass without iteration. 306 /// 307 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 308 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 309 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 310 311 // Verify inputs. 312 assert(N != nullptr && AA != nullptr && LI != nullptr && 313 DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 314 SafetyInfo != nullptr && "Unexpected input to sinkRegion"); 315 316 // Set changed as false. 317 bool Changed = false; 318 // Get basic block 319 BasicBlock *BB = N->getBlock(); 320 // If this subregion is not in the top level loop at all, exit. 321 if (!CurLoop->contains(BB)) return Changed; 322 323 // We are processing blocks in reverse dfo, so process children first. 324 const std::vector<DomTreeNode*> &Children = N->getChildren(); 325 for (unsigned i = 0, e = Children.size(); i != e; ++i) 326 Changed |= 327 sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 328 // Only need to process the contents of this block if it is not part of a 329 // subloop (which would already have been processed). 330 if (inSubLoop(BB,CurLoop,LI)) return Changed; 331 332 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) { 333 Instruction &I = *--II; 334 335 // If the instruction is dead, we would try to sink it because it isn't used 336 // in the loop, instead, just delete it. 337 if (isInstructionTriviallyDead(&I, TLI)) { 338 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 339 ++II; 340 CurAST->deleteValue(&I); 341 I.eraseFromParent(); 342 Changed = true; 343 continue; 344 } 345 346 // Check to see if we can sink this instruction to the exit blocks 347 // of the loop. We can do this if the all users of the instruction are 348 // outside of the loop. In this case, it doesn't even matter if the 349 // operands of the instruction are loop invariant. 350 // 351 if (isNotUsedInLoop(I, CurLoop) && 352 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) { 353 ++II; 354 Changed |= sink(I, LI, DT, CurLoop, CurAST); 355 } 356 } 357 return Changed; 358 } 359 360 /// Walk the specified region of the CFG (defined by all blocks dominated by 361 /// the specified block, and that are in the current loop) in depth first 362 /// order w.r.t the DominatorTree. This allows us to visit definitions before 363 /// uses, allowing us to hoist a loop body in one pass without iteration. 364 /// 365 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 366 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 367 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 368 // Verify inputs. 369 assert(N != nullptr && AA != nullptr && LI != nullptr && 370 DT != nullptr && CurLoop != nullptr && CurAST != nullptr && 371 SafetyInfo != nullptr && "Unexpected input to hoistRegion"); 372 // Set changed as false. 373 bool Changed = false; 374 // Get basic block 375 BasicBlock *BB = N->getBlock(); 376 // If this subregion is not in the top level loop at all, exit. 377 if (!CurLoop->contains(BB)) return Changed; 378 // Only need to process the contents of this block if it is not part of a 379 // subloop (which would already have been processed). 380 if (!inSubLoop(BB, CurLoop, LI)) 381 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) { 382 Instruction &I = *II++; 383 // Try constant folding this instruction. If all the operands are 384 // constants, it is technically hoistable, but it would be better to just 385 // fold it. 386 if (Constant *C = ConstantFoldInstruction( 387 &I, I.getModule()->getDataLayout(), TLI)) { 388 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'); 389 CurAST->copyValue(&I, C); 390 CurAST->deleteValue(&I); 391 I.replaceAllUsesWith(C); 392 I.eraseFromParent(); 393 continue; 394 } 395 396 // Try hoisting the instruction out to the preheader. We can only do this 397 // if all of the operands of the instruction are loop invariant and if it 398 // is safe to hoist the instruction. 399 // 400 if (CurLoop->hasLoopInvariantOperands(&I) && 401 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) && 402 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, 403 CurLoop->getLoopPreheader()->getTerminator())) 404 Changed |= hoist(I, CurLoop->getLoopPreheader()); 405 } 406 407 const std::vector<DomTreeNode*> &Children = N->getChildren(); 408 for (unsigned i = 0, e = Children.size(); i != e; ++i) 409 Changed |= 410 hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 411 return Changed; 412 } 413 414 /// Computes loop safety information, checks loop body & header 415 /// for the possibility of may throw exception. 416 /// 417 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) { 418 assert(CurLoop != nullptr && "CurLoop cant be null"); 419 BasicBlock *Header = CurLoop->getHeader(); 420 // Setting default safety values. 421 SafetyInfo->MayThrow = false; 422 SafetyInfo->HeaderMayThrow = false; 423 // Iterate over header and compute safety info. 424 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 425 (I != E) && !SafetyInfo->HeaderMayThrow; ++I) 426 SafetyInfo->HeaderMayThrow |= I->mayThrow(); 427 428 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow; 429 // Iterate over loop instructions and compute safety info. 430 for (Loop::block_iterator BB = CurLoop->block_begin(), 431 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB) 432 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); 433 (I != E) && !SafetyInfo->MayThrow; ++I) 434 SafetyInfo->MayThrow |= I->mayThrow(); 435 } 436 437 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this 438 /// instruction. 439 /// 440 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT, 441 TargetLibraryInfo *TLI, Loop *CurLoop, 442 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) { 443 // Loads have extra constraints we have to verify before we can hoist them. 444 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 445 if (!LI->isUnordered()) 446 return false; // Don't hoist volatile/atomic loads! 447 448 // Loads from constant memory are always safe to move, even if they end up 449 // in the same alias set as something that ends up being modified. 450 if (AA->pointsToConstantMemory(LI->getOperand(0))) 451 return true; 452 if (LI->getMetadata(LLVMContext::MD_invariant_load)) 453 return true; 454 455 // Don't hoist loads which have may-aliased stores in loop. 456 uint64_t Size = 0; 457 if (LI->getType()->isSized()) 458 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType()); 459 460 AAMDNodes AAInfo; 461 LI->getAAMetadata(AAInfo); 462 463 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST); 464 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 465 // Don't sink or hoist dbg info; it's legal, but not useful. 466 if (isa<DbgInfoIntrinsic>(I)) 467 return false; 468 469 // Handle simple cases by querying alias analysis. 470 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 471 if (Behavior == FMRB_DoesNotAccessMemory) 472 return true; 473 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 474 // A readonly argmemonly function only reads from memory pointed to by 475 // it's arguments with arbitrary offsets. If we can prove there are no 476 // writes to this memory in the loop, we can hoist or sink. 477 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 478 for (Value *Op : CI->arg_operands()) 479 if (Op->getType()->isPointerTy() && 480 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize, 481 AAMDNodes(), CurAST)) 482 return false; 483 return true; 484 } 485 // If this call only reads from memory and there are no writes to memory 486 // in the loop, we can hoist or sink the call as appropriate. 487 bool FoundMod = false; 488 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end(); 489 I != E; ++I) { 490 AliasSet &AS = *I; 491 if (!AS.isForwardingAliasSet() && AS.isMod()) { 492 FoundMod = true; 493 break; 494 } 495 } 496 if (!FoundMod) return true; 497 } 498 499 // FIXME: This should use mod/ref information to see if we can hoist or 500 // sink the call. 501 502 return false; 503 } 504 505 // Only these instructions are hoistable/sinkable. 506 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 507 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 508 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 509 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 510 !isa<InsertValueInst>(I)) 511 return false; 512 513 // TODO: Plumb the context instruction through to make hoisting and sinking 514 // more powerful. Hoisting of loads already works due to the special casing 515 // above. 516 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, 517 nullptr); 518 } 519 520 /// Returns true if a PHINode is a trivially replaceable with an 521 /// Instruction. 522 /// This is true when all incoming values are that instruction. 523 /// This pattern occurs most often with LCSSA PHI nodes. 524 /// 525 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) { 526 for (const Value *IncValue : PN.incoming_values()) 527 if (IncValue != &I) 528 return false; 529 530 return true; 531 } 532 533 /// Return true if the only users of this instruction are outside of 534 /// the loop. If this is true, we can sink the instruction to the exit 535 /// blocks of the loop. 536 /// 537 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) { 538 for (const User *U : I.users()) { 539 const Instruction *UI = cast<Instruction>(U); 540 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 541 // A PHI node where all of the incoming values are this instruction are 542 // special -- they can just be RAUW'ed with the instruction and thus 543 // don't require a use in the predecessor. This is a particular important 544 // special case because it is the pattern found in LCSSA form. 545 if (isTriviallyReplacablePHI(*PN, I)) { 546 if (CurLoop->contains(PN)) 547 return false; 548 else 549 continue; 550 } 551 552 // Otherwise, PHI node uses occur in predecessor blocks if the incoming 553 // values. Check for such a use being inside the loop. 554 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 555 if (PN->getIncomingValue(i) == &I) 556 if (CurLoop->contains(PN->getIncomingBlock(i))) 557 return false; 558 559 continue; 560 } 561 562 if (CurLoop->contains(UI)) 563 return false; 564 } 565 return true; 566 } 567 568 static Instruction *CloneInstructionInExitBlock(const Instruction &I, 569 BasicBlock &ExitBlock, 570 PHINode &PN, 571 const LoopInfo *LI) { 572 Instruction *New = I.clone(); 573 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 574 if (!I.getName().empty()) New->setName(I.getName() + ".le"); 575 576 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 577 // particularly cheap because we can rip off the PHI node that we're 578 // replacing for the number and blocks of the predecessors. 579 // OPT: If this shows up in a profile, we can instead finish sinking all 580 // invariant instructions, and then walk their operands to re-establish 581 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 582 // sinking bottom-up. 583 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 584 ++OI) 585 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 586 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 587 if (!OLoop->contains(&PN)) { 588 PHINode *OpPN = 589 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 590 OInst->getName() + ".lcssa", &ExitBlock.front()); 591 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 592 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 593 *OI = OpPN; 594 } 595 return New; 596 } 597 598 /// When an instruction is found to only be used outside of the loop, this 599 /// function moves it to the exit blocks and patches up SSA form as needed. 600 /// This method is guaranteed to remove the original instruction from its 601 /// position, and may either delete it or move it to outside of the loop. 602 /// 603 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 604 const Loop *CurLoop, AliasSetTracker *CurAST ) { 605 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 606 bool Changed = false; 607 if (isa<LoadInst>(I)) ++NumMovedLoads; 608 else if (isa<CallInst>(I)) ++NumMovedCalls; 609 ++NumSunk; 610 Changed = true; 611 612 #ifndef NDEBUG 613 SmallVector<BasicBlock *, 32> ExitBlocks; 614 CurLoop->getUniqueExitBlocks(ExitBlocks); 615 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 616 ExitBlocks.end()); 617 #endif 618 619 // Clones of this instruction. Don't create more than one per exit block! 620 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 621 622 // If this instruction is only used outside of the loop, then all users are 623 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 624 // the instruction. 625 while (!I.use_empty()) { 626 Value::user_iterator UI = I.user_begin(); 627 auto *User = cast<Instruction>(*UI); 628 if (!DT->isReachableFromEntry(User->getParent())) { 629 User->replaceUsesOfWith(&I, UndefValue::get(I.getType())); 630 continue; 631 } 632 // The user must be a PHI node. 633 PHINode *PN = cast<PHINode>(User); 634 635 // Surprisingly, instructions can be used outside of loops without any 636 // exits. This can only happen in PHI nodes if the incoming block is 637 // unreachable. 638 Use &U = UI.getUse(); 639 BasicBlock *BB = PN->getIncomingBlock(U); 640 if (!DT->isReachableFromEntry(BB)) { 641 U = UndefValue::get(I.getType()); 642 continue; 643 } 644 645 BasicBlock *ExitBlock = PN->getParent(); 646 assert(ExitBlockSet.count(ExitBlock) && 647 "The LCSSA PHI is not in an exit block!"); 648 649 Instruction *New; 650 auto It = SunkCopies.find(ExitBlock); 651 if (It != SunkCopies.end()) 652 New = It->second; 653 else 654 New = SunkCopies[ExitBlock] = 655 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI); 656 657 PN->replaceAllUsesWith(New); 658 PN->eraseFromParent(); 659 } 660 661 CurAST->deleteValue(&I); 662 I.eraseFromParent(); 663 return Changed; 664 } 665 666 /// When an instruction is found to only use loop invariant operands that 667 /// is safe to hoist, this instruction is called to do the dirty work. 668 /// 669 static bool hoist(Instruction &I, BasicBlock *Preheader) { 670 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " 671 << I << "\n"); 672 // Move the new node to the Preheader, before its terminator. 673 I.moveBefore(Preheader->getTerminator()); 674 675 if (isa<LoadInst>(I)) ++NumMovedLoads; 676 else if (isa<CallInst>(I)) ++NumMovedCalls; 677 ++NumHoisted; 678 return true; 679 } 680 681 /// Only sink or hoist an instruction if it is not a trapping instruction, 682 /// or if the instruction is known not to trap when moved to the preheader. 683 /// or if it is a trapping instruction and is guaranteed to execute. 684 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 685 const DominatorTree *DT, 686 const TargetLibraryInfo *TLI, 687 const Loop *CurLoop, 688 const LICMSafetyInfo *SafetyInfo, 689 const Instruction *CtxI) { 690 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI)) 691 return true; 692 693 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo); 694 } 695 696 static bool isGuaranteedToExecute(const Instruction &Inst, 697 const DominatorTree *DT, 698 const Loop *CurLoop, 699 const LICMSafetyInfo * SafetyInfo) { 700 701 // We have to check to make sure that the instruction dominates all 702 // of the exit blocks. If it doesn't, then there is a path out of the loop 703 // which does not execute this instruction, so we can't hoist it. 704 705 // If the instruction is in the header block for the loop (which is very 706 // common), it is always guaranteed to dominate the exit blocks. Since this 707 // is a common case, and can save some work, check it now. 708 if (Inst.getParent() == CurLoop->getHeader()) 709 // If there's a throw in the header block, we can't guarantee we'll reach 710 // Inst. 711 return !SafetyInfo->HeaderMayThrow; 712 713 // Somewhere in this loop there is an instruction which may throw and make us 714 // exit the loop. 715 if (SafetyInfo->MayThrow) 716 return false; 717 718 // Get the exit blocks for the current loop. 719 SmallVector<BasicBlock*, 8> ExitBlocks; 720 CurLoop->getExitBlocks(ExitBlocks); 721 722 // Verify that the block dominates each of the exit blocks of the loop. 723 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 724 if (!DT->dominates(Inst.getParent(), ExitBlocks[i])) 725 return false; 726 727 // As a degenerate case, if the loop is statically infinite then we haven't 728 // proven anything since there are no exit blocks. 729 if (ExitBlocks.empty()) 730 return false; 731 732 return true; 733 } 734 735 namespace { 736 class LoopPromoter : public LoadAndStorePromoter { 737 Value *SomePtr; // Designated pointer to store to. 738 SmallPtrSetImpl<Value*> &PointerMustAliases; 739 SmallVectorImpl<BasicBlock*> &LoopExitBlocks; 740 SmallVectorImpl<Instruction*> &LoopInsertPts; 741 PredIteratorCache &PredCache; 742 AliasSetTracker &AST; 743 LoopInfo &LI; 744 DebugLoc DL; 745 int Alignment; 746 AAMDNodes AATags; 747 748 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 749 if (Instruction *I = dyn_cast<Instruction>(V)) 750 if (Loop *L = LI.getLoopFor(I->getParent())) 751 if (!L->contains(BB)) { 752 // We need to create an LCSSA PHI node for the incoming value and 753 // store that. 754 PHINode *PN = 755 PHINode::Create(I->getType(), PredCache.size(BB), 756 I->getName() + ".lcssa", &BB->front()); 757 for (BasicBlock *Pred : PredCache.get(BB)) 758 PN->addIncoming(I, Pred); 759 return PN; 760 } 761 return V; 762 } 763 764 public: 765 LoopPromoter(Value *SP, 766 ArrayRef<const Instruction *> Insts, 767 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA, 768 SmallVectorImpl<BasicBlock *> &LEB, 769 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, 770 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, 771 const AAMDNodes &AATags) 772 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 773 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), 774 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {} 775 776 bool isInstInList(Instruction *I, 777 const SmallVectorImpl<Instruction*> &) const override { 778 Value *Ptr; 779 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 780 Ptr = LI->getOperand(0); 781 else 782 Ptr = cast<StoreInst>(I)->getPointerOperand(); 783 return PointerMustAliases.count(Ptr); 784 } 785 786 void doExtraRewritesBeforeFinalDeletion() const override { 787 // Insert stores after in the loop exit blocks. Each exit block gets a 788 // store of the live-out values that feed them. Since we've already told 789 // the SSA updater about the defs in the loop and the preheader 790 // definition, it is all set and we can start using it. 791 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 792 BasicBlock *ExitBlock = LoopExitBlocks[i]; 793 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 794 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 795 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 796 Instruction *InsertPos = LoopInsertPts[i]; 797 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 798 NewSI->setAlignment(Alignment); 799 NewSI->setDebugLoc(DL); 800 if (AATags) NewSI->setAAMetadata(AATags); 801 } 802 } 803 804 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 805 // Update alias analysis. 806 AST.copyValue(LI, V); 807 } 808 void instructionDeleted(Instruction *I) const override { 809 AST.deleteValue(I); 810 } 811 }; 812 } // end anon namespace 813 814 /// Try to promote memory values to scalars by sinking stores out of the 815 /// loop and moving loads to before the loop. We do this by looping over 816 /// the stores in the loop, looking for stores to Must pointers which are 817 /// loop invariant. 818 /// 819 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS, 820 SmallVectorImpl<BasicBlock*>&ExitBlocks, 821 SmallVectorImpl<Instruction*>&InsertPts, 822 PredIteratorCache &PIC, LoopInfo *LI, 823 DominatorTree *DT, Loop *CurLoop, 824 AliasSetTracker *CurAST, 825 LICMSafetyInfo * SafetyInfo) { 826 // Verify inputs. 827 assert(LI != nullptr && DT != nullptr && 828 CurLoop != nullptr && CurAST != nullptr && 829 SafetyInfo != nullptr && 830 "Unexpected Input to promoteLoopAccessesToScalars"); 831 // Initially set Changed status to false. 832 bool Changed = false; 833 // We can promote this alias set if it has a store, if it is a "Must" alias 834 // set, if the pointer is loop invariant, and if we are not eliminating any 835 // volatile loads or stores. 836 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 837 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 838 return Changed; 839 840 assert(!AS.empty() && 841 "Must alias set should have at least one pointer element in it!"); 842 843 Value *SomePtr = AS.begin()->getValue(); 844 BasicBlock * Preheader = CurLoop->getLoopPreheader(); 845 846 // It isn't safe to promote a load/store from the loop if the load/store is 847 // conditional. For example, turning: 848 // 849 // for () { if (c) *P += 1; } 850 // 851 // into: 852 // 853 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 854 // 855 // is not safe, because *P may only be valid to access if 'c' is true. 856 // 857 // It is safe to promote P if all uses are direct load/stores and if at 858 // least one is guaranteed to be executed. 859 bool GuaranteedToExecute = false; 860 861 SmallVector<Instruction*, 64> LoopUses; 862 SmallPtrSet<Value*, 4> PointerMustAliases; 863 864 // We start with an alignment of one and try to find instructions that allow 865 // us to prove better alignment. 866 unsigned Alignment = 1; 867 AAMDNodes AATags; 868 bool HasDedicatedExits = CurLoop->hasDedicatedExits(); 869 870 // Check that all of the pointers in the alias set have the same type. We 871 // cannot (yet) promote a memory location that is loaded and stored in 872 // different sizes. While we are at it, collect alignment and AA info. 873 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) { 874 Value *ASIV = ASI->getValue(); 875 PointerMustAliases.insert(ASIV); 876 877 // Check that all of the pointers in the alias set have the same type. We 878 // cannot (yet) promote a memory location that is loaded and stored in 879 // different sizes. 880 if (SomePtr->getType() != ASIV->getType()) 881 return Changed; 882 883 for (User *U : ASIV->users()) { 884 // Ignore instructions that are outside the loop. 885 Instruction *UI = dyn_cast<Instruction>(U); 886 if (!UI || !CurLoop->contains(UI)) 887 continue; 888 889 // If there is an non-load/store instruction in the loop, we can't promote 890 // it. 891 if (const LoadInst *load = dyn_cast<LoadInst>(UI)) { 892 assert(!load->isVolatile() && "AST broken"); 893 if (!load->isSimple()) 894 return Changed; 895 } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) { 896 // Stores *of* the pointer are not interesting, only stores *to* the 897 // pointer. 898 if (UI->getOperand(1) != ASIV) 899 continue; 900 assert(!store->isVolatile() && "AST broken"); 901 if (!store->isSimple()) 902 return Changed; 903 // Don't sink stores from loops without dedicated block exits. Exits 904 // containing indirect branches are not transformed by loop simplify, 905 // make sure we catch that. An additional load may be generated in the 906 // preheader for SSA updater, so also avoid sinking when no preheader 907 // is available. 908 if (!HasDedicatedExits || !Preheader) 909 return Changed; 910 911 // Note that we only check GuaranteedToExecute inside the store case 912 // so that we do not introduce stores where they did not exist before 913 // (which would break the LLVM concurrency model). 914 915 // If the alignment of this instruction allows us to specify a more 916 // restrictive (and performant) alignment and if we are sure this 917 // instruction will be executed, update the alignment. 918 // Larger is better, with the exception of 0 being the best alignment. 919 unsigned InstAlignment = store->getAlignment(); 920 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0) 921 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) { 922 GuaranteedToExecute = true; 923 Alignment = InstAlignment; 924 } 925 926 if (!GuaranteedToExecute) 927 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT, 928 CurLoop, SafetyInfo); 929 930 } else 931 return Changed; // Not a load or store. 932 933 // Merge the AA tags. 934 if (LoopUses.empty()) { 935 // On the first load/store, just take its AA tags. 936 UI->getAAMetadata(AATags); 937 } else if (AATags) { 938 UI->getAAMetadata(AATags, /* Merge = */ true); 939 } 940 941 LoopUses.push_back(UI); 942 } 943 } 944 945 // If there isn't a guaranteed-to-execute instruction, we can't promote. 946 if (!GuaranteedToExecute) 947 return Changed; 948 949 // Otherwise, this is safe to promote, lets do it! 950 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n'); 951 Changed = true; 952 ++NumPromoted; 953 954 // Grab a debug location for the inserted loads/stores; given that the 955 // inserted loads/stores have little relation to the original loads/stores, 956 // this code just arbitrarily picks a location from one, since any debug 957 // location is better than none. 958 DebugLoc DL = LoopUses[0]->getDebugLoc(); 959 960 // Figure out the loop exits and their insertion points, if this is the 961 // first promotion. 962 if (ExitBlocks.empty()) { 963 CurLoop->getUniqueExitBlocks(ExitBlocks); 964 InsertPts.resize(ExitBlocks.size()); 965 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 966 InsertPts[i] = &*ExitBlocks[i]->getFirstInsertionPt(); 967 } 968 969 // We use the SSAUpdater interface to insert phi nodes as required. 970 SmallVector<PHINode*, 16> NewPHIs; 971 SSAUpdater SSA(&NewPHIs); 972 LoopPromoter Promoter(SomePtr, LoopUses, SSA, 973 PointerMustAliases, ExitBlocks, 974 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags); 975 976 // Set up the preheader to have a definition of the value. It is the live-out 977 // value from the preheader that uses in the loop will use. 978 LoadInst *PreheaderLoad = 979 new LoadInst(SomePtr, SomePtr->getName()+".promoted", 980 Preheader->getTerminator()); 981 PreheaderLoad->setAlignment(Alignment); 982 PreheaderLoad->setDebugLoc(DL); 983 if (AATags) PreheaderLoad->setAAMetadata(AATags); 984 SSA.AddAvailableValue(Preheader, PreheaderLoad); 985 986 // Rewrite all the loads in the loop and remember all the definitions from 987 // stores in the loop. 988 Promoter.run(LoopUses); 989 990 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 991 if (PreheaderLoad->use_empty()) 992 PreheaderLoad->eraseFromParent(); 993 994 return Changed; 995 } 996 997 /// Simple analysis hook. Clone alias set info. 998 /// 999 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) { 1000 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1001 if (!AST) 1002 return; 1003 1004 AST->copyValue(From, To); 1005 } 1006 1007 /// Simple Analysis hook. Delete value V from alias set 1008 /// 1009 void LICM::deleteAnalysisValue(Value *V, Loop *L) { 1010 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1011 if (!AST) 1012 return; 1013 1014 AST->deleteValue(V); 1015 } 1016 1017 /// Simple Analysis hook. Delete value L from alias set map. 1018 /// 1019 void LICM::deleteAnalysisLoop(Loop *L) { 1020 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1021 if (!AST) 1022 return; 1023 1024 delete AST; 1025 LoopToAliasSetMap.erase(L); 1026 } 1027 1028 1029 /// Return true if the body of this loop may store into the memory 1030 /// location pointed to by V. 1031 /// 1032 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 1033 const AAMDNodes &AAInfo, 1034 AliasSetTracker *CurAST) { 1035 // Check to see if any of the basic blocks in CurLoop invalidate *V. 1036 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod(); 1037 } 1038 1039 /// Little predicate that returns true if the specified basic block is in 1040 /// a subloop of the current one, not the current one itself. 1041 /// 1042 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 1043 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 1044 return LI->getLoopFor(BB) != CurLoop; 1045 } 1046 1047