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