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/LICM.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/CaptureTracking.h" 39 #include "llvm/Analysis/ConstantFolding.h" 40 #include "llvm/Analysis/GlobalsModRef.h" 41 #include "llvm/Analysis/Loads.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/LoopPass.h" 44 #include "llvm/Analysis/MemoryBuiltins.h" 45 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 46 #include "llvm/Analysis/ScalarEvolution.h" 47 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 48 #include "llvm/Analysis/TargetLibraryInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/IR/CFG.h" 51 #include "llvm/IR/Constants.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DerivedTypes.h" 54 #include "llvm/IR/Dominators.h" 55 #include "llvm/IR/Instructions.h" 56 #include "llvm/IR/IntrinsicInst.h" 57 #include "llvm/IR/LLVMContext.h" 58 #include "llvm/IR/Metadata.h" 59 #include "llvm/IR/PredIteratorCache.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Transforms/Scalar.h" 64 #include "llvm/Transforms/Scalar/LoopPassManager.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include "llvm/Transforms/Utils/LoopUtils.h" 67 #include "llvm/Transforms/Utils/SSAUpdater.h" 68 #include <algorithm> 69 #include <utility> 70 using namespace llvm; 71 72 #define DEBUG_TYPE "licm" 73 74 STATISTIC(NumSunk, "Number of instructions sunk out of loop"); 75 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); 76 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 77 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 78 STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); 79 80 static cl::opt<bool> 81 DisablePromotion("disable-licm-promotion", cl::Hidden, 82 cl::desc("Disable memory promotion in LICM pass")); 83 84 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 85 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 86 const LoopSafetyInfo *SafetyInfo); 87 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 88 const LoopSafetyInfo *SafetyInfo, 89 OptimizationRemarkEmitter *ORE); 90 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 91 const Loop *CurLoop, AliasSetTracker *CurAST, 92 const LoopSafetyInfo *SafetyInfo, 93 OptimizationRemarkEmitter *ORE); 94 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 95 const DominatorTree *DT, 96 const Loop *CurLoop, 97 const LoopSafetyInfo *SafetyInfo, 98 OptimizationRemarkEmitter *ORE, 99 const Instruction *CtxI = nullptr); 100 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 101 const AAMDNodes &AAInfo, 102 AliasSetTracker *CurAST); 103 static Instruction * 104 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 105 const LoopInfo *LI, 106 const LoopSafetyInfo *SafetyInfo); 107 108 namespace { 109 struct LoopInvariantCodeMotion { 110 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 111 TargetLibraryInfo *TLI, ScalarEvolution *SE, 112 OptimizationRemarkEmitter *ORE, bool DeleteAST); 113 114 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() { 115 return LoopToAliasSetMap; 116 } 117 118 private: 119 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap; 120 121 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 122 AliasAnalysis *AA); 123 }; 124 125 struct LegacyLICMPass : public LoopPass { 126 static char ID; // Pass identification, replacement for typeid 127 LegacyLICMPass() : LoopPass(ID) { 128 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); 129 } 130 131 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 132 if (skipLoop(L)) { 133 // If we have run LICM on a previous loop but now we are skipping 134 // (because we've hit the opt-bisect limit), we need to clear the 135 // loop alias information. 136 for (auto <AS : LICM.getLoopToAliasSetMap()) 137 delete LTAS.second; 138 LICM.getLoopToAliasSetMap().clear(); 139 return false; 140 } 141 142 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 143 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 144 // pass. Function analyses need to be preserved across loop transformations 145 // but ORE cannot be preserved (see comment before the pass definition). 146 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 147 return LICM.runOnLoop(L, 148 &getAnalysis<AAResultsWrapperPass>().getAAResults(), 149 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), 150 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 151 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 152 SE ? &SE->getSE() : nullptr, &ORE, false); 153 } 154 155 /// This transformation requires natural loop information & requires that 156 /// loop preheaders be inserted into the CFG... 157 /// 158 void getAnalysisUsage(AnalysisUsage &AU) const override { 159 AU.setPreservesCFG(); 160 AU.addRequired<TargetLibraryInfoWrapperPass>(); 161 getLoopAnalysisUsage(AU); 162 } 163 164 using llvm::Pass::doFinalization; 165 166 bool doFinalization() override { 167 assert(LICM.getLoopToAliasSetMap().empty() && 168 "Didn't free loop alias sets"); 169 return false; 170 } 171 172 private: 173 LoopInvariantCodeMotion LICM; 174 175 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 176 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 177 Loop *L) override; 178 179 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 180 /// set. 181 void deleteAnalysisValue(Value *V, Loop *L) override; 182 183 /// Simple Analysis hook. Delete loop L from alias set map. 184 void deleteAnalysisLoop(Loop *L) override; 185 }; 186 } 187 188 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, 189 LoopStandardAnalysisResults &AR, LPMUpdater &) { 190 const auto &FAM = 191 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 192 Function *F = L.getHeader()->getParent(); 193 194 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); 195 // FIXME: This should probably be optional rather than required. 196 if (!ORE) 197 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not " 198 "cached at a higher level"); 199 200 LoopInvariantCodeMotion LICM; 201 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, ORE, true)) 202 return PreservedAnalyses::all(); 203 204 auto PA = getLoopPassPreservedAnalyses(); 205 PA.preserveSet<CFGAnalyses>(); 206 return PA; 207 } 208 209 char LegacyLICMPass::ID = 0; 210 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", 211 false, false) 212 INITIALIZE_PASS_DEPENDENCY(LoopPass) 213 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 214 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, 215 false) 216 217 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } 218 219 /// Hoist expressions out of the specified loop. Note, alias info for inner 220 /// loop is not preserved so it is not a good idea to run LICM multiple 221 /// times on one loop. 222 /// We should delete AST for inner loops in the new pass manager to avoid 223 /// memory leak. 224 /// 225 bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA, 226 LoopInfo *LI, DominatorTree *DT, 227 TargetLibraryInfo *TLI, 228 ScalarEvolution *SE, 229 OptimizationRemarkEmitter *ORE, 230 bool DeleteAST) { 231 bool Changed = false; 232 233 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 234 235 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA); 236 237 // Get the preheader block to move instructions into... 238 BasicBlock *Preheader = L->getLoopPreheader(); 239 240 // Compute loop safety information. 241 LoopSafetyInfo SafetyInfo; 242 computeLoopSafetyInfo(&SafetyInfo, L); 243 244 // We want to visit all of the instructions in this loop... that are not parts 245 // of our subloops (they have already had their invariants hoisted out of 246 // their loop, into this loop, so there is no need to process the BODIES of 247 // the subloops). 248 // 249 // Traverse the body of the loop in depth first order on the dominator tree so 250 // that we are guaranteed to see definitions before we see uses. This allows 251 // us to sink instructions in one pass, without iteration. After sinking 252 // instructions, we perform another pass to hoist them out of the loop. 253 // 254 if (L->hasDedicatedExits()) 255 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, 256 CurAST, &SafetyInfo, ORE); 257 if (Preheader) 258 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, 259 CurAST, &SafetyInfo, ORE); 260 261 // Now that all loop invariants have been removed from the loop, promote any 262 // memory references to scalars that we can. 263 // Don't sink stores from loops without dedicated block exits. Exits 264 // containing indirect branches are not transformed by loop simplify, 265 // make sure we catch that. An additional load may be generated in the 266 // preheader for SSA updater, so also avoid sinking when no preheader 267 // is available. 268 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) { 269 // Figure out the loop exits and their insertion points 270 SmallVector<BasicBlock *, 8> ExitBlocks; 271 L->getUniqueExitBlocks(ExitBlocks); 272 273 // We can't insert into a catchswitch. 274 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { 275 return isa<CatchSwitchInst>(Exit->getTerminator()); 276 }); 277 278 if (!HasCatchSwitch) { 279 SmallVector<Instruction *, 8> InsertPts; 280 InsertPts.reserve(ExitBlocks.size()); 281 for (BasicBlock *ExitBlock : ExitBlocks) 282 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 283 284 PredIteratorCache PIC; 285 286 bool Promoted = false; 287 288 // Loop over all of the alias sets in the tracker object. 289 for (AliasSet &AS : *CurAST) 290 Promoted |= 291 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT, 292 TLI, L, CurAST, &SafetyInfo, ORE); 293 294 // Once we have promoted values across the loop body we have to 295 // recursively reform LCSSA as any nested loop may now have values defined 296 // within the loop used in the outer loop. 297 // FIXME: This is really heavy handed. It would be a bit better to use an 298 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 299 // it as it went. 300 if (Promoted) 301 formLCSSARecursively(*L, *DT, LI, SE); 302 303 Changed |= Promoted; 304 } 305 } 306 307 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 308 // specifically moving instructions across the loop boundary and so it is 309 // especially in need of sanity checking here. 310 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 311 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 312 "Parent loop not left in LCSSA form after LICM!"); 313 314 // If this loop is nested inside of another one, save the alias information 315 // for when we process the outer loop. 316 if (L->getParentLoop() && !DeleteAST) 317 LoopToAliasSetMap[L] = CurAST; 318 else 319 delete CurAST; 320 321 if (Changed && SE) 322 SE->forgetLoopDispositions(L); 323 return Changed; 324 } 325 326 /// Walk the specified region of the CFG (defined by all blocks dominated by 327 /// the specified block, and that are in the current loop) in reverse depth 328 /// first order w.r.t the DominatorTree. This allows us to visit uses before 329 /// definitions, allowing us to sink a loop body in one pass without iteration. 330 /// 331 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 332 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 333 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 334 OptimizationRemarkEmitter *ORE) { 335 336 // Verify inputs. 337 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 338 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 339 "Unexpected input to sinkRegion"); 340 341 BasicBlock *BB = N->getBlock(); 342 // If this subregion is not in the top level loop at all, exit. 343 if (!CurLoop->contains(BB)) 344 return false; 345 346 // We are processing blocks in reverse dfo, so process children first. 347 bool Changed = false; 348 const std::vector<DomTreeNode *> &Children = N->getChildren(); 349 for (DomTreeNode *Child : Children) 350 Changed |= 351 sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE); 352 353 // Only need to process the contents of this block if it is not part of a 354 // subloop (which would already have been processed). 355 if (inSubLoop(BB, CurLoop, LI)) 356 return Changed; 357 358 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { 359 Instruction &I = *--II; 360 361 // If the instruction is dead, we would try to sink it because it isn't used 362 // in the loop, instead, just delete it. 363 if (isInstructionTriviallyDead(&I, TLI)) { 364 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 365 ++II; 366 CurAST->deleteValue(&I); 367 I.eraseFromParent(); 368 Changed = true; 369 continue; 370 } 371 372 // Check to see if we can sink this instruction to the exit blocks 373 // of the loop. We can do this if the all users of the instruction are 374 // outside of the loop. In this case, it doesn't even matter if the 375 // operands of the instruction are loop invariant. 376 // 377 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) && 378 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) { 379 ++II; 380 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo, ORE); 381 } 382 } 383 return Changed; 384 } 385 386 /// Walk the specified region of the CFG (defined by all blocks dominated by 387 /// the specified block, and that are in the current loop) in depth first 388 /// order w.r.t the DominatorTree. This allows us to visit definitions before 389 /// uses, allowing us to hoist a loop body in one pass without iteration. 390 /// 391 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 392 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 393 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 394 OptimizationRemarkEmitter *ORE) { 395 // Verify inputs. 396 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 397 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 398 "Unexpected input to hoistRegion"); 399 400 BasicBlock *BB = N->getBlock(); 401 402 // If this subregion is not in the top level loop at all, exit. 403 if (!CurLoop->contains(BB)) 404 return false; 405 406 // Only need to process the contents of this block if it is not part of a 407 // subloop (which would already have been processed). 408 bool Changed = false; 409 if (!inSubLoop(BB, CurLoop, LI)) 410 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { 411 Instruction &I = *II++; 412 // Try constant folding this instruction. If all the operands are 413 // constants, it is technically hoistable, but it would be better to just 414 // fold it. 415 if (Constant *C = ConstantFoldInstruction( 416 &I, I.getModule()->getDataLayout(), TLI)) { 417 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'); 418 CurAST->copyValue(&I, C); 419 I.replaceAllUsesWith(C); 420 if (isInstructionTriviallyDead(&I, TLI)) { 421 CurAST->deleteValue(&I); 422 I.eraseFromParent(); 423 } 424 Changed = true; 425 continue; 426 } 427 428 // Try hoisting the instruction out to the preheader. We can only do this 429 // if all of the operands of the instruction are loop invariant and if it 430 // is safe to hoist the instruction. 431 // 432 if (CurLoop->hasLoopInvariantOperands(&I) && 433 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) && 434 isSafeToExecuteUnconditionally( 435 I, DT, CurLoop, SafetyInfo, ORE, 436 CurLoop->getLoopPreheader()->getTerminator())) 437 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE); 438 } 439 440 const std::vector<DomTreeNode *> &Children = N->getChildren(); 441 for (DomTreeNode *Child : Children) 442 Changed |= 443 hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo, ORE); 444 return Changed; 445 } 446 447 /// Computes loop safety information, checks loop body & header 448 /// for the possibility of may throw exception. 449 /// 450 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) { 451 assert(CurLoop != nullptr && "CurLoop cant be null"); 452 BasicBlock *Header = CurLoop->getHeader(); 453 // Setting default safety values. 454 SafetyInfo->MayThrow = false; 455 SafetyInfo->HeaderMayThrow = false; 456 // Iterate over header and compute safety info. 457 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 458 (I != E) && !SafetyInfo->HeaderMayThrow; ++I) 459 SafetyInfo->HeaderMayThrow |= 460 !isGuaranteedToTransferExecutionToSuccessor(&*I); 461 462 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow; 463 // Iterate over loop instructions and compute safety info. 464 // Skip header as it has been computed and stored in HeaderMayThrow. 465 // The first block in loopinfo.Blocks is guaranteed to be the header. 466 assert(Header == *CurLoop->getBlocks().begin() && "First block must be header"); 467 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()), 468 BBE = CurLoop->block_end(); 469 (BB != BBE) && !SafetyInfo->MayThrow; ++BB) 470 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); 471 (I != E) && !SafetyInfo->MayThrow; ++I) 472 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I); 473 474 // Compute funclet colors if we might sink/hoist in a function with a funclet 475 // personality routine. 476 Function *Fn = CurLoop->getHeader()->getParent(); 477 if (Fn->hasPersonalityFn()) 478 if (Constant *PersonalityFn = Fn->getPersonalityFn()) 479 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn))) 480 SafetyInfo->BlockColors = colorEHFunclets(*Fn); 481 } 482 483 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, 484 Loop *CurLoop, AliasSetTracker *CurAST, 485 LoopSafetyInfo *SafetyInfo, 486 OptimizationRemarkEmitter *ORE) { 487 // Loads have extra constraints we have to verify before we can hoist them. 488 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 489 if (!LI->isUnordered()) 490 return false; // Don't hoist volatile/atomic loads! 491 492 // Loads from constant memory are always safe to move, even if they end up 493 // in the same alias set as something that ends up being modified. 494 if (AA->pointsToConstantMemory(LI->getOperand(0))) 495 return true; 496 if (LI->getMetadata(LLVMContext::MD_invariant_load)) 497 return true; 498 499 // Don't hoist loads which have may-aliased stores in loop. 500 uint64_t Size = 0; 501 if (LI->getType()->isSized()) 502 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType()); 503 504 AAMDNodes AAInfo; 505 LI->getAAMetadata(AAInfo); 506 507 bool Invalidated = 508 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST); 509 // Check loop-invariant address because this may also be a sinkable load 510 // whose address is not necessarily loop-invariant. 511 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) 512 ORE->emit(OptimizationRemarkMissed( 513 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI) 514 << "failed to move load with loop-invariant address " 515 "because the loop may invalidate its value"); 516 517 return !Invalidated; 518 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 519 // Don't sink or hoist dbg info; it's legal, but not useful. 520 if (isa<DbgInfoIntrinsic>(I)) 521 return false; 522 523 // Don't sink calls which can throw. 524 if (CI->mayThrow()) 525 return false; 526 527 // Handle simple cases by querying alias analysis. 528 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 529 if (Behavior == FMRB_DoesNotAccessMemory) 530 return true; 531 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 532 // A readonly argmemonly function only reads from memory pointed to by 533 // it's arguments with arbitrary offsets. If we can prove there are no 534 // writes to this memory in the loop, we can hoist or sink. 535 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 536 for (Value *Op : CI->arg_operands()) 537 if (Op->getType()->isPointerTy() && 538 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize, 539 AAMDNodes(), CurAST)) 540 return false; 541 return true; 542 } 543 // If this call only reads from memory and there are no writes to memory 544 // in the loop, we can hoist or sink the call as appropriate. 545 bool FoundMod = false; 546 for (AliasSet &AS : *CurAST) { 547 if (!AS.isForwardingAliasSet() && AS.isMod()) { 548 FoundMod = true; 549 break; 550 } 551 } 552 if (!FoundMod) 553 return true; 554 } 555 556 // FIXME: This should use mod/ref information to see if we can hoist or 557 // sink the call. 558 559 return false; 560 } 561 562 // Only these instructions are hoistable/sinkable. 563 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 564 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 565 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 566 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 567 !isa<InsertValueInst>(I)) 568 return false; 569 570 // SafetyInfo is nullptr if we are checking for sinking from preheader to 571 // loop body. It will be always safe as there is no speculative execution. 572 if (!SafetyInfo) 573 return true; 574 575 // TODO: Plumb the context instruction through to make hoisting and sinking 576 // more powerful. Hoisting of loads already works due to the special casing 577 // above. 578 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr); 579 } 580 581 /// Returns true if a PHINode is a trivially replaceable with an 582 /// Instruction. 583 /// This is true when all incoming values are that instruction. 584 /// This pattern occurs most often with LCSSA PHI nodes. 585 /// 586 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) { 587 for (const Value *IncValue : PN.incoming_values()) 588 if (IncValue != &I) 589 return false; 590 591 return true; 592 } 593 594 /// Return true if the only users of this instruction are outside of 595 /// the loop. If this is true, we can sink the instruction to the exit 596 /// blocks of the loop. 597 /// 598 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 599 const LoopSafetyInfo *SafetyInfo) { 600 const auto &BlockColors = SafetyInfo->BlockColors; 601 for (const User *U : I.users()) { 602 const Instruction *UI = cast<Instruction>(U); 603 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 604 const BasicBlock *BB = PN->getParent(); 605 // We cannot sink uses in catchswitches. 606 if (isa<CatchSwitchInst>(BB->getTerminator())) 607 return false; 608 609 // We need to sink a callsite to a unique funclet. Avoid sinking if the 610 // phi use is too muddled. 611 if (isa<CallInst>(I)) 612 if (!BlockColors.empty() && 613 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 614 return false; 615 616 // A PHI node where all of the incoming values are this instruction are 617 // special -- they can just be RAUW'ed with the instruction and thus 618 // don't require a use in the predecessor. This is a particular important 619 // special case because it is the pattern found in LCSSA form. 620 if (isTriviallyReplacablePHI(*PN, I)) { 621 if (CurLoop->contains(PN)) 622 return false; 623 else 624 continue; 625 } 626 627 // Otherwise, PHI node uses occur in predecessor blocks if the incoming 628 // values. Check for such a use being inside the loop. 629 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 630 if (PN->getIncomingValue(i) == &I) 631 if (CurLoop->contains(PN->getIncomingBlock(i))) 632 return false; 633 634 continue; 635 } 636 637 if (CurLoop->contains(UI)) 638 return false; 639 } 640 return true; 641 } 642 643 static Instruction * 644 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 645 const LoopInfo *LI, 646 const LoopSafetyInfo *SafetyInfo) { 647 Instruction *New; 648 if (auto *CI = dyn_cast<CallInst>(&I)) { 649 const auto &BlockColors = SafetyInfo->BlockColors; 650 651 // Sinking call-sites need to be handled differently from other 652 // instructions. The cloned call-site needs a funclet bundle operand 653 // appropriate for it's location in the CFG. 654 SmallVector<OperandBundleDef, 1> OpBundles; 655 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 656 BundleIdx != BundleEnd; ++BundleIdx) { 657 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 658 if (Bundle.getTagID() == LLVMContext::OB_funclet) 659 continue; 660 661 OpBundles.emplace_back(Bundle); 662 } 663 664 if (!BlockColors.empty()) { 665 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 666 assert(CV.size() == 1 && "non-unique color for exit block!"); 667 BasicBlock *BBColor = CV.front(); 668 Instruction *EHPad = BBColor->getFirstNonPHI(); 669 if (EHPad->isEHPad()) 670 OpBundles.emplace_back("funclet", EHPad); 671 } 672 673 New = CallInst::Create(CI, OpBundles); 674 } else { 675 New = I.clone(); 676 } 677 678 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 679 if (!I.getName().empty()) 680 New->setName(I.getName() + ".le"); 681 682 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 683 // particularly cheap because we can rip off the PHI node that we're 684 // replacing for the number and blocks of the predecessors. 685 // OPT: If this shows up in a profile, we can instead finish sinking all 686 // invariant instructions, and then walk their operands to re-establish 687 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 688 // sinking bottom-up. 689 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 690 ++OI) 691 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 692 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 693 if (!OLoop->contains(&PN)) { 694 PHINode *OpPN = 695 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 696 OInst->getName() + ".lcssa", &ExitBlock.front()); 697 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 698 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 699 *OI = OpPN; 700 } 701 return New; 702 } 703 704 /// When an instruction is found to only be used outside of the loop, this 705 /// function moves it to the exit blocks and patches up SSA form as needed. 706 /// This method is guaranteed to remove the original instruction from its 707 /// position, and may either delete it or move it to outside of the loop. 708 /// 709 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 710 const Loop *CurLoop, AliasSetTracker *CurAST, 711 const LoopSafetyInfo *SafetyInfo, 712 OptimizationRemarkEmitter *ORE) { 713 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 714 ORE->emit(OptimizationRemark(DEBUG_TYPE, "InstSunk", &I) 715 << "sinking " << ore::NV("Inst", &I)); 716 bool Changed = false; 717 if (isa<LoadInst>(I)) 718 ++NumMovedLoads; 719 else if (isa<CallInst>(I)) 720 ++NumMovedCalls; 721 ++NumSunk; 722 Changed = true; 723 724 #ifndef NDEBUG 725 SmallVector<BasicBlock *, 32> ExitBlocks; 726 CurLoop->getUniqueExitBlocks(ExitBlocks); 727 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 728 ExitBlocks.end()); 729 #endif 730 731 // Clones of this instruction. Don't create more than one per exit block! 732 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 733 734 // If this instruction is only used outside of the loop, then all users are 735 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 736 // the instruction. 737 while (!I.use_empty()) { 738 Value::user_iterator UI = I.user_begin(); 739 auto *User = cast<Instruction>(*UI); 740 if (!DT->isReachableFromEntry(User->getParent())) { 741 User->replaceUsesOfWith(&I, UndefValue::get(I.getType())); 742 continue; 743 } 744 // The user must be a PHI node. 745 PHINode *PN = cast<PHINode>(User); 746 747 // Surprisingly, instructions can be used outside of loops without any 748 // exits. This can only happen in PHI nodes if the incoming block is 749 // unreachable. 750 Use &U = UI.getUse(); 751 BasicBlock *BB = PN->getIncomingBlock(U); 752 if (!DT->isReachableFromEntry(BB)) { 753 U = UndefValue::get(I.getType()); 754 continue; 755 } 756 757 BasicBlock *ExitBlock = PN->getParent(); 758 assert(ExitBlockSet.count(ExitBlock) && 759 "The LCSSA PHI is not in an exit block!"); 760 761 Instruction *New; 762 auto It = SunkCopies.find(ExitBlock); 763 if (It != SunkCopies.end()) 764 New = It->second; 765 else 766 New = SunkCopies[ExitBlock] = 767 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo); 768 769 PN->replaceAllUsesWith(New); 770 PN->eraseFromParent(); 771 } 772 773 CurAST->deleteValue(&I); 774 I.eraseFromParent(); 775 return Changed; 776 } 777 778 /// When an instruction is found to only use loop invariant operands that 779 /// is safe to hoist, this instruction is called to do the dirty work. 780 /// 781 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 782 const LoopSafetyInfo *SafetyInfo, 783 OptimizationRemarkEmitter *ORE) { 784 auto *Preheader = CurLoop->getLoopPreheader(); 785 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I 786 << "\n"); 787 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) 788 << "hosting " << ore::NV("Inst", &I)); 789 790 // Metadata can be dependent on conditions we are hoisting above. 791 // Conservatively strip all metadata on the instruction unless we were 792 // guaranteed to execute I if we entered the loop, in which case the metadata 793 // is valid in the loop preheader. 794 if (I.hasMetadataOtherThanDebugLoc() && 795 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 796 // time in isGuaranteedToExecute if we don't actually have anything to 797 // drop. It is a compile time optimization, not required for correctness. 798 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo)) 799 I.dropUnknownNonDebugMetadata(); 800 801 // Move the new node to the Preheader, before its terminator. 802 I.moveBefore(Preheader->getTerminator()); 803 804 // Do not retain debug locations when we are moving instructions to different 805 // basic blocks, because we want to avoid jumpy line tables. Calls, however, 806 // need to retain their debug locs because they may be inlined. 807 // FIXME: How do we retain source locations without causing poor debugging 808 // behavior? 809 if (!isa<CallInst>(I)) 810 I.setDebugLoc(DebugLoc()); 811 812 if (isa<LoadInst>(I)) 813 ++NumMovedLoads; 814 else if (isa<CallInst>(I)) 815 ++NumMovedCalls; 816 ++NumHoisted; 817 return true; 818 } 819 820 /// Only sink or hoist an instruction if it is not a trapping instruction, 821 /// or if the instruction is known not to trap when moved to the preheader. 822 /// or if it is a trapping instruction and is guaranteed to execute. 823 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 824 const DominatorTree *DT, 825 const Loop *CurLoop, 826 const LoopSafetyInfo *SafetyInfo, 827 OptimizationRemarkEmitter *ORE, 828 const Instruction *CtxI) { 829 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) 830 return true; 831 832 bool GuaranteedToExecute = 833 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo); 834 835 if (!GuaranteedToExecute) { 836 auto *LI = dyn_cast<LoadInst>(&Inst); 837 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) 838 ORE->emit(OptimizationRemarkMissed( 839 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI) 840 << "failed to hoist load with loop-invariant address " 841 "because load is conditionally executed"); 842 } 843 844 return GuaranteedToExecute; 845 } 846 847 namespace { 848 class LoopPromoter : public LoadAndStorePromoter { 849 Value *SomePtr; // Designated pointer to store to. 850 SmallPtrSetImpl<Value *> &PointerMustAliases; 851 SmallVectorImpl<BasicBlock *> &LoopExitBlocks; 852 SmallVectorImpl<Instruction *> &LoopInsertPts; 853 PredIteratorCache &PredCache; 854 AliasSetTracker &AST; 855 LoopInfo &LI; 856 DebugLoc DL; 857 int Alignment; 858 AAMDNodes AATags; 859 860 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 861 if (Instruction *I = dyn_cast<Instruction>(V)) 862 if (Loop *L = LI.getLoopFor(I->getParent())) 863 if (!L->contains(BB)) { 864 // We need to create an LCSSA PHI node for the incoming value and 865 // store that. 866 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), 867 I->getName() + ".lcssa", &BB->front()); 868 for (BasicBlock *Pred : PredCache.get(BB)) 869 PN->addIncoming(I, Pred); 870 return PN; 871 } 872 return V; 873 } 874 875 public: 876 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, 877 SmallPtrSetImpl<Value *> &PMA, 878 SmallVectorImpl<BasicBlock *> &LEB, 879 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, 880 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, 881 const AAMDNodes &AATags) 882 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 883 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), 884 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {} 885 886 bool isInstInList(Instruction *I, 887 const SmallVectorImpl<Instruction *> &) const override { 888 Value *Ptr; 889 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 890 Ptr = LI->getOperand(0); 891 else 892 Ptr = cast<StoreInst>(I)->getPointerOperand(); 893 return PointerMustAliases.count(Ptr); 894 } 895 896 void doExtraRewritesBeforeFinalDeletion() const override { 897 // Insert stores after in the loop exit blocks. Each exit block gets a 898 // store of the live-out values that feed them. Since we've already told 899 // the SSA updater about the defs in the loop and the preheader 900 // definition, it is all set and we can start using it. 901 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 902 BasicBlock *ExitBlock = LoopExitBlocks[i]; 903 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 904 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 905 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 906 Instruction *InsertPos = LoopInsertPts[i]; 907 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 908 NewSI->setAlignment(Alignment); 909 NewSI->setDebugLoc(DL); 910 if (AATags) 911 NewSI->setAAMetadata(AATags); 912 } 913 } 914 915 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 916 // Update alias analysis. 917 AST.copyValue(LI, V); 918 } 919 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); } 920 }; 921 } // end anon namespace 922 923 /// Try to promote memory values to scalars by sinking stores out of the 924 /// loop and moving loads to before the loop. We do this by looping over 925 /// the stores in the loop, looking for stores to Must pointers which are 926 /// loop invariant. 927 /// 928 bool llvm::promoteLoopAccessesToScalars( 929 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks, 930 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC, 931 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 932 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, 933 OptimizationRemarkEmitter *ORE) { 934 // Verify inputs. 935 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && 936 CurAST != nullptr && SafetyInfo != nullptr && 937 "Unexpected Input to promoteLoopAccessesToScalars"); 938 939 // We can promote this alias set if it has a store, if it is a "Must" alias 940 // set, if the pointer is loop invariant, and if we are not eliminating any 941 // volatile loads or stores. 942 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 943 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 944 return false; 945 946 assert(!AS.empty() && 947 "Must alias set should have at least one pointer element in it!"); 948 949 Value *SomePtr = AS.begin()->getValue(); 950 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 951 952 // It isn't safe to promote a load/store from the loop if the load/store is 953 // conditional. For example, turning: 954 // 955 // for () { if (c) *P += 1; } 956 // 957 // into: 958 // 959 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 960 // 961 // is not safe, because *P may only be valid to access if 'c' is true. 962 // 963 // The safety property divides into two parts: 964 // p1) The memory may not be dereferenceable on entry to the loop. In this 965 // case, we can't insert the required load in the preheader. 966 // p2) The memory model does not allow us to insert a store along any dynamic 967 // path which did not originally have one. 968 // 969 // If at least one store is guaranteed to execute, both properties are 970 // satisfied, and promotion is legal. 971 // 972 // This, however, is not a necessary condition. Even if no store/load is 973 // guaranteed to execute, we can still establish these properties. 974 // We can establish (p1) by proving that hoisting the load into the preheader 975 // is safe (i.e. proving dereferenceability on all paths through the loop). We 976 // can use any access within the alias set to prove dereferenceability, 977 // since they're all must alias. 978 // 979 // There are two ways establish (p2): 980 // a) Prove the location is thread-local. In this case the memory model 981 // requirement does not apply, and stores are safe to insert. 982 // b) Prove a store dominates every exit block. In this case, if an exit 983 // blocks is reached, the original dynamic path would have taken us through 984 // the store, so inserting a store into the exit block is safe. Note that this 985 // is different from the store being guaranteed to execute. For instance, 986 // if an exception is thrown on the first iteration of the loop, the original 987 // store is never executed, but the exit blocks are not executed either. 988 989 bool DereferenceableInPH = false; 990 bool SafeToInsertStore = false; 991 992 SmallVector<Instruction *, 64> LoopUses; 993 SmallPtrSet<Value *, 4> PointerMustAliases; 994 995 // We start with an alignment of one and try to find instructions that allow 996 // us to prove better alignment. 997 unsigned Alignment = 1; 998 AAMDNodes AATags; 999 1000 const DataLayout &MDL = Preheader->getModule()->getDataLayout(); 1001 1002 // Do we know this object does not escape ? 1003 bool IsKnownNonEscapingObject = false; 1004 if (SafetyInfo->MayThrow) { 1005 // If a loop can throw, we have to insert a store along each unwind edge. 1006 // That said, we can't actually make the unwind edge explicit. Therefore, 1007 // we have to prove that the store is dead along the unwind edge. 1008 // 1009 // If the underlying object is not an alloca, nor a pointer that does not 1010 // escape, then we can not effectively prove that the store is dead along 1011 // the unwind edge. i.e. the caller of this function could have ways to 1012 // access the pointed object. 1013 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1014 // If this is a base pointer we do not understand, simply bail. 1015 // We only handle alloca and return value from alloc-like fn right now. 1016 if (!isa<AllocaInst>(Object)) { 1017 if (!isAllocLikeFn(Object, TLI)) 1018 return false; 1019 // If this is an alloc like fn. There are more constraints we need to verify. 1020 // More specifically, we must make sure that the pointer can not escape. 1021 // 1022 // NOTE: PointerMayBeCaptured is not enough as the pointer may have escaped 1023 // even though its not captured by the enclosing function. Standard allocation 1024 // functions like malloc, calloc, and operator new return values which can 1025 // be assumed not to have previously escaped. 1026 if (PointerMayBeCaptured(Object, true, true)) 1027 return false; 1028 IsKnownNonEscapingObject = true; 1029 } 1030 } 1031 1032 // Check that all of the pointers in the alias set have the same type. We 1033 // cannot (yet) promote a memory location that is loaded and stored in 1034 // different sizes. While we are at it, collect alignment and AA info. 1035 for (const auto &ASI : AS) { 1036 Value *ASIV = ASI.getValue(); 1037 PointerMustAliases.insert(ASIV); 1038 1039 // Check that all of the pointers in the alias set have the same type. We 1040 // cannot (yet) promote a memory location that is loaded and stored in 1041 // different sizes. 1042 if (SomePtr->getType() != ASIV->getType()) 1043 return false; 1044 1045 for (User *U : ASIV->users()) { 1046 // Ignore instructions that are outside the loop. 1047 Instruction *UI = dyn_cast<Instruction>(U); 1048 if (!UI || !CurLoop->contains(UI)) 1049 continue; 1050 1051 // If there is an non-load/store instruction in the loop, we can't promote 1052 // it. 1053 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { 1054 assert(!Load->isVolatile() && "AST broken"); 1055 if (!Load->isSimple()) 1056 return false; 1057 1058 if (!DereferenceableInPH) 1059 DereferenceableInPH = isSafeToExecuteUnconditionally( 1060 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator()); 1061 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 1062 // Stores *of* the pointer are not interesting, only stores *to* the 1063 // pointer. 1064 if (UI->getOperand(1) != ASIV) 1065 continue; 1066 assert(!Store->isVolatile() && "AST broken"); 1067 if (!Store->isSimple()) 1068 return false; 1069 1070 // If the store is guaranteed to execute, both properties are satisfied. 1071 // We may want to check if a store is guaranteed to execute even if we 1072 // already know that promotion is safe, since it may have higher 1073 // alignment than any other guaranteed stores, in which case we can 1074 // raise the alignment on the promoted store. 1075 unsigned InstAlignment = Store->getAlignment(); 1076 if (!InstAlignment) 1077 InstAlignment = 1078 MDL.getABITypeAlignment(Store->getValueOperand()->getType()); 1079 1080 if (!DereferenceableInPH || !SafeToInsertStore || 1081 (InstAlignment > Alignment)) { 1082 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) { 1083 DereferenceableInPH = true; 1084 SafeToInsertStore = true; 1085 Alignment = std::max(Alignment, InstAlignment); 1086 } 1087 } 1088 1089 // If a store dominates all exit blocks, it is safe to sink. 1090 // As explained above, if an exit block was executed, a dominating 1091 // store must have been been executed at least once, so we are not 1092 // introducing stores on paths that did not have them. 1093 // Note that this only looks at explicit exit blocks. If we ever 1094 // start sinking stores into unwind edges (see above), this will break. 1095 if (!SafeToInsertStore) 1096 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { 1097 return DT->dominates(Store->getParent(), Exit); 1098 }); 1099 1100 // If the store is not guaranteed to execute, we may still get 1101 // deref info through it. 1102 if (!DereferenceableInPH) { 1103 DereferenceableInPH = isDereferenceableAndAlignedPointer( 1104 Store->getPointerOperand(), Store->getAlignment(), MDL, 1105 Preheader->getTerminator(), DT); 1106 } 1107 } else 1108 return false; // Not a load or store. 1109 1110 // Merge the AA tags. 1111 if (LoopUses.empty()) { 1112 // On the first load/store, just take its AA tags. 1113 UI->getAAMetadata(AATags); 1114 } else if (AATags) { 1115 UI->getAAMetadata(AATags, /* Merge = */ true); 1116 } 1117 1118 LoopUses.push_back(UI); 1119 } 1120 } 1121 1122 1123 // If we couldn't prove we can hoist the load, bail. 1124 if (!DereferenceableInPH) 1125 return false; 1126 1127 // We know we can hoist the load, but don't have a guaranteed store. 1128 // Check whether the location is thread-local. If it is, then we can insert 1129 // stores along paths which originally didn't have them without violating the 1130 // memory model. 1131 if (!SafeToInsertStore) { 1132 // If this is a known non-escaping object, it is safe to insert the stores. 1133 if (IsKnownNonEscapingObject) 1134 SafeToInsertStore = true; 1135 else { 1136 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1137 SafeToInsertStore = 1138 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && 1139 !PointerMayBeCaptured(Object, true, true); 1140 } 1141 } 1142 1143 // If we've still failed to prove we can sink the store, give up. 1144 if (!SafeToInsertStore) 1145 return false; 1146 1147 // Otherwise, this is safe to promote, lets do it! 1148 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr 1149 << '\n'); 1150 ORE->emit( 1151 OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", LoopUses[0]) 1152 << "Moving accesses to memory location out of the loop"); 1153 ++NumPromoted; 1154 1155 // Grab a debug location for the inserted loads/stores; given that the 1156 // inserted loads/stores have little relation to the original loads/stores, 1157 // this code just arbitrarily picks a location from one, since any debug 1158 // location is better than none. 1159 DebugLoc DL = LoopUses[0]->getDebugLoc(); 1160 1161 // We use the SSAUpdater interface to insert phi nodes as required. 1162 SmallVector<PHINode *, 16> NewPHIs; 1163 SSAUpdater SSA(&NewPHIs); 1164 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 1165 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags); 1166 1167 // Set up the preheader to have a definition of the value. It is the live-out 1168 // value from the preheader that uses in the loop will use. 1169 LoadInst *PreheaderLoad = new LoadInst( 1170 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator()); 1171 PreheaderLoad->setAlignment(Alignment); 1172 PreheaderLoad->setDebugLoc(DL); 1173 if (AATags) 1174 PreheaderLoad->setAAMetadata(AATags); 1175 SSA.AddAvailableValue(Preheader, PreheaderLoad); 1176 1177 // Rewrite all the loads in the loop and remember all the definitions from 1178 // stores in the loop. 1179 Promoter.run(LoopUses); 1180 1181 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 1182 if (PreheaderLoad->use_empty()) 1183 PreheaderLoad->eraseFromParent(); 1184 1185 return true; 1186 } 1187 1188 /// Returns an owning pointer to an alias set which incorporates aliasing info 1189 /// from L and all subloops of L. 1190 /// FIXME: In new pass manager, there is no helper function to handle loop 1191 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed 1192 /// from scratch for every loop. Hook up with the helper functions when 1193 /// available in the new pass manager to avoid redundant computation. 1194 AliasSetTracker * 1195 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 1196 AliasAnalysis *AA) { 1197 AliasSetTracker *CurAST = nullptr; 1198 SmallVector<Loop *, 4> RecomputeLoops; 1199 for (Loop *InnerL : L->getSubLoops()) { 1200 auto MapI = LoopToAliasSetMap.find(InnerL); 1201 // If the AST for this inner loop is missing it may have been merged into 1202 // some other loop's AST and then that loop unrolled, and so we need to 1203 // recompute it. 1204 if (MapI == LoopToAliasSetMap.end()) { 1205 RecomputeLoops.push_back(InnerL); 1206 continue; 1207 } 1208 AliasSetTracker *InnerAST = MapI->second; 1209 1210 if (CurAST != nullptr) { 1211 // What if InnerLoop was modified by other passes ? 1212 CurAST->add(*InnerAST); 1213 1214 // Once we've incorporated the inner loop's AST into ours, we don't need 1215 // the subloop's anymore. 1216 delete InnerAST; 1217 } else { 1218 CurAST = InnerAST; 1219 } 1220 LoopToAliasSetMap.erase(MapI); 1221 } 1222 if (CurAST == nullptr) 1223 CurAST = new AliasSetTracker(*AA); 1224 1225 auto mergeLoop = [&](Loop *L) { 1226 // Loop over the body of this loop, looking for calls, invokes, and stores. 1227 // Because subloops have already been incorporated into AST, we skip blocks 1228 // in subloops. 1229 for (BasicBlock *BB : L->blocks()) 1230 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops. 1231 CurAST->add(*BB); // Incorporate the specified basic block 1232 }; 1233 1234 // Add everything from the sub loops that are no longer directly available. 1235 for (Loop *InnerL : RecomputeLoops) 1236 mergeLoop(InnerL); 1237 1238 // And merge in this loop. 1239 mergeLoop(L); 1240 1241 return CurAST; 1242 } 1243 1244 /// Simple analysis hook. Clone alias set info. 1245 /// 1246 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 1247 Loop *L) { 1248 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1249 if (!AST) 1250 return; 1251 1252 AST->copyValue(From, To); 1253 } 1254 1255 /// Simple Analysis hook. Delete value V from alias set 1256 /// 1257 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) { 1258 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1259 if (!AST) 1260 return; 1261 1262 AST->deleteValue(V); 1263 } 1264 1265 /// Simple Analysis hook. Delete value L from alias set map. 1266 /// 1267 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) { 1268 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L); 1269 if (!AST) 1270 return; 1271 1272 delete AST; 1273 LICM.getLoopToAliasSetMap().erase(L); 1274 } 1275 1276 /// Return true if the body of this loop may store into the memory 1277 /// location pointed to by V. 1278 /// 1279 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 1280 const AAMDNodes &AAInfo, 1281 AliasSetTracker *CurAST) { 1282 // Check to see if any of the basic blocks in CurLoop invalidate *V. 1283 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod(); 1284 } 1285 1286 /// Little predicate that returns true if the specified basic block is in 1287 /// a subloop of the current one, not the current one itself. 1288 /// 1289 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 1290 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 1291 return LI->getLoopFor(BB) != CurLoop; 1292 } 1293