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