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