1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass performs loop invariant code motion, attempting to remove as much 10 // code from the body of a loop as possible. It does this by either hoisting 11 // code into the preheader block, or by sinking code to the exit blocks if it is 12 // safe. This pass also promotes must-aliased memory locations in the loop to 13 // live in registers, thus hoisting and sinking "invariant" loads and stores. 14 // 15 // This pass uses alias analysis for two purposes: 16 // 17 // 1. Moving loop invariant loads and calls out of loops. If we can determine 18 // that a load or call inside of a loop never aliases anything stored to, 19 // we can hoist it or sink it like any other instruction. 20 // 2. Scalar Promotion of Memory - If there is a store instruction inside of 21 // the loop, we try to move the store to happen AFTER the loop instead of 22 // inside of the loop. This can only happen if a few conditions are true: 23 // A. The pointer stored through is loop invariant 24 // B. There are no stores or loads in the loop which _may_ alias the 25 // pointer. There are no calls in the loop which mod/ref the pointer. 26 // If these conditions are true, we can promote the loads and stores in the 27 // loop of the pointer to use a temporary alloca'd variable. We then use 28 // the SSAUpdater to construct the appropriate SSA form for the value. 29 // 30 //===----------------------------------------------------------------------===// 31 32 #include "llvm/Transforms/Scalar/LICM.h" 33 #include "llvm/ADT/SetOperations.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/GuardUtils.h" 42 #include "llvm/Analysis/Loads.h" 43 #include "llvm/Analysis/LoopInfo.h" 44 #include "llvm/Analysis/LoopIterator.h" 45 #include "llvm/Analysis/LoopPass.h" 46 #include "llvm/Analysis/MemoryBuiltins.h" 47 #include "llvm/Analysis/MemorySSA.h" 48 #include "llvm/Analysis/MemorySSAUpdater.h" 49 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 50 #include "llvm/Analysis/ScalarEvolution.h" 51 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 52 #include "llvm/Analysis/TargetLibraryInfo.h" 53 #include "llvm/Analysis/ValueTracking.h" 54 #include "llvm/IR/CFG.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugInfoMetadata.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/Dominators.h" 60 #include "llvm/IR/Instructions.h" 61 #include "llvm/IR/IntrinsicInst.h" 62 #include "llvm/IR/LLVMContext.h" 63 #include "llvm/IR/Metadata.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/IR/PredIteratorCache.h" 66 #include "llvm/InitializePasses.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Debug.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Transforms/Scalar.h" 71 #include "llvm/Transforms/Scalar/LoopPassManager.h" 72 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 73 #include "llvm/Transforms/Utils/Local.h" 74 #include "llvm/Transforms/Utils/LoopUtils.h" 75 #include "llvm/Transforms/Utils/SSAUpdater.h" 76 #include <algorithm> 77 #include <utility> 78 using namespace llvm; 79 80 #define DEBUG_TYPE "licm" 81 82 STATISTIC(NumCreatedBlocks, "Number of blocks created"); 83 STATISTIC(NumClonedBranches, "Number of branches cloned"); 84 STATISTIC(NumSunk, "Number of instructions sunk out of loop"); 85 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); 86 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 87 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 88 STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); 89 90 /// Memory promotion is enabled by default. 91 static cl::opt<bool> 92 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), 93 cl::desc("Disable memory promotion in LICM pass")); 94 95 static cl::opt<bool> ControlFlowHoisting( 96 "licm-control-flow-hoisting", cl::Hidden, cl::init(false), 97 cl::desc("Enable control flow (and PHI) hoisting in LICM")); 98 99 static cl::opt<uint32_t> MaxNumUsesTraversed( 100 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8), 101 cl::desc("Max num uses visited for identifying load " 102 "invariance in loop using invariant start (default = 8)")); 103 104 // Default value of zero implies we use the regular alias set tracker mechanism 105 // instead of the cross product using AA to identify aliasing of the memory 106 // location we are interested in. 107 static cl::opt<int> 108 LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0), 109 cl::desc("How many instruction to cross product using AA")); 110 111 // Experimental option to allow imprecision in LICM in pathological cases, in 112 // exchange for faster compile. This is to be removed if MemorySSA starts to 113 // address the same issue. This flag applies only when LICM uses MemorySSA 114 // instead on AliasSetTracker. LICM calls MemorySSAWalker's 115 // getClobberingMemoryAccess, up to the value of the Cap, getting perfect 116 // accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess, 117 // which may not be precise, since optimizeUses is capped. The result is 118 // correct, but we may not get as "far up" as possible to get which access is 119 // clobbering the one queried. 120 cl::opt<unsigned> llvm::SetLicmMssaOptCap( 121 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden, 122 cl::desc("Enable imprecision in LICM in pathological cases, in exchange " 123 "for faster compile. Caps the MemorySSA clobbering calls.")); 124 125 // Experimentally, memory promotion carries less importance than sinking and 126 // hoisting. Limit when we do promotion when using MemorySSA, in order to save 127 // compile time. 128 cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap( 129 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden, 130 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no " 131 "effect. When MSSA in LICM is enabled, then this is the maximum " 132 "number of accesses allowed to be present in a loop in order to " 133 "enable memory promotion.")); 134 135 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 136 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 137 const LoopSafetyInfo *SafetyInfo, 138 TargetTransformInfo *TTI, bool &FreeInLoop); 139 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 140 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, 141 MemorySSAUpdater *MSSAU, ScalarEvolution *SE, 142 OptimizationRemarkEmitter *ORE); 143 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 144 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, 145 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE); 146 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 147 const DominatorTree *DT, 148 const Loop *CurLoop, 149 const LoopSafetyInfo *SafetyInfo, 150 OptimizationRemarkEmitter *ORE, 151 const Instruction *CtxI = nullptr); 152 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, 153 AliasSetTracker *CurAST, Loop *CurLoop, 154 AliasAnalysis *AA); 155 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, 156 Loop *CurLoop, 157 SinkAndHoistLICMFlags &Flags); 158 static Instruction *CloneInstructionInExitBlock( 159 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, 160 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU); 161 162 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, 163 AliasSetTracker *AST, MemorySSAUpdater *MSSAU); 164 165 static void moveInstructionBefore(Instruction &I, Instruction &Dest, 166 ICFLoopSafetyInfo &SafetyInfo, 167 MemorySSAUpdater *MSSAU, ScalarEvolution *SE); 168 169 namespace { 170 struct LoopInvariantCodeMotion { 171 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 172 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, 173 ScalarEvolution *SE, MemorySSA *MSSA, 174 OptimizationRemarkEmitter *ORE); 175 176 LoopInvariantCodeMotion(unsigned LicmMssaOptCap, 177 unsigned LicmMssaNoAccForPromotionCap) 178 : LicmMssaOptCap(LicmMssaOptCap), 179 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {} 180 181 private: 182 unsigned LicmMssaOptCap; 183 unsigned LicmMssaNoAccForPromotionCap; 184 185 std::unique_ptr<AliasSetTracker> 186 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA); 187 std::unique_ptr<AliasSetTracker> 188 collectAliasInfoForLoopWithMSSA(Loop *L, AliasAnalysis *AA, 189 MemorySSAUpdater *MSSAU); 190 }; 191 192 struct LegacyLICMPass : public LoopPass { 193 static char ID; // Pass identification, replacement for typeid 194 LegacyLICMPass( 195 unsigned LicmMssaOptCap = SetLicmMssaOptCap, 196 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap) 197 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) { 198 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); 199 } 200 201 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 202 if (skipLoop(L)) 203 return false; 204 205 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 206 MemorySSA *MSSA = EnableMSSALoopDependency 207 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA()) 208 : nullptr; 209 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 210 // pass. Function analyses need to be preserved across loop transformations 211 // but ORE cannot be preserved (see comment before the pass definition). 212 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 213 return LICM.runOnLoop(L, 214 &getAnalysis<AAResultsWrapperPass>().getAAResults(), 215 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), 216 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 217 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 218 *L->getHeader()->getParent()), 219 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 220 *L->getHeader()->getParent()), 221 SE ? &SE->getSE() : nullptr, MSSA, &ORE); 222 } 223 224 /// This transformation requires natural loop information & requires that 225 /// loop preheaders be inserted into the CFG... 226 /// 227 void getAnalysisUsage(AnalysisUsage &AU) const override { 228 AU.addPreserved<DominatorTreeWrapperPass>(); 229 AU.addPreserved<LoopInfoWrapperPass>(); 230 AU.addRequired<TargetLibraryInfoWrapperPass>(); 231 if (EnableMSSALoopDependency) { 232 AU.addRequired<MemorySSAWrapperPass>(); 233 AU.addPreserved<MemorySSAWrapperPass>(); 234 } 235 AU.addRequired<TargetTransformInfoWrapperPass>(); 236 getLoopAnalysisUsage(AU); 237 } 238 239 private: 240 LoopInvariantCodeMotion LICM; 241 }; 242 } // namespace 243 244 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, 245 LoopStandardAnalysisResults &AR, LPMUpdater &) { 246 const auto &FAM = 247 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 248 Function *F = L.getHeader()->getParent(); 249 250 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); 251 // FIXME: This should probably be optional rather than required. 252 if (!ORE) 253 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not " 254 "cached at a higher level"); 255 256 LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); 257 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE, 258 AR.MSSA, ORE)) 259 return PreservedAnalyses::all(); 260 261 auto PA = getLoopPassPreservedAnalyses(); 262 263 PA.preserve<DominatorTreeAnalysis>(); 264 PA.preserve<LoopAnalysis>(); 265 if (AR.MSSA) 266 PA.preserve<MemorySSAAnalysis>(); 267 268 return PA; 269 } 270 271 char LegacyLICMPass::ID = 0; 272 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", 273 false, false) 274 INITIALIZE_PASS_DEPENDENCY(LoopPass) 275 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 276 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 277 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 278 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, 279 false) 280 281 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } 282 Pass *llvm::createLICMPass(unsigned LicmMssaOptCap, 283 unsigned LicmMssaNoAccForPromotionCap) { 284 return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap); 285 } 286 287 /// Hoist expressions out of the specified loop. Note, alias info for inner 288 /// loop is not preserved so it is not a good idea to run LICM multiple 289 /// times on one loop. 290 bool LoopInvariantCodeMotion::runOnLoop( 291 Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, 292 TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE, 293 MemorySSA *MSSA, OptimizationRemarkEmitter *ORE) { 294 bool Changed = false; 295 296 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 297 298 // If this loop has metadata indicating that LICM is not to be performed then 299 // just exit. 300 if (hasDisableLICMTransformsHint(L)) { 301 return false; 302 } 303 304 std::unique_ptr<AliasSetTracker> CurAST; 305 std::unique_ptr<MemorySSAUpdater> MSSAU; 306 bool NoOfMemAccTooLarge = false; 307 unsigned LicmMssaOptCounter = 0; 308 309 if (!MSSA) { 310 LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n"); 311 CurAST = collectAliasInfoForLoop(L, LI, AA); 312 } else { 313 LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n"); 314 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 315 316 unsigned AccessCapCount = 0; 317 for (auto *BB : L->getBlocks()) { 318 if (auto *Accesses = MSSA->getBlockAccesses(BB)) { 319 for (const auto &MA : *Accesses) { 320 (void)MA; 321 AccessCapCount++; 322 if (AccessCapCount > LicmMssaNoAccForPromotionCap) { 323 NoOfMemAccTooLarge = true; 324 break; 325 } 326 } 327 } 328 if (NoOfMemAccTooLarge) 329 break; 330 } 331 } 332 333 // Get the preheader block to move instructions into... 334 BasicBlock *Preheader = L->getLoopPreheader(); 335 336 // Compute loop safety information. 337 ICFLoopSafetyInfo SafetyInfo(DT); 338 SafetyInfo.computeLoopSafetyInfo(L); 339 340 // We want to visit all of the instructions in this loop... that are not parts 341 // of our subloops (they have already had their invariants hoisted out of 342 // their loop, into this loop, so there is no need to process the BODIES of 343 // the subloops). 344 // 345 // Traverse the body of the loop in depth first order on the dominator tree so 346 // that we are guaranteed to see definitions before we see uses. This allows 347 // us to sink instructions in one pass, without iteration. After sinking 348 // instructions, we perform another pass to hoist them out of the loop. 349 SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter, 350 LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 351 /*IsSink=*/true}; 352 if (L->hasDedicatedExits()) 353 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L, 354 CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE); 355 Flags.IsSink = false; 356 if (Preheader) 357 Changed |= 358 hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, 359 CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE); 360 361 // Now that all loop invariants have been removed from the loop, promote any 362 // memory references to scalars that we can. 363 // Don't sink stores from loops without dedicated block exits. Exits 364 // containing indirect branches are not transformed by loop simplify, 365 // make sure we catch that. An additional load may be generated in the 366 // preheader for SSA updater, so also avoid sinking when no preheader 367 // is available. 368 if (!DisablePromotion && Preheader && L->hasDedicatedExits() && 369 !NoOfMemAccTooLarge) { 370 // Figure out the loop exits and their insertion points 371 SmallVector<BasicBlock *, 8> ExitBlocks; 372 L->getUniqueExitBlocks(ExitBlocks); 373 374 // We can't insert into a catchswitch. 375 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { 376 return isa<CatchSwitchInst>(Exit->getTerminator()); 377 }); 378 379 if (!HasCatchSwitch) { 380 SmallVector<Instruction *, 8> InsertPts; 381 SmallVector<MemoryAccess *, 8> MSSAInsertPts; 382 InsertPts.reserve(ExitBlocks.size()); 383 if (MSSAU) 384 MSSAInsertPts.reserve(ExitBlocks.size()); 385 for (BasicBlock *ExitBlock : ExitBlocks) { 386 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 387 if (MSSAU) 388 MSSAInsertPts.push_back(nullptr); 389 } 390 391 PredIteratorCache PIC; 392 393 bool Promoted = false; 394 395 // Build an AST using MSSA. 396 if (!CurAST.get()) 397 CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get()); 398 399 // Loop over all of the alias sets in the tracker object. 400 for (AliasSet &AS : *CurAST) { 401 // We can promote this alias set if it has a store, if it is a "Must" 402 // alias set, if the pointer is loop invariant, and if we are not 403 // eliminating any volatile loads or stores. 404 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 405 !L->isLoopInvariant(AS.begin()->getValue())) 406 continue; 407 408 assert( 409 !AS.empty() && 410 "Must alias set should have at least one pointer element in it!"); 411 412 SmallSetVector<Value *, 8> PointerMustAliases; 413 for (const auto &ASI : AS) 414 PointerMustAliases.insert(ASI.getValue()); 415 416 Promoted |= promoteLoopAccessesToScalars( 417 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI, 418 DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE); 419 } 420 421 // Once we have promoted values across the loop body we have to 422 // recursively reform LCSSA as any nested loop may now have values defined 423 // within the loop used in the outer loop. 424 // FIXME: This is really heavy handed. It would be a bit better to use an 425 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 426 // it as it went. 427 if (Promoted) 428 formLCSSARecursively(*L, *DT, LI, SE); 429 430 Changed |= Promoted; 431 } 432 } 433 434 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 435 // specifically moving instructions across the loop boundary and so it is 436 // especially in need of sanity checking here. 437 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 438 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 439 "Parent loop not left in LCSSA form after LICM!"); 440 441 if (MSSAU.get() && VerifyMemorySSA) 442 MSSAU->getMemorySSA()->verifyMemorySSA(); 443 444 if (Changed && SE) 445 SE->forgetLoopDispositions(L); 446 return Changed; 447 } 448 449 /// Walk the specified region of the CFG (defined by all blocks dominated by 450 /// the specified block, and that are in the current loop) in reverse depth 451 /// first order w.r.t the DominatorTree. This allows us to visit uses before 452 /// definitions, allowing us to sink a loop body in one pass without iteration. 453 /// 454 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 455 DominatorTree *DT, TargetLibraryInfo *TLI, 456 TargetTransformInfo *TTI, Loop *CurLoop, 457 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 458 ICFLoopSafetyInfo *SafetyInfo, 459 SinkAndHoistLICMFlags &Flags, 460 OptimizationRemarkEmitter *ORE) { 461 462 // Verify inputs. 463 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 464 CurLoop != nullptr && SafetyInfo != nullptr && 465 "Unexpected input to sinkRegion."); 466 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && 467 "Either AliasSetTracker or MemorySSA should be initialized."); 468 469 // We want to visit children before parents. We will enque all the parents 470 // before their children in the worklist and process the worklist in reverse 471 // order. 472 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); 473 474 bool Changed = false; 475 for (DomTreeNode *DTN : reverse(Worklist)) { 476 BasicBlock *BB = DTN->getBlock(); 477 // Only need to process the contents of this block if it is not part of a 478 // subloop (which would already have been processed). 479 if (inSubLoop(BB, CurLoop, LI)) 480 continue; 481 482 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { 483 Instruction &I = *--II; 484 485 // If the instruction is dead, we would try to sink it because it isn't 486 // used in the loop, instead, just delete it. 487 if (isInstructionTriviallyDead(&I, TLI)) { 488 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 489 salvageDebugInfo(I); 490 ++II; 491 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 492 Changed = true; 493 continue; 494 } 495 496 // Check to see if we can sink this instruction to the exit blocks 497 // of the loop. We can do this if the all users of the instruction are 498 // outside of the loop. In this case, it doesn't even matter if the 499 // operands of the instruction are loop invariant. 500 // 501 bool FreeInLoop = false; 502 if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) && 503 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, 504 ORE) && 505 !I.mayHaveSideEffects()) { 506 if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) { 507 if (!FreeInLoop) { 508 ++II; 509 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 510 } 511 Changed = true; 512 } 513 } 514 } 515 } 516 if (MSSAU && VerifyMemorySSA) 517 MSSAU->getMemorySSA()->verifyMemorySSA(); 518 return Changed; 519 } 520 521 namespace { 522 // This is a helper class for hoistRegion to make it able to hoist control flow 523 // in order to be able to hoist phis. The way this works is that we initially 524 // start hoisting to the loop preheader, and when we see a loop invariant branch 525 // we make note of this. When we then come to hoist an instruction that's 526 // conditional on such a branch we duplicate the branch and the relevant control 527 // flow, then hoist the instruction into the block corresponding to its original 528 // block in the duplicated control flow. 529 class ControlFlowHoister { 530 private: 531 // Information about the loop we are hoisting from 532 LoopInfo *LI; 533 DominatorTree *DT; 534 Loop *CurLoop; 535 MemorySSAUpdater *MSSAU; 536 537 // A map of blocks in the loop to the block their instructions will be hoisted 538 // to. 539 DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap; 540 541 // The branches that we can hoist, mapped to the block that marks a 542 // convergence point of their control flow. 543 DenseMap<BranchInst *, BasicBlock *> HoistableBranches; 544 545 public: 546 ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop, 547 MemorySSAUpdater *MSSAU) 548 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {} 549 550 void registerPossiblyHoistableBranch(BranchInst *BI) { 551 // We can only hoist conditional branches with loop invariant operands. 552 if (!ControlFlowHoisting || !BI->isConditional() || 553 !CurLoop->hasLoopInvariantOperands(BI)) 554 return; 555 556 // The branch destinations need to be in the loop, and we don't gain 557 // anything by duplicating conditional branches with duplicate successors, 558 // as it's essentially the same as an unconditional branch. 559 BasicBlock *TrueDest = BI->getSuccessor(0); 560 BasicBlock *FalseDest = BI->getSuccessor(1); 561 if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) || 562 TrueDest == FalseDest) 563 return; 564 565 // We can hoist BI if one branch destination is the successor of the other, 566 // or both have common successor which we check by seeing if the 567 // intersection of their successors is non-empty. 568 // TODO: This could be expanded to allowing branches where both ends 569 // eventually converge to a single block. 570 SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc; 571 TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest)); 572 FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest)); 573 BasicBlock *CommonSucc = nullptr; 574 if (TrueDestSucc.count(FalseDest)) { 575 CommonSucc = FalseDest; 576 } else if (FalseDestSucc.count(TrueDest)) { 577 CommonSucc = TrueDest; 578 } else { 579 set_intersect(TrueDestSucc, FalseDestSucc); 580 // If there's one common successor use that. 581 if (TrueDestSucc.size() == 1) 582 CommonSucc = *TrueDestSucc.begin(); 583 // If there's more than one pick whichever appears first in the block list 584 // (we can't use the value returned by TrueDestSucc.begin() as it's 585 // unpredicatable which element gets returned). 586 else if (!TrueDestSucc.empty()) { 587 Function *F = TrueDest->getParent(); 588 auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); }; 589 auto It = std::find_if(F->begin(), F->end(), IsSucc); 590 assert(It != F->end() && "Could not find successor in function"); 591 CommonSucc = &*It; 592 } 593 } 594 // The common successor has to be dominated by the branch, as otherwise 595 // there will be some other path to the successor that will not be 596 // controlled by this branch so any phi we hoist would be controlled by the 597 // wrong condition. This also takes care of avoiding hoisting of loop back 598 // edges. 599 // TODO: In some cases this could be relaxed if the successor is dominated 600 // by another block that's been hoisted and we can guarantee that the 601 // control flow has been replicated exactly. 602 if (CommonSucc && DT->dominates(BI, CommonSucc)) 603 HoistableBranches[BI] = CommonSucc; 604 } 605 606 bool canHoistPHI(PHINode *PN) { 607 // The phi must have loop invariant operands. 608 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN)) 609 return false; 610 // We can hoist phis if the block they are in is the target of hoistable 611 // branches which cover all of the predecessors of the block. 612 SmallPtrSet<BasicBlock *, 8> PredecessorBlocks; 613 BasicBlock *BB = PN->getParent(); 614 for (BasicBlock *PredBB : predecessors(BB)) 615 PredecessorBlocks.insert(PredBB); 616 // If we have less predecessor blocks than predecessors then the phi will 617 // have more than one incoming value for the same block which we can't 618 // handle. 619 // TODO: This could be handled be erasing some of the duplicate incoming 620 // values. 621 if (PredecessorBlocks.size() != pred_size(BB)) 622 return false; 623 for (auto &Pair : HoistableBranches) { 624 if (Pair.second == BB) { 625 // Which blocks are predecessors via this branch depends on if the 626 // branch is triangle-like or diamond-like. 627 if (Pair.first->getSuccessor(0) == BB) { 628 PredecessorBlocks.erase(Pair.first->getParent()); 629 PredecessorBlocks.erase(Pair.first->getSuccessor(1)); 630 } else if (Pair.first->getSuccessor(1) == BB) { 631 PredecessorBlocks.erase(Pair.first->getParent()); 632 PredecessorBlocks.erase(Pair.first->getSuccessor(0)); 633 } else { 634 PredecessorBlocks.erase(Pair.first->getSuccessor(0)); 635 PredecessorBlocks.erase(Pair.first->getSuccessor(1)); 636 } 637 } 638 } 639 // PredecessorBlocks will now be empty if for every predecessor of BB we 640 // found a hoistable branch source. 641 return PredecessorBlocks.empty(); 642 } 643 644 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) { 645 if (!ControlFlowHoisting) 646 return CurLoop->getLoopPreheader(); 647 // If BB has already been hoisted, return that 648 if (HoistDestinationMap.count(BB)) 649 return HoistDestinationMap[BB]; 650 651 // Check if this block is conditional based on a pending branch 652 auto HasBBAsSuccessor = 653 [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) { 654 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB || 655 Pair.first->getSuccessor(1) == BB); 656 }; 657 auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(), 658 HasBBAsSuccessor); 659 660 // If not involved in a pending branch, hoist to preheader 661 BasicBlock *InitialPreheader = CurLoop->getLoopPreheader(); 662 if (It == HoistableBranches.end()) { 663 LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName() 664 << " as hoist destination for " << BB->getName() 665 << "\n"); 666 HoistDestinationMap[BB] = InitialPreheader; 667 return InitialPreheader; 668 } 669 BranchInst *BI = It->first; 670 assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == 671 HoistableBranches.end() && 672 "BB is expected to be the target of at most one branch"); 673 674 LLVMContext &C = BB->getContext(); 675 BasicBlock *TrueDest = BI->getSuccessor(0); 676 BasicBlock *FalseDest = BI->getSuccessor(1); 677 BasicBlock *CommonSucc = HoistableBranches[BI]; 678 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent()); 679 680 // Create hoisted versions of blocks that currently don't have them 681 auto CreateHoistedBlock = [&](BasicBlock *Orig) { 682 if (HoistDestinationMap.count(Orig)) 683 return HoistDestinationMap[Orig]; 684 BasicBlock *New = 685 BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent()); 686 HoistDestinationMap[Orig] = New; 687 DT->addNewBlock(New, HoistTarget); 688 if (CurLoop->getParentLoop()) 689 CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI); 690 ++NumCreatedBlocks; 691 LLVM_DEBUG(dbgs() << "LICM created " << New->getName() 692 << " as hoist destination for " << Orig->getName() 693 << "\n"); 694 return New; 695 }; 696 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest); 697 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest); 698 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc); 699 700 // Link up these blocks with branches. 701 if (!HoistCommonSucc->getTerminator()) { 702 // The new common successor we've generated will branch to whatever that 703 // hoist target branched to. 704 BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor(); 705 assert(TargetSucc && "Expected hoist target to have a single successor"); 706 HoistCommonSucc->moveBefore(TargetSucc); 707 BranchInst::Create(TargetSucc, HoistCommonSucc); 708 } 709 if (!HoistTrueDest->getTerminator()) { 710 HoistTrueDest->moveBefore(HoistCommonSucc); 711 BranchInst::Create(HoistCommonSucc, HoistTrueDest); 712 } 713 if (!HoistFalseDest->getTerminator()) { 714 HoistFalseDest->moveBefore(HoistCommonSucc); 715 BranchInst::Create(HoistCommonSucc, HoistFalseDest); 716 } 717 718 // If BI is being cloned to what was originally the preheader then 719 // HoistCommonSucc will now be the new preheader. 720 if (HoistTarget == InitialPreheader) { 721 // Phis in the loop header now need to use the new preheader. 722 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc); 723 if (MSSAU) 724 MSSAU->wireOldPredecessorsToNewImmediatePredecessor( 725 HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget}); 726 // The new preheader dominates the loop header. 727 DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc); 728 DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader()); 729 DT->changeImmediateDominator(HeaderNode, PreheaderNode); 730 // The preheader hoist destination is now the new preheader, with the 731 // exception of the hoist destination of this branch. 732 for (auto &Pair : HoistDestinationMap) 733 if (Pair.second == InitialPreheader && Pair.first != BI->getParent()) 734 Pair.second = HoistCommonSucc; 735 } 736 737 // Now finally clone BI. 738 ReplaceInstWithInst( 739 HoistTarget->getTerminator(), 740 BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition())); 741 ++NumClonedBranches; 742 743 assert(CurLoop->getLoopPreheader() && 744 "Hoisting blocks should not have destroyed preheader"); 745 return HoistDestinationMap[BB]; 746 } 747 }; 748 } // namespace 749 750 751 /// Return true if we know how to rewrite all uses of the given alloca after 752 /// hoisting it out of the loop. The main concerns are a) potential captures 753 /// and b) invariant.start markers which don't capture, but are no longer 754 /// valid w/o a corresponding invariant.end. 755 static bool canRewriteUsesOfAlloca(AllocaInst &AI) { 756 // TODO: This looks a lot like capture tracking, but we need to remove any 757 // invariant starts if we extend the lifetime of the alloca by hoisting it. 758 // We should probably refactor capture tracking into a form which allows us 759 // to reuse the relevant bits and remove the duplicated logic here. 760 761 SmallVector<Use *, 16> Worklist; 762 for (Use &U : AI.uses()) 763 Worklist.push_back(&U); 764 765 unsigned NumUsesExplored = 0; 766 while (!Worklist.empty()) { 767 Use *U = Worklist.pop_back_val(); 768 Instruction *I = cast<Instruction>(U->getUser()); 769 NumUsesExplored++; 770 if (NumUsesExplored > DefaultMaxUsesToExplore) 771 return false; 772 // Non capturing, terminating uses 773 if (isa<LoadInst>(I) || 774 (isa<StoreInst>(I) && U->getOperandNo() == 1)) 775 continue; 776 // Non capturing, non-terminating 777 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I)) 778 return false; 779 for (Use &U : I->uses()) 780 Worklist.push_back(&U); 781 } 782 return true; 783 } 784 785 /// Walk the specified region of the CFG (defined by all blocks dominated by 786 /// the specified block, and that are in the current loop) in depth first 787 /// order w.r.t the DominatorTree. This allows us to visit definitions before 788 /// uses, allowing us to hoist a loop body in one pass without iteration. 789 /// 790 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 791 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 792 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 793 ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo, 794 SinkAndHoistLICMFlags &Flags, 795 OptimizationRemarkEmitter *ORE) { 796 // Verify inputs. 797 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 798 CurLoop != nullptr && SafetyInfo != nullptr && 799 "Unexpected input to hoistRegion."); 800 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && 801 "Either AliasSetTracker or MemorySSA should be initialized."); 802 803 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU); 804 805 // Keep track of instructions that have been hoisted, as they may need to be 806 // re-hoisted if they end up not dominating all of their uses. 807 SmallVector<Instruction *, 16> HoistedInstructions; 808 809 // For PHI hoisting to work we need to hoist blocks before their successors. 810 // We can do this by iterating through the blocks in the loop in reverse 811 // post-order. 812 LoopBlocksRPO Worklist(CurLoop); 813 Worklist.perform(LI); 814 bool Changed = false; 815 for (BasicBlock *BB : Worklist) { 816 // Only need to process the contents of this block if it is not part of a 817 // subloop (which would already have been processed). 818 if (inSubLoop(BB, CurLoop, LI)) 819 continue; 820 821 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { 822 Instruction &I = *II++; 823 // Try constant folding this instruction. If all the operands are 824 // constants, it is technically hoistable, but it would be better to 825 // just fold it. 826 if (Constant *C = ConstantFoldInstruction( 827 &I, I.getModule()->getDataLayout(), TLI)) { 828 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C 829 << '\n'); 830 if (CurAST) 831 CurAST->copyValue(&I, C); 832 // FIXME MSSA: Such replacements may make accesses unoptimized (D51960). 833 I.replaceAllUsesWith(C); 834 if (isInstructionTriviallyDead(&I, TLI)) 835 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 836 Changed = true; 837 continue; 838 } 839 840 // Try hoisting the instruction out to the preheader. We can only do 841 // this if all of the operands of the instruction are loop invariant and 842 // if it is safe to hoist the instruction. 843 // TODO: It may be safe to hoist if we are hoisting to a conditional block 844 // and we have accurately duplicated the control flow from the loop header 845 // to that block. 846 if (CurLoop->hasLoopInvariantOperands(&I) && 847 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags, 848 ORE) && 849 isSafeToExecuteUnconditionally( 850 I, DT, CurLoop, SafetyInfo, ORE, 851 CurLoop->getLoopPreheader()->getTerminator())) { 852 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 853 MSSAU, SE, ORE); 854 HoistedInstructions.push_back(&I); 855 Changed = true; 856 continue; 857 } 858 859 // Attempt to remove floating point division out of the loop by 860 // converting it to a reciprocal multiplication. 861 if (I.getOpcode() == Instruction::FDiv && 862 CurLoop->isLoopInvariant(I.getOperand(1)) && 863 I.hasAllowReciprocal()) { 864 auto Divisor = I.getOperand(1); 865 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0); 866 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor); 867 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags()); 868 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent()); 869 ReciprocalDivisor->insertBefore(&I); 870 871 auto Product = 872 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor); 873 Product->setFastMathFlags(I.getFastMathFlags()); 874 SafetyInfo->insertInstructionTo(Product, I.getParent()); 875 Product->insertAfter(&I); 876 I.replaceAllUsesWith(Product); 877 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); 878 879 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), 880 SafetyInfo, MSSAU, SE, ORE); 881 HoistedInstructions.push_back(ReciprocalDivisor); 882 Changed = true; 883 continue; 884 } 885 886 auto IsInvariantStart = [&](Instruction &I) { 887 using namespace PatternMatch; 888 return I.use_empty() && 889 match(&I, m_Intrinsic<Intrinsic::invariant_start>()); 890 }; 891 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) { 892 return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && 893 SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop); 894 }; 895 if ((IsInvariantStart(I) || isGuard(&I)) && 896 CurLoop->hasLoopInvariantOperands(&I) && 897 MustExecuteWithoutWritesBefore(I)) { 898 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 899 MSSAU, SE, ORE); 900 HoistedInstructions.push_back(&I); 901 Changed = true; 902 continue; 903 } 904 905 if (isa<AllocaInst>(&I) && 906 SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && 907 canRewriteUsesOfAlloca(cast<AllocaInst>(I))) { 908 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 909 MSSAU, SE, ORE); 910 HoistedInstructions.push_back(&I); 911 Changed = true; 912 continue; 913 } 914 915 if (PHINode *PN = dyn_cast<PHINode>(&I)) { 916 if (CFH.canHoistPHI(PN)) { 917 // Redirect incoming blocks first to ensure that we create hoisted 918 // versions of those blocks before we hoist the phi. 919 for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i) 920 PN->setIncomingBlock( 921 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i))); 922 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, 923 MSSAU, SE, ORE); 924 assert(DT->dominates(PN, BB) && "Conditional PHIs not expected"); 925 Changed = true; 926 continue; 927 } 928 } 929 930 // Remember possibly hoistable branches so we can actually hoist them 931 // later if needed. 932 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 933 CFH.registerPossiblyHoistableBranch(BI); 934 } 935 } 936 937 // If we hoisted instructions to a conditional block they may not dominate 938 // their uses that weren't hoisted (such as phis where some operands are not 939 // loop invariant). If so make them unconditional by moving them to their 940 // immediate dominator. We iterate through the instructions in reverse order 941 // which ensures that when we rehoist an instruction we rehoist its operands, 942 // and also keep track of where in the block we are rehoisting to to make sure 943 // that we rehoist instructions before the instructions that use them. 944 Instruction *HoistPoint = nullptr; 945 if (ControlFlowHoisting) { 946 for (Instruction *I : reverse(HoistedInstructions)) { 947 if (!llvm::all_of(I->uses(), 948 [&](Use &U) { return DT->dominates(I, U); })) { 949 BasicBlock *Dominator = 950 DT->getNode(I->getParent())->getIDom()->getBlock(); 951 if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) { 952 if (HoistPoint) 953 assert(DT->dominates(Dominator, HoistPoint->getParent()) && 954 "New hoist point expected to dominate old hoist point"); 955 HoistPoint = Dominator->getTerminator(); 956 } 957 LLVM_DEBUG(dbgs() << "LICM rehoisting to " 958 << HoistPoint->getParent()->getName() 959 << ": " << *I << "\n"); 960 moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE); 961 HoistPoint = I; 962 Changed = true; 963 } 964 } 965 } 966 if (MSSAU && VerifyMemorySSA) 967 MSSAU->getMemorySSA()->verifyMemorySSA(); 968 969 // Now that we've finished hoisting make sure that LI and DT are still 970 // valid. 971 #ifdef EXPENSIVE_CHECKS 972 if (Changed) { 973 assert(DT->verify(DominatorTree::VerificationLevel::Fast) && 974 "Dominator tree verification failed"); 975 LI->verify(*DT); 976 } 977 #endif 978 979 return Changed; 980 } 981 982 // Return true if LI is invariant within scope of the loop. LI is invariant if 983 // CurLoop is dominated by an invariant.start representing the same memory 984 // location and size as the memory location LI loads from, and also the 985 // invariant.start has no uses. 986 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, 987 Loop *CurLoop) { 988 Value *Addr = LI->getOperand(0); 989 const DataLayout &DL = LI->getModule()->getDataLayout(); 990 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType()); 991 992 // if the type is i8 addrspace(x)*, we know this is the type of 993 // llvm.invariant.start operand 994 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()), 995 LI->getPointerAddressSpace()); 996 unsigned BitcastsVisited = 0; 997 // Look through bitcasts until we reach the i8* type (this is invariant.start 998 // operand type). 999 while (Addr->getType() != PtrInt8Ty) { 1000 auto *BC = dyn_cast<BitCastInst>(Addr); 1001 // Avoid traversing high number of bitcast uses. 1002 if (++BitcastsVisited > MaxNumUsesTraversed || !BC) 1003 return false; 1004 Addr = BC->getOperand(0); 1005 } 1006 1007 unsigned UsesVisited = 0; 1008 // Traverse all uses of the load operand value, to see if invariant.start is 1009 // one of the uses, and whether it dominates the load instruction. 1010 for (auto *U : Addr->users()) { 1011 // Avoid traversing for Load operand with high number of users. 1012 if (++UsesVisited > MaxNumUsesTraversed) 1013 return false; 1014 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 1015 // If there are escaping uses of invariant.start instruction, the load maybe 1016 // non-invariant. 1017 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start || 1018 !II->use_empty()) 1019 continue; 1020 unsigned InvariantSizeInBits = 1021 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8; 1022 // Confirm the invariant.start location size contains the load operand size 1023 // in bits. Also, the invariant.start should dominate the load, and we 1024 // should not hoist the load out of a loop that contains this dominating 1025 // invariant.start. 1026 if (LocSizeInBits <= InvariantSizeInBits && 1027 DT->properlyDominates(II->getParent(), CurLoop->getHeader())) 1028 return true; 1029 } 1030 1031 return false; 1032 } 1033 1034 namespace { 1035 /// Return true if-and-only-if we know how to (mechanically) both hoist and 1036 /// sink a given instruction out of a loop. Does not address legality 1037 /// concerns such as aliasing or speculation safety. 1038 bool isHoistableAndSinkableInst(Instruction &I) { 1039 // Only these instructions are hoistable/sinkable. 1040 return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 1041 isa<FenceInst>(I) || isa<CastInst>(I) || 1042 isa<UnaryOperator>(I) || isa<BinaryOperator>(I) || 1043 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) || 1044 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 1045 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) || 1046 isa<InsertValueInst>(I)); 1047 } 1048 /// Return true if all of the alias sets within this AST are known not to 1049 /// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop. 1050 bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU, 1051 const Loop *L) { 1052 if (CurAST) { 1053 for (AliasSet &AS : *CurAST) { 1054 if (!AS.isForwardingAliasSet() && AS.isMod()) { 1055 return false; 1056 } 1057 } 1058 return true; 1059 } else { /*MSSAU*/ 1060 for (auto *BB : L->getBlocks()) 1061 if (MSSAU->getMemorySSA()->getBlockDefs(BB)) 1062 return false; 1063 return true; 1064 } 1065 } 1066 1067 /// Return true if I is the only Instruction with a MemoryAccess in L. 1068 bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, 1069 const MemorySSAUpdater *MSSAU) { 1070 for (auto *BB : L->getBlocks()) 1071 if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) { 1072 int NotAPhi = 0; 1073 for (const auto &Acc : *Accs) { 1074 if (isa<MemoryPhi>(&Acc)) 1075 continue; 1076 const auto *MUD = cast<MemoryUseOrDef>(&Acc); 1077 if (MUD->getMemoryInst() != I || NotAPhi++ == 1) 1078 return false; 1079 } 1080 } 1081 return true; 1082 } 1083 } 1084 1085 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, 1086 Loop *CurLoop, AliasSetTracker *CurAST, 1087 MemorySSAUpdater *MSSAU, 1088 bool TargetExecutesOncePerLoop, 1089 SinkAndHoistLICMFlags *Flags, 1090 OptimizationRemarkEmitter *ORE) { 1091 // If we don't understand the instruction, bail early. 1092 if (!isHoistableAndSinkableInst(I)) 1093 return false; 1094 1095 MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr; 1096 if (MSSA) 1097 assert(Flags != nullptr && "Flags cannot be null."); 1098 1099 // Loads have extra constraints we have to verify before we can hoist them. 1100 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 1101 if (!LI->isUnordered()) 1102 return false; // Don't sink/hoist volatile or ordered atomic loads! 1103 1104 // Loads from constant memory are always safe to move, even if they end up 1105 // in the same alias set as something that ends up being modified. 1106 if (AA->pointsToConstantMemory(LI->getOperand(0))) 1107 return true; 1108 if (LI->hasMetadata(LLVMContext::MD_invariant_load)) 1109 return true; 1110 1111 if (LI->isAtomic() && !TargetExecutesOncePerLoop) 1112 return false; // Don't risk duplicating unordered loads 1113 1114 // This checks for an invariant.start dominating the load. 1115 if (isLoadInvariantInLoop(LI, DT, CurLoop)) 1116 return true; 1117 1118 bool Invalidated; 1119 if (CurAST) 1120 Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST, 1121 CurLoop, AA); 1122 else 1123 Invalidated = pointerInvalidatedByLoopWithMSSA( 1124 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags); 1125 // Check loop-invariant address because this may also be a sinkable load 1126 // whose address is not necessarily loop-invariant. 1127 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) 1128 ORE->emit([&]() { 1129 return OptimizationRemarkMissed( 1130 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI) 1131 << "failed to move load with loop-invariant address " 1132 "because the loop may invalidate its value"; 1133 }); 1134 1135 return !Invalidated; 1136 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1137 // Don't sink or hoist dbg info; it's legal, but not useful. 1138 if (isa<DbgInfoIntrinsic>(I)) 1139 return false; 1140 1141 // Don't sink calls which can throw. 1142 if (CI->mayThrow()) 1143 return false; 1144 1145 using namespace PatternMatch; 1146 if (match(CI, m_Intrinsic<Intrinsic::assume>())) 1147 // Assumes don't actually alias anything or throw 1148 return true; 1149 1150 if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>())) 1151 // Widenable conditions don't actually alias anything or throw 1152 return true; 1153 1154 // Handle simple cases by querying alias analysis. 1155 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 1156 if (Behavior == FMRB_DoesNotAccessMemory) 1157 return true; 1158 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 1159 // A readonly argmemonly function only reads from memory pointed to by 1160 // it's arguments with arbitrary offsets. If we can prove there are no 1161 // writes to this memory in the loop, we can hoist or sink. 1162 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 1163 // TODO: expand to writeable arguments 1164 for (Value *Op : CI->arg_operands()) 1165 if (Op->getType()->isPointerTy()) { 1166 bool Invalidated; 1167 if (CurAST) 1168 Invalidated = pointerInvalidatedByLoop( 1169 MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()), 1170 CurAST, CurLoop, AA); 1171 else 1172 Invalidated = pointerInvalidatedByLoopWithMSSA( 1173 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, 1174 *Flags); 1175 if (Invalidated) 1176 return false; 1177 } 1178 return true; 1179 } 1180 1181 // If this call only reads from memory and there are no writes to memory 1182 // in the loop, we can hoist or sink the call as appropriate. 1183 if (isReadOnly(CurAST, MSSAU, CurLoop)) 1184 return true; 1185 } 1186 1187 // FIXME: This should use mod/ref information to see if we can hoist or 1188 // sink the call. 1189 1190 return false; 1191 } else if (auto *FI = dyn_cast<FenceInst>(&I)) { 1192 // Fences alias (most) everything to provide ordering. For the moment, 1193 // just give up if there are any other memory operations in the loop. 1194 if (CurAST) { 1195 auto Begin = CurAST->begin(); 1196 assert(Begin != CurAST->end() && "must contain FI"); 1197 if (std::next(Begin) != CurAST->end()) 1198 // constant memory for instance, TODO: handle better 1199 return false; 1200 auto *UniqueI = Begin->getUniqueInstruction(); 1201 if (!UniqueI) 1202 // other memory op, give up 1203 return false; 1204 (void)FI; // suppress unused variable warning 1205 assert(UniqueI == FI && "AS must contain FI"); 1206 return true; 1207 } else // MSSAU 1208 return isOnlyMemoryAccess(FI, CurLoop, MSSAU); 1209 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 1210 if (!SI->isUnordered()) 1211 return false; // Don't sink/hoist volatile or ordered atomic store! 1212 1213 // We can only hoist a store that we can prove writes a value which is not 1214 // read or overwritten within the loop. For those cases, we fallback to 1215 // load store promotion instead. TODO: We can extend this to cases where 1216 // there is exactly one write to the location and that write dominates an 1217 // arbitrary number of reads in the loop. 1218 if (CurAST) { 1219 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI)); 1220 1221 if (AS.isRef() || !AS.isMustAlias()) 1222 // Quick exit test, handled by the full path below as well. 1223 return false; 1224 auto *UniqueI = AS.getUniqueInstruction(); 1225 if (!UniqueI) 1226 // other memory op, give up 1227 return false; 1228 assert(UniqueI == SI && "AS must contain SI"); 1229 return true; 1230 } else { // MSSAU 1231 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU)) 1232 return true; 1233 // If there are more accesses than the Promotion cap, give up, we're not 1234 // walking a list that long. 1235 if (Flags->NoOfMemAccTooLarge) 1236 return false; 1237 // Check store only if there's still "quota" to check clobber. 1238 if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap) 1239 return false; 1240 // If there are interfering Uses (i.e. their defining access is in the 1241 // loop), or ordered loads (stored as Defs!), don't move this store. 1242 // Could do better here, but this is conservatively correct. 1243 // TODO: Cache set of Uses on the first walk in runOnLoop, update when 1244 // moving accesses. Can also extend to dominating uses. 1245 auto *SIMD = MSSA->getMemoryAccess(SI); 1246 for (auto *BB : CurLoop->getBlocks()) 1247 if (auto *Accesses = MSSA->getBlockAccesses(BB)) { 1248 for (const auto &MA : *Accesses) 1249 if (const auto *MU = dyn_cast<MemoryUse>(&MA)) { 1250 auto *MD = MU->getDefiningAccess(); 1251 if (!MSSA->isLiveOnEntryDef(MD) && 1252 CurLoop->contains(MD->getBlock())) 1253 return false; 1254 // Disable hoisting past potentially interfering loads. Optimized 1255 // Uses may point to an access outside the loop, as getClobbering 1256 // checks the previous iteration when walking the backedge. 1257 // FIXME: More precise: no Uses that alias SI. 1258 if (!Flags->IsSink && !MSSA->dominates(SIMD, MU)) 1259 return false; 1260 } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) { 1261 if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) { 1262 (void)LI; // Silence warning. 1263 assert(!LI->isUnordered() && "Expected unordered load"); 1264 return false; 1265 } 1266 // Any call, while it may not be clobbering SI, it may be a use. 1267 if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) { 1268 // Check if the call may read from the memory locattion written 1269 // to by SI. Check CI's attributes and arguments; the number of 1270 // such checks performed is limited above by NoOfMemAccTooLarge. 1271 ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI)); 1272 if (isModOrRefSet(MRI)) 1273 return false; 1274 } 1275 } 1276 } 1277 1278 auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI); 1279 Flags->LicmMssaOptCounter++; 1280 // If there are no clobbering Defs in the loop, store is safe to hoist. 1281 return MSSA->isLiveOnEntryDef(Source) || 1282 !CurLoop->contains(Source->getBlock()); 1283 } 1284 } 1285 1286 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing"); 1287 1288 // We've established mechanical ability and aliasing, it's up to the caller 1289 // to check fault safety 1290 return true; 1291 } 1292 1293 /// Returns true if a PHINode is a trivially replaceable with an 1294 /// Instruction. 1295 /// This is true when all incoming values are that instruction. 1296 /// This pattern occurs most often with LCSSA PHI nodes. 1297 /// 1298 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) { 1299 for (const Value *IncValue : PN.incoming_values()) 1300 if (IncValue != &I) 1301 return false; 1302 1303 return true; 1304 } 1305 1306 /// Return true if the instruction is free in the loop. 1307 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, 1308 const TargetTransformInfo *TTI) { 1309 1310 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) { 1311 if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free) 1312 return false; 1313 // For a GEP, we cannot simply use getUserCost because currently it 1314 // optimistically assume that a GEP will fold into addressing mode 1315 // regardless of its users. 1316 const BasicBlock *BB = GEP->getParent(); 1317 for (const User *U : GEP->users()) { 1318 const Instruction *UI = cast<Instruction>(U); 1319 if (CurLoop->contains(UI) && 1320 (BB != UI->getParent() || 1321 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI)))) 1322 return false; 1323 } 1324 return true; 1325 } else 1326 return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free; 1327 } 1328 1329 /// Return true if the only users of this instruction are outside of 1330 /// the loop. If this is true, we can sink the instruction to the exit 1331 /// blocks of the loop. 1332 /// 1333 /// We also return true if the instruction could be folded away in lowering. 1334 /// (e.g., a GEP can be folded into a load as an addressing mode in the loop). 1335 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, 1336 const LoopSafetyInfo *SafetyInfo, 1337 TargetTransformInfo *TTI, bool &FreeInLoop) { 1338 const auto &BlockColors = SafetyInfo->getBlockColors(); 1339 bool IsFree = isFreeInLoop(I, CurLoop, TTI); 1340 for (const User *U : I.users()) { 1341 const Instruction *UI = cast<Instruction>(U); 1342 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 1343 const BasicBlock *BB = PN->getParent(); 1344 // We cannot sink uses in catchswitches. 1345 if (isa<CatchSwitchInst>(BB->getTerminator())) 1346 return false; 1347 1348 // We need to sink a callsite to a unique funclet. Avoid sinking if the 1349 // phi use is too muddled. 1350 if (isa<CallInst>(I)) 1351 if (!BlockColors.empty() && 1352 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 1353 return false; 1354 } 1355 1356 if (CurLoop->contains(UI)) { 1357 if (IsFree) { 1358 FreeInLoop = true; 1359 continue; 1360 } 1361 return false; 1362 } 1363 } 1364 return true; 1365 } 1366 1367 static Instruction *CloneInstructionInExitBlock( 1368 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, 1369 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) { 1370 Instruction *New; 1371 if (auto *CI = dyn_cast<CallInst>(&I)) { 1372 const auto &BlockColors = SafetyInfo->getBlockColors(); 1373 1374 // Sinking call-sites need to be handled differently from other 1375 // instructions. The cloned call-site needs a funclet bundle operand 1376 // appropriate for its location in the CFG. 1377 SmallVector<OperandBundleDef, 1> OpBundles; 1378 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 1379 BundleIdx != BundleEnd; ++BundleIdx) { 1380 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 1381 if (Bundle.getTagID() == LLVMContext::OB_funclet) 1382 continue; 1383 1384 OpBundles.emplace_back(Bundle); 1385 } 1386 1387 if (!BlockColors.empty()) { 1388 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 1389 assert(CV.size() == 1 && "non-unique color for exit block!"); 1390 BasicBlock *BBColor = CV.front(); 1391 Instruction *EHPad = BBColor->getFirstNonPHI(); 1392 if (EHPad->isEHPad()) 1393 OpBundles.emplace_back("funclet", EHPad); 1394 } 1395 1396 New = CallInst::Create(CI, OpBundles); 1397 } else { 1398 New = I.clone(); 1399 } 1400 1401 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 1402 if (!I.getName().empty()) 1403 New->setName(I.getName() + ".le"); 1404 1405 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) { 1406 // Create a new MemoryAccess and let MemorySSA set its defining access. 1407 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1408 New, nullptr, New->getParent(), MemorySSA::Beginning); 1409 if (NewMemAcc) { 1410 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc)) 1411 MSSAU->insertDef(MemDef, /*RenameUses=*/true); 1412 else { 1413 auto *MemUse = cast<MemoryUse>(NewMemAcc); 1414 MSSAU->insertUse(MemUse, /*RenameUses=*/true); 1415 } 1416 } 1417 } 1418 1419 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 1420 // particularly cheap because we can rip off the PHI node that we're 1421 // replacing for the number and blocks of the predecessors. 1422 // OPT: If this shows up in a profile, we can instead finish sinking all 1423 // invariant instructions, and then walk their operands to re-establish 1424 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 1425 // sinking bottom-up. 1426 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 1427 ++OI) 1428 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 1429 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 1430 if (!OLoop->contains(&PN)) { 1431 PHINode *OpPN = 1432 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 1433 OInst->getName() + ".lcssa", &ExitBlock.front()); 1434 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 1435 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 1436 *OI = OpPN; 1437 } 1438 return New; 1439 } 1440 1441 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, 1442 AliasSetTracker *AST, MemorySSAUpdater *MSSAU) { 1443 if (AST) 1444 AST->deleteValue(&I); 1445 if (MSSAU) 1446 MSSAU->removeMemoryAccess(&I); 1447 SafetyInfo.removeInstruction(&I); 1448 I.eraseFromParent(); 1449 } 1450 1451 static void moveInstructionBefore(Instruction &I, Instruction &Dest, 1452 ICFLoopSafetyInfo &SafetyInfo, 1453 MemorySSAUpdater *MSSAU, 1454 ScalarEvolution *SE) { 1455 SafetyInfo.removeInstruction(&I); 1456 SafetyInfo.insertInstructionTo(&I, Dest.getParent()); 1457 I.moveBefore(&Dest); 1458 if (MSSAU) 1459 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>( 1460 MSSAU->getMemorySSA()->getMemoryAccess(&I))) 1461 MSSAU->moveToPlace(OldMemAcc, Dest.getParent(), 1462 MemorySSA::BeforeTerminator); 1463 if (SE) 1464 SE->forgetValue(&I); 1465 } 1466 1467 static Instruction *sinkThroughTriviallyReplaceablePHI( 1468 PHINode *TPN, Instruction *I, LoopInfo *LI, 1469 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies, 1470 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, 1471 MemorySSAUpdater *MSSAU) { 1472 assert(isTriviallyReplaceablePHI(*TPN, *I) && 1473 "Expect only trivially replaceable PHI"); 1474 BasicBlock *ExitBlock = TPN->getParent(); 1475 Instruction *New; 1476 auto It = SunkCopies.find(ExitBlock); 1477 if (It != SunkCopies.end()) 1478 New = It->second; 1479 else 1480 New = SunkCopies[ExitBlock] = CloneInstructionInExitBlock( 1481 *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU); 1482 return New; 1483 } 1484 1485 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) { 1486 BasicBlock *BB = PN->getParent(); 1487 if (!BB->canSplitPredecessors()) 1488 return false; 1489 // It's not impossible to split EHPad blocks, but if BlockColors already exist 1490 // it require updating BlockColors for all offspring blocks accordingly. By 1491 // skipping such corner case, we can make updating BlockColors after splitting 1492 // predecessor fairly simple. 1493 if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad()) 1494 return false; 1495 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 1496 BasicBlock *BBPred = *PI; 1497 if (isa<IndirectBrInst>(BBPred->getTerminator())) 1498 return false; 1499 } 1500 return true; 1501 } 1502 1503 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, 1504 LoopInfo *LI, const Loop *CurLoop, 1505 LoopSafetyInfo *SafetyInfo, 1506 MemorySSAUpdater *MSSAU) { 1507 #ifndef NDEBUG 1508 SmallVector<BasicBlock *, 32> ExitBlocks; 1509 CurLoop->getUniqueExitBlocks(ExitBlocks); 1510 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 1511 ExitBlocks.end()); 1512 #endif 1513 BasicBlock *ExitBB = PN->getParent(); 1514 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block."); 1515 1516 // Split predecessors of the loop exit to make instructions in the loop are 1517 // exposed to exit blocks through trivially replaceable PHIs while keeping the 1518 // loop in the canonical form where each predecessor of each exit block should 1519 // be contained within the loop. For example, this will convert the loop below 1520 // from 1521 // 1522 // LB1: 1523 // %v1 = 1524 // br %LE, %LB2 1525 // LB2: 1526 // %v2 = 1527 // br %LE, %LB1 1528 // LE: 1529 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable 1530 // 1531 // to 1532 // 1533 // LB1: 1534 // %v1 = 1535 // br %LE.split, %LB2 1536 // LB2: 1537 // %v2 = 1538 // br %LE.split2, %LB1 1539 // LE.split: 1540 // %p1 = phi [%v1, %LB1] <-- trivially replaceable 1541 // br %LE 1542 // LE.split2: 1543 // %p2 = phi [%v2, %LB2] <-- trivially replaceable 1544 // br %LE 1545 // LE: 1546 // %p = phi [%p1, %LE.split], [%p2, %LE.split2] 1547 // 1548 const auto &BlockColors = SafetyInfo->getBlockColors(); 1549 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB)); 1550 while (!PredBBs.empty()) { 1551 BasicBlock *PredBB = *PredBBs.begin(); 1552 assert(CurLoop->contains(PredBB) && 1553 "Expect all predecessors are in the loop"); 1554 if (PN->getBasicBlockIndex(PredBB) >= 0) { 1555 BasicBlock *NewPred = SplitBlockPredecessors( 1556 ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true); 1557 // Since we do not allow splitting EH-block with BlockColors in 1558 // canSplitPredecessors(), we can simply assign predecessor's color to 1559 // the new block. 1560 if (!BlockColors.empty()) 1561 // Grab a reference to the ColorVector to be inserted before getting the 1562 // reference to the vector we are copying because inserting the new 1563 // element in BlockColors might cause the map to be reallocated. 1564 SafetyInfo->copyColors(NewPred, PredBB); 1565 } 1566 PredBBs.remove(PredBB); 1567 } 1568 } 1569 1570 /// When an instruction is found to only be used outside of the loop, this 1571 /// function moves it to the exit blocks and patches up SSA form as needed. 1572 /// This method is guaranteed to remove the original instruction from its 1573 /// position, and may either delete it or move it to outside of the loop. 1574 /// 1575 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, 1576 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, 1577 MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) { 1578 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 1579 ORE->emit([&]() { 1580 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I) 1581 << "sinking " << ore::NV("Inst", &I); 1582 }); 1583 bool Changed = false; 1584 if (isa<LoadInst>(I)) 1585 ++NumMovedLoads; 1586 else if (isa<CallInst>(I)) 1587 ++NumMovedCalls; 1588 ++NumSunk; 1589 1590 // Iterate over users to be ready for actual sinking. Replace users via 1591 // unreachable blocks with undef and make all user PHIs trivially replaceable. 1592 SmallPtrSet<Instruction *, 8> VisitedUsers; 1593 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) { 1594 auto *User = cast<Instruction>(*UI); 1595 Use &U = UI.getUse(); 1596 ++UI; 1597 1598 if (VisitedUsers.count(User) || CurLoop->contains(User)) 1599 continue; 1600 1601 if (!DT->isReachableFromEntry(User->getParent())) { 1602 U = UndefValue::get(I.getType()); 1603 Changed = true; 1604 continue; 1605 } 1606 1607 // The user must be a PHI node. 1608 PHINode *PN = cast<PHINode>(User); 1609 1610 // Surprisingly, instructions can be used outside of loops without any 1611 // exits. This can only happen in PHI nodes if the incoming block is 1612 // unreachable. 1613 BasicBlock *BB = PN->getIncomingBlock(U); 1614 if (!DT->isReachableFromEntry(BB)) { 1615 U = UndefValue::get(I.getType()); 1616 Changed = true; 1617 continue; 1618 } 1619 1620 VisitedUsers.insert(PN); 1621 if (isTriviallyReplaceablePHI(*PN, I)) 1622 continue; 1623 1624 if (!canSplitPredecessors(PN, SafetyInfo)) 1625 return Changed; 1626 1627 // Split predecessors of the PHI so that we can make users trivially 1628 // replaceable. 1629 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU); 1630 1631 // Should rebuild the iterators, as they may be invalidated by 1632 // splitPredecessorsOfLoopExit(). 1633 UI = I.user_begin(); 1634 UE = I.user_end(); 1635 } 1636 1637 if (VisitedUsers.empty()) 1638 return Changed; 1639 1640 #ifndef NDEBUG 1641 SmallVector<BasicBlock *, 32> ExitBlocks; 1642 CurLoop->getUniqueExitBlocks(ExitBlocks); 1643 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 1644 ExitBlocks.end()); 1645 #endif 1646 1647 // Clones of this instruction. Don't create more than one per exit block! 1648 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 1649 1650 // If this instruction is only used outside of the loop, then all users are 1651 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 1652 // the instruction. 1653 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end()); 1654 for (auto *UI : Users) { 1655 auto *User = cast<Instruction>(UI); 1656 1657 if (CurLoop->contains(User)) 1658 continue; 1659 1660 PHINode *PN = cast<PHINode>(User); 1661 assert(ExitBlockSet.count(PN->getParent()) && 1662 "The LCSSA PHI is not in an exit block!"); 1663 // The PHI must be trivially replaceable. 1664 Instruction *New = sinkThroughTriviallyReplaceablePHI( 1665 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU); 1666 PN->replaceAllUsesWith(New); 1667 eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr); 1668 Changed = true; 1669 } 1670 return Changed; 1671 } 1672 1673 /// When an instruction is found to only use loop invariant operands that 1674 /// is safe to hoist, this instruction is called to do the dirty work. 1675 /// 1676 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 1677 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, 1678 MemorySSAUpdater *MSSAU, ScalarEvolution *SE, 1679 OptimizationRemarkEmitter *ORE) { 1680 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << I 1681 << "\n"); 1682 ORE->emit([&]() { 1683 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting " 1684 << ore::NV("Inst", &I); 1685 }); 1686 1687 // Metadata can be dependent on conditions we are hoisting above. 1688 // Conservatively strip all metadata on the instruction unless we were 1689 // guaranteed to execute I if we entered the loop, in which case the metadata 1690 // is valid in the loop preheader. 1691 if (I.hasMetadataOtherThanDebugLoc() && 1692 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 1693 // time in isGuaranteedToExecute if we don't actually have anything to 1694 // drop. It is a compile time optimization, not required for correctness. 1695 !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop)) 1696 I.dropUnknownNonDebugMetadata(); 1697 1698 if (isa<PHINode>(I)) 1699 // Move the new node to the end of the phi list in the destination block. 1700 moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE); 1701 else 1702 // Move the new node to the destination block, before its terminator. 1703 moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE); 1704 1705 // Apply line 0 debug locations when we are moving instructions to different 1706 // basic blocks because we want to avoid jumpy line tables. 1707 if (const DebugLoc &DL = I.getDebugLoc()) 1708 I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 1709 1710 if (isa<LoadInst>(I)) 1711 ++NumMovedLoads; 1712 else if (isa<CallInst>(I)) 1713 ++NumMovedCalls; 1714 ++NumHoisted; 1715 } 1716 1717 /// Only sink or hoist an instruction if it is not a trapping instruction, 1718 /// or if the instruction is known not to trap when moved to the preheader. 1719 /// or if it is a trapping instruction and is guaranteed to execute. 1720 static bool isSafeToExecuteUnconditionally(Instruction &Inst, 1721 const DominatorTree *DT, 1722 const Loop *CurLoop, 1723 const LoopSafetyInfo *SafetyInfo, 1724 OptimizationRemarkEmitter *ORE, 1725 const Instruction *CtxI) { 1726 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) 1727 return true; 1728 1729 bool GuaranteedToExecute = 1730 SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop); 1731 1732 if (!GuaranteedToExecute) { 1733 auto *LI = dyn_cast<LoadInst>(&Inst); 1734 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) 1735 ORE->emit([&]() { 1736 return OptimizationRemarkMissed( 1737 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI) 1738 << "failed to hoist load with loop-invariant address " 1739 "because load is conditionally executed"; 1740 }); 1741 } 1742 1743 return GuaranteedToExecute; 1744 } 1745 1746 namespace { 1747 class LoopPromoter : public LoadAndStorePromoter { 1748 Value *SomePtr; // Designated pointer to store to. 1749 const SmallSetVector<Value *, 8> &PointerMustAliases; 1750 SmallVectorImpl<BasicBlock *> &LoopExitBlocks; 1751 SmallVectorImpl<Instruction *> &LoopInsertPts; 1752 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts; 1753 PredIteratorCache &PredCache; 1754 AliasSetTracker &AST; 1755 MemorySSAUpdater *MSSAU; 1756 LoopInfo &LI; 1757 DebugLoc DL; 1758 int Alignment; 1759 bool UnorderedAtomic; 1760 AAMDNodes AATags; 1761 ICFLoopSafetyInfo &SafetyInfo; 1762 1763 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 1764 if (Instruction *I = dyn_cast<Instruction>(V)) 1765 if (Loop *L = LI.getLoopFor(I->getParent())) 1766 if (!L->contains(BB)) { 1767 // We need to create an LCSSA PHI node for the incoming value and 1768 // store that. 1769 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), 1770 I->getName() + ".lcssa", &BB->front()); 1771 for (BasicBlock *Pred : PredCache.get(BB)) 1772 PN->addIncoming(I, Pred); 1773 return PN; 1774 } 1775 return V; 1776 } 1777 1778 public: 1779 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, 1780 const SmallSetVector<Value *, 8> &PMA, 1781 SmallVectorImpl<BasicBlock *> &LEB, 1782 SmallVectorImpl<Instruction *> &LIP, 1783 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC, 1784 AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li, 1785 DebugLoc dl, int alignment, bool UnorderedAtomic, 1786 const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo) 1787 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 1788 LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), 1789 PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)), 1790 Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags), 1791 SafetyInfo(SafetyInfo) {} 1792 1793 bool isInstInList(Instruction *I, 1794 const SmallVectorImpl<Instruction *> &) const override { 1795 Value *Ptr; 1796 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1797 Ptr = LI->getOperand(0); 1798 else 1799 Ptr = cast<StoreInst>(I)->getPointerOperand(); 1800 return PointerMustAliases.count(Ptr); 1801 } 1802 1803 void doExtraRewritesBeforeFinalDeletion() override { 1804 // Insert stores after in the loop exit blocks. Each exit block gets a 1805 // store of the live-out values that feed them. Since we've already told 1806 // the SSA updater about the defs in the loop and the preheader 1807 // definition, it is all set and we can start using it. 1808 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 1809 BasicBlock *ExitBlock = LoopExitBlocks[i]; 1810 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 1811 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 1812 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 1813 Instruction *InsertPos = LoopInsertPts[i]; 1814 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 1815 if (UnorderedAtomic) 1816 NewSI->setOrdering(AtomicOrdering::Unordered); 1817 NewSI->setAlignment(MaybeAlign(Alignment)); 1818 NewSI->setDebugLoc(DL); 1819 if (AATags) 1820 NewSI->setAAMetadata(AATags); 1821 1822 if (MSSAU) { 1823 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i]; 1824 MemoryAccess *NewMemAcc; 1825 if (!MSSAInsertPoint) { 1826 NewMemAcc = MSSAU->createMemoryAccessInBB( 1827 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning); 1828 } else { 1829 NewMemAcc = 1830 MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint); 1831 } 1832 MSSAInsertPts[i] = NewMemAcc; 1833 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1834 // FIXME: true for safety, false may still be correct. 1835 } 1836 } 1837 } 1838 1839 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 1840 // Update alias analysis. 1841 AST.copyValue(LI, V); 1842 } 1843 void instructionDeleted(Instruction *I) const override { 1844 SafetyInfo.removeInstruction(I); 1845 AST.deleteValue(I); 1846 if (MSSAU) 1847 MSSAU->removeMemoryAccess(I); 1848 } 1849 }; 1850 1851 1852 /// Return true iff we can prove that a caller of this function can not inspect 1853 /// the contents of the provided object in a well defined program. 1854 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) { 1855 if (isa<AllocaInst>(Object)) 1856 // Since the alloca goes out of scope, we know the caller can't retain a 1857 // reference to it and be well defined. Thus, we don't need to check for 1858 // capture. 1859 return true; 1860 1861 // For all other objects we need to know that the caller can't possibly 1862 // have gotten a reference to the object. There are two components of 1863 // that: 1864 // 1) Object can't be escaped by this function. This is what 1865 // PointerMayBeCaptured checks. 1866 // 2) Object can't have been captured at definition site. For this, we 1867 // need to know the return value is noalias. At the moment, we use a 1868 // weaker condition and handle only AllocLikeFunctions (which are 1869 // known to be noalias). TODO 1870 return isAllocLikeFn(Object, TLI) && 1871 !PointerMayBeCaptured(Object, true, true); 1872 } 1873 1874 } // namespace 1875 1876 /// Try to promote memory values to scalars by sinking stores out of the 1877 /// loop and moving loads to before the loop. We do this by looping over 1878 /// the stores in the loop, looking for stores to Must pointers which are 1879 /// loop invariant. 1880 /// 1881 bool llvm::promoteLoopAccessesToScalars( 1882 const SmallSetVector<Value *, 8> &PointerMustAliases, 1883 SmallVectorImpl<BasicBlock *> &ExitBlocks, 1884 SmallVectorImpl<Instruction *> &InsertPts, 1885 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC, 1886 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 1887 Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, 1888 ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) { 1889 // Verify inputs. 1890 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && 1891 CurAST != nullptr && SafetyInfo != nullptr && 1892 "Unexpected Input to promoteLoopAccessesToScalars"); 1893 1894 Value *SomePtr = *PointerMustAliases.begin(); 1895 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1896 1897 // It is not safe to promote a load/store from the loop if the load/store is 1898 // conditional. For example, turning: 1899 // 1900 // for () { if (c) *P += 1; } 1901 // 1902 // into: 1903 // 1904 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 1905 // 1906 // is not safe, because *P may only be valid to access if 'c' is true. 1907 // 1908 // The safety property divides into two parts: 1909 // p1) The memory may not be dereferenceable on entry to the loop. In this 1910 // case, we can't insert the required load in the preheader. 1911 // p2) The memory model does not allow us to insert a store along any dynamic 1912 // path which did not originally have one. 1913 // 1914 // If at least one store is guaranteed to execute, both properties are 1915 // satisfied, and promotion is legal. 1916 // 1917 // This, however, is not a necessary condition. Even if no store/load is 1918 // guaranteed to execute, we can still establish these properties. 1919 // We can establish (p1) by proving that hoisting the load into the preheader 1920 // is safe (i.e. proving dereferenceability on all paths through the loop). We 1921 // can use any access within the alias set to prove dereferenceability, 1922 // since they're all must alias. 1923 // 1924 // There are two ways establish (p2): 1925 // a) Prove the location is thread-local. In this case the memory model 1926 // requirement does not apply, and stores are safe to insert. 1927 // b) Prove a store dominates every exit block. In this case, if an exit 1928 // blocks is reached, the original dynamic path would have taken us through 1929 // the store, so inserting a store into the exit block is safe. Note that this 1930 // is different from the store being guaranteed to execute. For instance, 1931 // if an exception is thrown on the first iteration of the loop, the original 1932 // store is never executed, but the exit blocks are not executed either. 1933 1934 bool DereferenceableInPH = false; 1935 bool SafeToInsertStore = false; 1936 1937 SmallVector<Instruction *, 64> LoopUses; 1938 1939 // We start with an alignment of one and try to find instructions that allow 1940 // us to prove better alignment. 1941 unsigned Alignment = 1; 1942 // Keep track of which types of access we see 1943 bool SawUnorderedAtomic = false; 1944 bool SawNotAtomic = false; 1945 AAMDNodes AATags; 1946 1947 const DataLayout &MDL = Preheader->getModule()->getDataLayout(); 1948 1949 bool IsKnownThreadLocalObject = false; 1950 if (SafetyInfo->anyBlockMayThrow()) { 1951 // If a loop can throw, we have to insert a store along each unwind edge. 1952 // That said, we can't actually make the unwind edge explicit. Therefore, 1953 // we have to prove that the store is dead along the unwind edge. We do 1954 // this by proving that the caller can't have a reference to the object 1955 // after return and thus can't possibly load from the object. 1956 Value *Object = GetUnderlyingObject(SomePtr, MDL); 1957 if (!isKnownNonEscaping(Object, TLI)) 1958 return false; 1959 // Subtlety: Alloca's aren't visible to callers, but *are* potentially 1960 // visible to other threads if captured and used during their lifetimes. 1961 IsKnownThreadLocalObject = !isa<AllocaInst>(Object); 1962 } 1963 1964 // Check that all of the pointers in the alias set have the same type. We 1965 // cannot (yet) promote a memory location that is loaded and stored in 1966 // different sizes. While we are at it, collect alignment and AA info. 1967 for (Value *ASIV : PointerMustAliases) { 1968 // Check that all of the pointers in the alias set have the same type. We 1969 // cannot (yet) promote a memory location that is loaded and stored in 1970 // different sizes. 1971 if (SomePtr->getType() != ASIV->getType()) 1972 return false; 1973 1974 for (User *U : ASIV->users()) { 1975 // Ignore instructions that are outside the loop. 1976 Instruction *UI = dyn_cast<Instruction>(U); 1977 if (!UI || !CurLoop->contains(UI)) 1978 continue; 1979 1980 // If there is an non-load/store instruction in the loop, we can't promote 1981 // it. 1982 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { 1983 if (!Load->isUnordered()) 1984 return false; 1985 1986 SawUnorderedAtomic |= Load->isAtomic(); 1987 SawNotAtomic |= !Load->isAtomic(); 1988 1989 unsigned InstAlignment = Load->getAlignment(); 1990 if (!InstAlignment) 1991 InstAlignment = 1992 MDL.getABITypeAlignment(Load->getType()); 1993 1994 // Note that proving a load safe to speculate requires proving 1995 // sufficient alignment at the target location. Proving it guaranteed 1996 // to execute does as well. Thus we can increase our guaranteed 1997 // alignment as well. 1998 if (!DereferenceableInPH || (InstAlignment > Alignment)) 1999 if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo, 2000 ORE, Preheader->getTerminator())) { 2001 DereferenceableInPH = true; 2002 Alignment = std::max(Alignment, InstAlignment); 2003 } 2004 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 2005 // Stores *of* the pointer are not interesting, only stores *to* the 2006 // pointer. 2007 if (UI->getOperand(1) != ASIV) 2008 continue; 2009 if (!Store->isUnordered()) 2010 return false; 2011 2012 SawUnorderedAtomic |= Store->isAtomic(); 2013 SawNotAtomic |= !Store->isAtomic(); 2014 2015 // If the store is guaranteed to execute, both properties are satisfied. 2016 // We may want to check if a store is guaranteed to execute even if we 2017 // already know that promotion is safe, since it may have higher 2018 // alignment than any other guaranteed stores, in which case we can 2019 // raise the alignment on the promoted store. 2020 unsigned InstAlignment = Store->getAlignment(); 2021 if (!InstAlignment) 2022 InstAlignment = 2023 MDL.getABITypeAlignment(Store->getValueOperand()->getType()); 2024 2025 if (!DereferenceableInPH || !SafeToInsertStore || 2026 (InstAlignment > Alignment)) { 2027 if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) { 2028 DereferenceableInPH = true; 2029 SafeToInsertStore = true; 2030 Alignment = std::max(Alignment, InstAlignment); 2031 } 2032 } 2033 2034 // If a store dominates all exit blocks, it is safe to sink. 2035 // As explained above, if an exit block was executed, a dominating 2036 // store must have been executed at least once, so we are not 2037 // introducing stores on paths that did not have them. 2038 // Note that this only looks at explicit exit blocks. If we ever 2039 // start sinking stores into unwind edges (see above), this will break. 2040 if (!SafeToInsertStore) 2041 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { 2042 return DT->dominates(Store->getParent(), Exit); 2043 }); 2044 2045 // If the store is not guaranteed to execute, we may still get 2046 // deref info through it. 2047 if (!DereferenceableInPH) { 2048 DereferenceableInPH = isDereferenceableAndAlignedPointer( 2049 Store->getPointerOperand(), Store->getValueOperand()->getType(), 2050 MaybeAlign(Store->getAlignment()), MDL, 2051 Preheader->getTerminator(), DT); 2052 } 2053 } else 2054 return false; // Not a load or store. 2055 2056 // Merge the AA tags. 2057 if (LoopUses.empty()) { 2058 // On the first load/store, just take its AA tags. 2059 UI->getAAMetadata(AATags); 2060 } else if (AATags) { 2061 UI->getAAMetadata(AATags, /* Merge = */ true); 2062 } 2063 2064 LoopUses.push_back(UI); 2065 } 2066 } 2067 2068 // If we found both an unordered atomic instruction and a non-atomic memory 2069 // access, bail. We can't blindly promote non-atomic to atomic since we 2070 // might not be able to lower the result. We can't downgrade since that 2071 // would violate memory model. Also, align 0 is an error for atomics. 2072 if (SawUnorderedAtomic && SawNotAtomic) 2073 return false; 2074 2075 // If we're inserting an atomic load in the preheader, we must be able to 2076 // lower it. We're only guaranteed to be able to lower naturally aligned 2077 // atomics. 2078 auto *SomePtrElemType = SomePtr->getType()->getPointerElementType(); 2079 if (SawUnorderedAtomic && 2080 Alignment < MDL.getTypeStoreSize(SomePtrElemType)) 2081 return false; 2082 2083 // If we couldn't prove we can hoist the load, bail. 2084 if (!DereferenceableInPH) 2085 return false; 2086 2087 // We know we can hoist the load, but don't have a guaranteed store. 2088 // Check whether the location is thread-local. If it is, then we can insert 2089 // stores along paths which originally didn't have them without violating the 2090 // memory model. 2091 if (!SafeToInsertStore) { 2092 if (IsKnownThreadLocalObject) 2093 SafeToInsertStore = true; 2094 else { 2095 Value *Object = GetUnderlyingObject(SomePtr, MDL); 2096 SafeToInsertStore = 2097 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && 2098 !PointerMayBeCaptured(Object, true, true); 2099 } 2100 } 2101 2102 // If we've still failed to prove we can sink the store, give up. 2103 if (!SafeToInsertStore) 2104 return false; 2105 2106 // Otherwise, this is safe to promote, lets do it! 2107 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr 2108 << '\n'); 2109 ORE->emit([&]() { 2110 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", 2111 LoopUses[0]) 2112 << "Moving accesses to memory location out of the loop"; 2113 }); 2114 ++NumPromoted; 2115 2116 // Grab a debug location for the inserted loads/stores; given that the 2117 // inserted loads/stores have little relation to the original loads/stores, 2118 // this code just arbitrarily picks a location from one, since any debug 2119 // location is better than none. 2120 DebugLoc DL = LoopUses[0]->getDebugLoc(); 2121 2122 // We use the SSAUpdater interface to insert phi nodes as required. 2123 SmallVector<PHINode *, 16> NewPHIs; 2124 SSAUpdater SSA(&NewPHIs); 2125 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 2126 InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL, 2127 Alignment, SawUnorderedAtomic, AATags, *SafetyInfo); 2128 2129 // Set up the preheader to have a definition of the value. It is the live-out 2130 // value from the preheader that uses in the loop will use. 2131 LoadInst *PreheaderLoad = new LoadInst( 2132 SomePtr->getType()->getPointerElementType(), SomePtr, 2133 SomePtr->getName() + ".promoted", Preheader->getTerminator()); 2134 if (SawUnorderedAtomic) 2135 PreheaderLoad->setOrdering(AtomicOrdering::Unordered); 2136 PreheaderLoad->setAlignment(MaybeAlign(Alignment)); 2137 PreheaderLoad->setDebugLoc(DL); 2138 if (AATags) 2139 PreheaderLoad->setAAMetadata(AATags); 2140 SSA.AddAvailableValue(Preheader, PreheaderLoad); 2141 2142 if (MSSAU) { 2143 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB( 2144 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End); 2145 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess); 2146 MSSAU->insertUse(NewMemUse, /*RenameUses=*/true); 2147 } 2148 2149 if (MSSAU && VerifyMemorySSA) 2150 MSSAU->getMemorySSA()->verifyMemorySSA(); 2151 // Rewrite all the loads in the loop and remember all the definitions from 2152 // stores in the loop. 2153 Promoter.run(LoopUses); 2154 2155 if (MSSAU && VerifyMemorySSA) 2156 MSSAU->getMemorySSA()->verifyMemorySSA(); 2157 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 2158 if (PreheaderLoad->use_empty()) 2159 eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU); 2160 2161 return true; 2162 } 2163 2164 /// Returns an owning pointer to an alias set which incorporates aliasing info 2165 /// from L and all subloops of L. 2166 std::unique_ptr<AliasSetTracker> 2167 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, 2168 AliasAnalysis *AA) { 2169 auto CurAST = std::make_unique<AliasSetTracker>(*AA); 2170 2171 // Add everything from all the sub loops. 2172 for (Loop *InnerL : L->getSubLoops()) 2173 for (BasicBlock *BB : InnerL->blocks()) 2174 CurAST->add(*BB); 2175 2176 // And merge in this loop (without anything from inner loops). 2177 for (BasicBlock *BB : L->blocks()) 2178 if (LI->getLoopFor(BB) == L) 2179 CurAST->add(*BB); 2180 2181 return CurAST; 2182 } 2183 2184 std::unique_ptr<AliasSetTracker> 2185 LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA( 2186 Loop *L, AliasAnalysis *AA, MemorySSAUpdater *MSSAU) { 2187 auto *MSSA = MSSAU->getMemorySSA(); 2188 auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L); 2189 CurAST->addAllInstructionsInLoopUsingMSSA(); 2190 return CurAST; 2191 } 2192 2193 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, 2194 AliasSetTracker *CurAST, Loop *CurLoop, 2195 AliasAnalysis *AA) { 2196 // First check to see if any of the basic blocks in CurLoop invalidate *V. 2197 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod(); 2198 2199 if (!isInvalidatedAccordingToAST || !LICMN2Theshold) 2200 return isInvalidatedAccordingToAST; 2201 2202 // Check with a diagnostic analysis if we can refine the information above. 2203 // This is to identify the limitations of using the AST. 2204 // The alias set mechanism used by LICM has a major weakness in that it 2205 // combines all things which may alias into a single set *before* asking 2206 // modref questions. As a result, a single readonly call within a loop will 2207 // collapse all loads and stores into a single alias set and report 2208 // invalidation if the loop contains any store. For example, readonly calls 2209 // with deopt states have this form and create a general alias set with all 2210 // loads and stores. In order to get any LICM in loops containing possible 2211 // deopt states we need a more precise invalidation of checking the mod ref 2212 // info of each instruction within the loop and LI. This has a complexity of 2213 // O(N^2), so currently, it is used only as a diagnostic tool since the 2214 // default value of LICMN2Threshold is zero. 2215 2216 // Don't look at nested loops. 2217 if (CurLoop->begin() != CurLoop->end()) 2218 return true; 2219 2220 int N = 0; 2221 for (BasicBlock *BB : CurLoop->getBlocks()) 2222 for (Instruction &I : *BB) { 2223 if (N >= LICMN2Theshold) { 2224 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for " 2225 << *(MemLoc.Ptr) << "\n"); 2226 return true; 2227 } 2228 N++; 2229 auto Res = AA->getModRefInfo(&I, MemLoc); 2230 if (isModSet(Res)) { 2231 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for " 2232 << *(MemLoc.Ptr) << "\n"); 2233 return true; 2234 } 2235 } 2236 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n"); 2237 return false; 2238 } 2239 2240 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, 2241 Loop *CurLoop, 2242 SinkAndHoistLICMFlags &Flags) { 2243 // For hoisting, use the walker to determine safety 2244 if (!Flags.IsSink) { 2245 MemoryAccess *Source; 2246 // See declaration of SetLicmMssaOptCap for usage details. 2247 if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap) 2248 Source = MU->getDefiningAccess(); 2249 else { 2250 Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU); 2251 Flags.LicmMssaOptCounter++; 2252 } 2253 return !MSSA->isLiveOnEntryDef(Source) && 2254 CurLoop->contains(Source->getBlock()); 2255 } 2256 2257 // For sinking, we'd need to check all Defs below this use. The getClobbering 2258 // call will look on the backedge of the loop, but will check aliasing with 2259 // the instructions on the previous iteration. 2260 // For example: 2261 // for (i ... ) 2262 // load a[i] ( Use (LoE) 2263 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop. 2264 // i++; 2265 // The load sees no clobbering inside the loop, as the backedge alias check 2266 // does phi translation, and will check aliasing against store a[i-1]. 2267 // However sinking the load outside the loop, below the store is incorrect. 2268 2269 // For now, only sink if there are no Defs in the loop, and the existing ones 2270 // precede the use and are in the same block. 2271 // FIXME: Increase precision: Safe to sink if Use post dominates the Def; 2272 // needs PostDominatorTreeAnalysis. 2273 // FIXME: More precise: no Defs that alias this Use. 2274 if (Flags.NoOfMemAccTooLarge) 2275 return true; 2276 for (auto *BB : CurLoop->getBlocks()) 2277 if (auto *Accesses = MSSA->getBlockDefs(BB)) 2278 for (const auto &MA : *Accesses) 2279 if (const auto *MD = dyn_cast<MemoryDef>(&MA)) 2280 if (MU->getBlock() != MD->getBlock() || 2281 !MSSA->locallyDominates(MD, MU)) 2282 return true; 2283 return false; 2284 } 2285 2286 /// Little predicate that returns true if the specified basic block is in 2287 /// a subloop of the current one, not the current one itself. 2288 /// 2289 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 2290 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 2291 return LI->getLoopFor(BB) != CurLoop; 2292 } 2293