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