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