Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LICM.cpp
35268 views
//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This pass performs loop invariant code motion, attempting to remove as much9// code from the body of a loop as possible. It does this by either hoisting10// code into the preheader block, or by sinking code to the exit blocks if it is11// safe. This pass also promotes must-aliased memory locations in the loop to12// live in registers, thus hoisting and sinking "invariant" loads and stores.13//14// Hoisting operations out of loops is a canonicalization transform. It15// enables and simplifies subsequent optimizations in the middle-end.16// Rematerialization of hoisted instructions to reduce register pressure is the17// responsibility of the back-end, which has more accurate information about18// register pressure and also handles other optimizations than LICM that19// increase live-ranges.20//21// This pass uses alias analysis for two purposes:22//23// 1. Moving loop invariant loads and calls out of loops. If we can determine24// that a load or call inside of a loop never aliases anything stored to,25// we can hoist it or sink it like any other instruction.26// 2. Scalar Promotion of Memory - If there is a store instruction inside of27// the loop, we try to move the store to happen AFTER the loop instead of28// inside of the loop. This can only happen if a few conditions are true:29// A. The pointer stored through is loop invariant30// B. There are no stores or loads in the loop which _may_ alias the31// pointer. There are no calls in the loop which mod/ref the pointer.32// If these conditions are true, we can promote the loads and stores in the33// loop of the pointer to use a temporary alloca'd variable. We then use34// the SSAUpdater to construct the appropriate SSA form for the value.35//36//===----------------------------------------------------------------------===//3738#include "llvm/Transforms/Scalar/LICM.h"39#include "llvm/ADT/PriorityWorklist.h"40#include "llvm/ADT/SetOperations.h"41#include "llvm/ADT/Statistic.h"42#include "llvm/Analysis/AliasAnalysis.h"43#include "llvm/Analysis/AliasSetTracker.h"44#include "llvm/Analysis/AssumptionCache.h"45#include "llvm/Analysis/CaptureTracking.h"46#include "llvm/Analysis/GuardUtils.h"47#include "llvm/Analysis/LazyBlockFrequencyInfo.h"48#include "llvm/Analysis/Loads.h"49#include "llvm/Analysis/LoopInfo.h"50#include "llvm/Analysis/LoopIterator.h"51#include "llvm/Analysis/LoopNestAnalysis.h"52#include "llvm/Analysis/LoopPass.h"53#include "llvm/Analysis/MemorySSA.h"54#include "llvm/Analysis/MemorySSAUpdater.h"55#include "llvm/Analysis/MustExecute.h"56#include "llvm/Analysis/OptimizationRemarkEmitter.h"57#include "llvm/Analysis/ScalarEvolution.h"58#include "llvm/Analysis/TargetLibraryInfo.h"59#include "llvm/Analysis/TargetTransformInfo.h"60#include "llvm/Analysis/ValueTracking.h"61#include "llvm/IR/CFG.h"62#include "llvm/IR/Constants.h"63#include "llvm/IR/DataLayout.h"64#include "llvm/IR/DebugInfoMetadata.h"65#include "llvm/IR/DerivedTypes.h"66#include "llvm/IR/Dominators.h"67#include "llvm/IR/Instructions.h"68#include "llvm/IR/IntrinsicInst.h"69#include "llvm/IR/IRBuilder.h"70#include "llvm/IR/LLVMContext.h"71#include "llvm/IR/Metadata.h"72#include "llvm/IR/PatternMatch.h"73#include "llvm/IR/PredIteratorCache.h"74#include "llvm/InitializePasses.h"75#include "llvm/Support/CommandLine.h"76#include "llvm/Support/Debug.h"77#include "llvm/Support/raw_ostream.h"78#include "llvm/Target/TargetOptions.h"79#include "llvm/Transforms/Scalar.h"80#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"81#include "llvm/Transforms/Utils/BasicBlockUtils.h"82#include "llvm/Transforms/Utils/Local.h"83#include "llvm/Transforms/Utils/LoopUtils.h"84#include "llvm/Transforms/Utils/SSAUpdater.h"85#include <algorithm>86#include <utility>87using namespace llvm;8889namespace llvm {90class LPMUpdater;91} // namespace llvm9293#define DEBUG_TYPE "licm"9495STATISTIC(NumCreatedBlocks, "Number of blocks created");96STATISTIC(NumClonedBranches, "Number of branches cloned");97STATISTIC(NumSunk, "Number of instructions sunk out of loop");98STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");99STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");100STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");101STATISTIC(NumPromotionCandidates, "Number of promotion candidates");102STATISTIC(NumLoadPromoted, "Number of load-only promotions");103STATISTIC(NumLoadStorePromoted, "Number of load and store promotions");104STATISTIC(NumMinMaxHoisted,105"Number of min/max expressions hoisted out of the loop");106STATISTIC(NumGEPsHoisted,107"Number of geps reassociated and hoisted out of the loop");108STATISTIC(NumAddSubHoisted, "Number of add/subtract expressions reassociated "109"and hoisted out of the loop");110STATISTIC(NumFPAssociationsHoisted, "Number of invariant FP expressions "111"reassociated and hoisted out of the loop");112STATISTIC(NumIntAssociationsHoisted,113"Number of invariant int expressions "114"reassociated and hoisted out of the loop");115116/// Memory promotion is enabled by default.117static cl::opt<bool>118DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),119cl::desc("Disable memory promotion in LICM pass"));120121static cl::opt<bool> ControlFlowHoisting(122"licm-control-flow-hoisting", cl::Hidden, cl::init(false),123cl::desc("Enable control flow (and PHI) hoisting in LICM"));124125static cl::opt<bool>126SingleThread("licm-force-thread-model-single", cl::Hidden, cl::init(false),127cl::desc("Force thread model single in LICM pass"));128129static cl::opt<uint32_t> MaxNumUsesTraversed(130"licm-max-num-uses-traversed", cl::Hidden, cl::init(8),131cl::desc("Max num uses visited for identifying load "132"invariance in loop using invariant start (default = 8)"));133134static cl::opt<unsigned> FPAssociationUpperLimit(135"licm-max-num-fp-reassociations", cl::init(5U), cl::Hidden,136cl::desc(137"Set upper limit for the number of transformations performed "138"during a single round of hoisting the reassociated expressions."));139140cl::opt<unsigned> IntAssociationUpperLimit(141"licm-max-num-int-reassociations", cl::init(5U), cl::Hidden,142cl::desc(143"Set upper limit for the number of transformations performed "144"during a single round of hoisting the reassociated expressions."));145146// Experimental option to allow imprecision in LICM in pathological cases, in147// exchange for faster compile. This is to be removed if MemorySSA starts to148// address the same issue. LICM calls MemorySSAWalker's149// getClobberingMemoryAccess, up to the value of the Cap, getting perfect150// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,151// which may not be precise, since optimizeUses is capped. The result is152// correct, but we may not get as "far up" as possible to get which access is153// clobbering the one queried.154cl::opt<unsigned> llvm::SetLicmMssaOptCap(155"licm-mssa-optimization-cap", cl::init(100), cl::Hidden,156cl::desc("Enable imprecision in LICM in pathological cases, in exchange "157"for faster compile. Caps the MemorySSA clobbering calls."));158159// Experimentally, memory promotion carries less importance than sinking and160// hoisting. Limit when we do promotion when using MemorySSA, in order to save161// compile time.162cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(163"licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,164cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "165"effect. When MSSA in LICM is enabled, then this is the maximum "166"number of accesses allowed to be present in a loop in order to "167"enable memory promotion."));168169static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);170static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,171const LoopSafetyInfo *SafetyInfo,172TargetTransformInfo *TTI,173bool &FoldableInLoop, bool LoopNestMode);174static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,175BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,176MemorySSAUpdater &MSSAU, ScalarEvolution *SE,177OptimizationRemarkEmitter *ORE);178static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,179const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,180MemorySSAUpdater &MSSAU, OptimizationRemarkEmitter *ORE);181static bool isSafeToExecuteUnconditionally(182Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,183const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,184OptimizationRemarkEmitter *ORE, const Instruction *CtxI,185AssumptionCache *AC, bool AllowSpeculation);186static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU,187Loop *CurLoop, Instruction &I,188SinkAndHoistLICMFlags &Flags,189bool InvariantGroup);190static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA,191MemoryUse &MU);192/// Aggregates various functions for hoisting computations out of loop.193static bool hoistArithmetics(Instruction &I, Loop &L,194ICFLoopSafetyInfo &SafetyInfo,195MemorySSAUpdater &MSSAU, AssumptionCache *AC,196DominatorTree *DT);197static Instruction *cloneInstructionInExitBlock(198Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,199const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU);200201static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,202MemorySSAUpdater &MSSAU);203204static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest,205ICFLoopSafetyInfo &SafetyInfo,206MemorySSAUpdater &MSSAU, ScalarEvolution *SE);207208static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,209function_ref<void(Instruction *)> Fn);210using PointersAndHasReadsOutsideSet =211std::pair<SmallSetVector<Value *, 8>, bool>;212static SmallVector<PointersAndHasReadsOutsideSet, 0>213collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L);214215namespace {216struct LoopInvariantCodeMotion {217bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,218AssumptionCache *AC, TargetLibraryInfo *TLI,219TargetTransformInfo *TTI, ScalarEvolution *SE, MemorySSA *MSSA,220OptimizationRemarkEmitter *ORE, bool LoopNestMode = false);221222LoopInvariantCodeMotion(unsigned LicmMssaOptCap,223unsigned LicmMssaNoAccForPromotionCap,224bool LicmAllowSpeculation)225: LicmMssaOptCap(LicmMssaOptCap),226LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),227LicmAllowSpeculation(LicmAllowSpeculation) {}228229private:230unsigned LicmMssaOptCap;231unsigned LicmMssaNoAccForPromotionCap;232bool LicmAllowSpeculation;233};234235struct LegacyLICMPass : public LoopPass {236static char ID; // Pass identification, replacement for typeid237LegacyLICMPass(238unsigned LicmMssaOptCap = SetLicmMssaOptCap,239unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap,240bool LicmAllowSpeculation = true)241: LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,242LicmAllowSpeculation) {243initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());244}245246bool runOnLoop(Loop *L, LPPassManager &LPM) override {247if (skipLoop(L))248return false;249250LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "251<< L->getHeader()->getNameOrAsOperand() << "\n");252253Function *F = L->getHeader()->getParent();254255auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();256MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();257// For the old PM, we can't use OptimizationRemarkEmitter as an analysis258// pass. Function analyses need to be preserved across loop transformations259// but ORE cannot be preserved (see comment before the pass definition).260OptimizationRemarkEmitter ORE(L->getHeader()->getParent());261return LICM.runOnLoop(262L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),263&getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),264&getAnalysis<DominatorTreeWrapperPass>().getDomTree(),265&getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F),266&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(*F),267&getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F),268SE ? &SE->getSE() : nullptr, MSSA, &ORE);269}270271/// This transformation requires natural loop information & requires that272/// loop preheaders be inserted into the CFG...273///274void getAnalysisUsage(AnalysisUsage &AU) const override {275AU.addPreserved<DominatorTreeWrapperPass>();276AU.addPreserved<LoopInfoWrapperPass>();277AU.addRequired<TargetLibraryInfoWrapperPass>();278AU.addRequired<MemorySSAWrapperPass>();279AU.addPreserved<MemorySSAWrapperPass>();280AU.addRequired<TargetTransformInfoWrapperPass>();281AU.addRequired<AssumptionCacheTracker>();282getLoopAnalysisUsage(AU);283LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);284AU.addPreserved<LazyBlockFrequencyInfoPass>();285AU.addPreserved<LazyBranchProbabilityInfoPass>();286}287288private:289LoopInvariantCodeMotion LICM;290};291} // namespace292293PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,294LoopStandardAnalysisResults &AR, LPMUpdater &) {295if (!AR.MSSA)296report_fatal_error("LICM requires MemorySSA (loop-mssa)",297/*GenCrashDiag*/false);298299// For the new PM, we also can't use OptimizationRemarkEmitter as an analysis300// pass. Function analyses need to be preserved across loop transformations301// but ORE cannot be preserved (see comment before the pass definition).302OptimizationRemarkEmitter ORE(L.getHeader()->getParent());303304LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,305Opts.AllowSpeculation);306if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.AC, &AR.TLI, &AR.TTI,307&AR.SE, AR.MSSA, &ORE))308return PreservedAnalyses::all();309310auto PA = getLoopPassPreservedAnalyses();311PA.preserve<MemorySSAAnalysis>();312313return PA;314}315316void LICMPass::printPipeline(317raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {318static_cast<PassInfoMixin<LICMPass> *>(this)->printPipeline(319OS, MapClassName2PassName);320321OS << '<';322OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";323OS << '>';324}325326PreservedAnalyses LNICMPass::run(LoopNest &LN, LoopAnalysisManager &AM,327LoopStandardAnalysisResults &AR,328LPMUpdater &) {329if (!AR.MSSA)330report_fatal_error("LNICM requires MemorySSA (loop-mssa)",331/*GenCrashDiag*/false);332333// For the new PM, we also can't use OptimizationRemarkEmitter as an analysis334// pass. Function analyses need to be preserved across loop transformations335// but ORE cannot be preserved (see comment before the pass definition).336OptimizationRemarkEmitter ORE(LN.getParent());337338LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,339Opts.AllowSpeculation);340341Loop &OutermostLoop = LN.getOutermostLoop();342bool Changed = LICM.runOnLoop(&OutermostLoop, &AR.AA, &AR.LI, &AR.DT, &AR.AC,343&AR.TLI, &AR.TTI, &AR.SE, AR.MSSA, &ORE, true);344345if (!Changed)346return PreservedAnalyses::all();347348auto PA = getLoopPassPreservedAnalyses();349350PA.preserve<DominatorTreeAnalysis>();351PA.preserve<LoopAnalysis>();352PA.preserve<MemorySSAAnalysis>();353354return PA;355}356357void LNICMPass::printPipeline(358raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {359static_cast<PassInfoMixin<LNICMPass> *>(this)->printPipeline(360OS, MapClassName2PassName);361362OS << '<';363OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";364OS << '>';365}366367char LegacyLICMPass::ID = 0;368INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",369false, false)370INITIALIZE_PASS_DEPENDENCY(LoopPass)371INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)372INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)373INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)374INITIALIZE_PASS_DEPENDENCY(LazyBFIPass)375INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,376false)377378Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }379380llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(bool IsSink, Loop &L,381MemorySSA &MSSA)382: SinkAndHoistLICMFlags(SetLicmMssaOptCap, SetLicmMssaNoAccForPromotionCap,383IsSink, L, MSSA) {}384385llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(386unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,387Loop &L, MemorySSA &MSSA)388: LicmMssaOptCap(LicmMssaOptCap),389LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),390IsSink(IsSink) {391unsigned AccessCapCount = 0;392for (auto *BB : L.getBlocks())393if (const auto *Accesses = MSSA.getBlockAccesses(BB))394for (const auto &MA : *Accesses) {395(void)MA;396++AccessCapCount;397if (AccessCapCount > LicmMssaNoAccForPromotionCap) {398NoOfMemAccTooLarge = true;399return;400}401}402}403404/// Hoist expressions out of the specified loop. Note, alias info for inner405/// loop is not preserved so it is not a good idea to run LICM multiple406/// times on one loop.407bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI,408DominatorTree *DT, AssumptionCache *AC,409TargetLibraryInfo *TLI,410TargetTransformInfo *TTI,411ScalarEvolution *SE, MemorySSA *MSSA,412OptimizationRemarkEmitter *ORE,413bool LoopNestMode) {414bool Changed = false;415416assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");417418// If this loop has metadata indicating that LICM is not to be performed then419// just exit.420if (hasDisableLICMTransformsHint(L)) {421return false;422}423424// Don't sink stores from loops with coroutine suspend instructions.425// LICM would sink instructions into the default destination of426// the coroutine switch. The default destination of the switch is to427// handle the case where the coroutine is suspended, by which point the428// coroutine frame may have been destroyed. No instruction can be sunk there.429// FIXME: This would unfortunately hurt the performance of coroutines, however430// there is currently no general solution for this. Similar issues could also431// potentially happen in other passes where instructions are being moved432// across that edge.433bool HasCoroSuspendInst = llvm::any_of(L->getBlocks(), [](BasicBlock *BB) {434return llvm::any_of(*BB, [](Instruction &I) {435IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);436return II && II->getIntrinsicID() == Intrinsic::coro_suspend;437});438});439440MemorySSAUpdater MSSAU(MSSA);441SinkAndHoistLICMFlags Flags(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,442/*IsSink=*/true, *L, *MSSA);443444// Get the preheader block to move instructions into...445BasicBlock *Preheader = L->getLoopPreheader();446447// Compute loop safety information.448ICFLoopSafetyInfo SafetyInfo;449SafetyInfo.computeLoopSafetyInfo(L);450451// We want to visit all of the instructions in this loop... that are not parts452// of our subloops (they have already had their invariants hoisted out of453// their loop, into this loop, so there is no need to process the BODIES of454// the subloops).455//456// Traverse the body of the loop in depth first order on the dominator tree so457// that we are guaranteed to see definitions before we see uses. This allows458// us to sink instructions in one pass, without iteration. After sinking459// instructions, we perform another pass to hoist them out of the loop.460if (L->hasDedicatedExits())461Changed |=462LoopNestMode463? sinkRegionForLoopNest(DT->getNode(L->getHeader()), AA, LI, DT,464TLI, TTI, L, MSSAU, &SafetyInfo, Flags, ORE)465: sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,466MSSAU, &SafetyInfo, Flags, ORE);467Flags.setIsSink(false);468if (Preheader)469Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, AC, TLI, L,470MSSAU, SE, &SafetyInfo, Flags, ORE, LoopNestMode,471LicmAllowSpeculation);472473// Now that all loop invariants have been removed from the loop, promote any474// memory references to scalars that we can.475// Don't sink stores from loops without dedicated block exits. Exits476// containing indirect branches are not transformed by loop simplify,477// make sure we catch that. An additional load may be generated in the478// preheader for SSA updater, so also avoid sinking when no preheader479// is available.480if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&481!Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {482// Figure out the loop exits and their insertion points483SmallVector<BasicBlock *, 8> ExitBlocks;484L->getUniqueExitBlocks(ExitBlocks);485486// We can't insert into a catchswitch.487bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {488return isa<CatchSwitchInst>(Exit->getTerminator());489});490491if (!HasCatchSwitch) {492SmallVector<BasicBlock::iterator, 8> InsertPts;493SmallVector<MemoryAccess *, 8> MSSAInsertPts;494InsertPts.reserve(ExitBlocks.size());495MSSAInsertPts.reserve(ExitBlocks.size());496for (BasicBlock *ExitBlock : ExitBlocks) {497InsertPts.push_back(ExitBlock->getFirstInsertionPt());498MSSAInsertPts.push_back(nullptr);499}500501PredIteratorCache PIC;502503// Promoting one set of accesses may make the pointers for another set504// loop invariant, so run this in a loop.505bool Promoted = false;506bool LocalPromoted;507do {508LocalPromoted = false;509for (auto [PointerMustAliases, HasReadsOutsideSet] :510collectPromotionCandidates(MSSA, AA, L)) {511LocalPromoted |= promoteLoopAccessesToScalars(512PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,513DT, AC, TLI, TTI, L, MSSAU, &SafetyInfo, ORE,514LicmAllowSpeculation, HasReadsOutsideSet);515}516Promoted |= LocalPromoted;517} while (LocalPromoted);518519// Once we have promoted values across the loop body we have to520// recursively reform LCSSA as any nested loop may now have values defined521// within the loop used in the outer loop.522// FIXME: This is really heavy handed. It would be a bit better to use an523// SSAUpdater strategy during promotion that was LCSSA aware and reformed524// it as it went.525if (Promoted)526formLCSSARecursively(*L, *DT, LI, SE);527528Changed |= Promoted;529}530}531532// Check that neither this loop nor its parent have had LCSSA broken. LICM is533// specifically moving instructions across the loop boundary and so it is534// especially in need of basic functional correctness checking here.535assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");536assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) &&537"Parent loop not left in LCSSA form after LICM!");538539if (VerifyMemorySSA)540MSSA->verifyMemorySSA();541542if (Changed && SE)543SE->forgetLoopDispositions();544return Changed;545}546547/// Walk the specified region of the CFG (defined by all blocks dominated by548/// the specified block, and that are in the current loop) in reverse depth549/// first order w.r.t the DominatorTree. This allows us to visit uses before550/// definitions, allowing us to sink a loop body in one pass without iteration.551///552bool llvm::sinkRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,553DominatorTree *DT, TargetLibraryInfo *TLI,554TargetTransformInfo *TTI, Loop *CurLoop,555MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,556SinkAndHoistLICMFlags &Flags,557OptimizationRemarkEmitter *ORE, Loop *OutermostLoop) {558559// Verify inputs.560assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&561CurLoop != nullptr && SafetyInfo != nullptr &&562"Unexpected input to sinkRegion.");563564// We want to visit children before parents. We will enqueue all the parents565// before their children in the worklist and process the worklist in reverse566// order.567SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);568569bool Changed = false;570for (DomTreeNode *DTN : reverse(Worklist)) {571BasicBlock *BB = DTN->getBlock();572// Only need to process the contents of this block if it is not part of a573// subloop (which would already have been processed).574if (inSubLoop(BB, CurLoop, LI))575continue;576577for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {578Instruction &I = *--II;579580// The instruction is not used in the loop if it is dead. In this case,581// we just delete it instead of sinking it.582if (isInstructionTriviallyDead(&I, TLI)) {583LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');584salvageKnowledge(&I);585salvageDebugInfo(I);586++II;587eraseInstruction(I, *SafetyInfo, MSSAU);588Changed = true;589continue;590}591592// Check to see if we can sink this instruction to the exit blocks593// of the loop. We can do this if the all users of the instruction are594// outside of the loop. In this case, it doesn't even matter if the595// operands of the instruction are loop invariant.596//597bool FoldableInLoop = false;598bool LoopNestMode = OutermostLoop != nullptr;599if (!I.mayHaveSideEffects() &&600isNotUsedOrFoldableInLoop(I, LoopNestMode ? OutermostLoop : CurLoop,601SafetyInfo, TTI, FoldableInLoop,602LoopNestMode) &&603canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE)) {604if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {605if (!FoldableInLoop) {606++II;607salvageDebugInfo(I);608eraseInstruction(I, *SafetyInfo, MSSAU);609}610Changed = true;611}612}613}614}615if (VerifyMemorySSA)616MSSAU.getMemorySSA()->verifyMemorySSA();617return Changed;618}619620bool llvm::sinkRegionForLoopNest(DomTreeNode *N, AAResults *AA, LoopInfo *LI,621DominatorTree *DT, TargetLibraryInfo *TLI,622TargetTransformInfo *TTI, Loop *CurLoop,623MemorySSAUpdater &MSSAU,624ICFLoopSafetyInfo *SafetyInfo,625SinkAndHoistLICMFlags &Flags,626OptimizationRemarkEmitter *ORE) {627628bool Changed = false;629SmallPriorityWorklist<Loop *, 4> Worklist;630Worklist.insert(CurLoop);631appendLoopsToWorklist(*CurLoop, Worklist);632while (!Worklist.empty()) {633Loop *L = Worklist.pop_back_val();634Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,635MSSAU, SafetyInfo, Flags, ORE, CurLoop);636}637return Changed;638}639640namespace {641// This is a helper class for hoistRegion to make it able to hoist control flow642// in order to be able to hoist phis. The way this works is that we initially643// start hoisting to the loop preheader, and when we see a loop invariant branch644// we make note of this. When we then come to hoist an instruction that's645// conditional on such a branch we duplicate the branch and the relevant control646// flow, then hoist the instruction into the block corresponding to its original647// block in the duplicated control flow.648class ControlFlowHoister {649private:650// Information about the loop we are hoisting from651LoopInfo *LI;652DominatorTree *DT;653Loop *CurLoop;654MemorySSAUpdater &MSSAU;655656// A map of blocks in the loop to the block their instructions will be hoisted657// to.658DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;659660// The branches that we can hoist, mapped to the block that marks a661// convergence point of their control flow.662DenseMap<BranchInst *, BasicBlock *> HoistableBranches;663664public:665ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,666MemorySSAUpdater &MSSAU)667: LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}668669void registerPossiblyHoistableBranch(BranchInst *BI) {670// We can only hoist conditional branches with loop invariant operands.671if (!ControlFlowHoisting || !BI->isConditional() ||672!CurLoop->hasLoopInvariantOperands(BI))673return;674675// The branch destinations need to be in the loop, and we don't gain676// anything by duplicating conditional branches with duplicate successors,677// as it's essentially the same as an unconditional branch.678BasicBlock *TrueDest = BI->getSuccessor(0);679BasicBlock *FalseDest = BI->getSuccessor(1);680if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||681TrueDest == FalseDest)682return;683684// We can hoist BI if one branch destination is the successor of the other,685// or both have common successor which we check by seeing if the686// intersection of their successors is non-empty.687// TODO: This could be expanded to allowing branches where both ends688// eventually converge to a single block.689SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;690TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));691FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));692BasicBlock *CommonSucc = nullptr;693if (TrueDestSucc.count(FalseDest)) {694CommonSucc = FalseDest;695} else if (FalseDestSucc.count(TrueDest)) {696CommonSucc = TrueDest;697} else {698set_intersect(TrueDestSucc, FalseDestSucc);699// If there's one common successor use that.700if (TrueDestSucc.size() == 1)701CommonSucc = *TrueDestSucc.begin();702// If there's more than one pick whichever appears first in the block list703// (we can't use the value returned by TrueDestSucc.begin() as it's704// unpredicatable which element gets returned).705else if (!TrueDestSucc.empty()) {706Function *F = TrueDest->getParent();707auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };708auto It = llvm::find_if(*F, IsSucc);709assert(It != F->end() && "Could not find successor in function");710CommonSucc = &*It;711}712}713// The common successor has to be dominated by the branch, as otherwise714// there will be some other path to the successor that will not be715// controlled by this branch so any phi we hoist would be controlled by the716// wrong condition. This also takes care of avoiding hoisting of loop back717// edges.718// TODO: In some cases this could be relaxed if the successor is dominated719// by another block that's been hoisted and we can guarantee that the720// control flow has been replicated exactly.721if (CommonSucc && DT->dominates(BI, CommonSucc))722HoistableBranches[BI] = CommonSucc;723}724725bool canHoistPHI(PHINode *PN) {726// The phi must have loop invariant operands.727if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))728return false;729// We can hoist phis if the block they are in is the target of hoistable730// branches which cover all of the predecessors of the block.731SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;732BasicBlock *BB = PN->getParent();733for (BasicBlock *PredBB : predecessors(BB))734PredecessorBlocks.insert(PredBB);735// If we have less predecessor blocks than predecessors then the phi will736// have more than one incoming value for the same block which we can't737// handle.738// TODO: This could be handled be erasing some of the duplicate incoming739// values.740if (PredecessorBlocks.size() != pred_size(BB))741return false;742for (auto &Pair : HoistableBranches) {743if (Pair.second == BB) {744// Which blocks are predecessors via this branch depends on if the745// branch is triangle-like or diamond-like.746if (Pair.first->getSuccessor(0) == BB) {747PredecessorBlocks.erase(Pair.first->getParent());748PredecessorBlocks.erase(Pair.first->getSuccessor(1));749} else if (Pair.first->getSuccessor(1) == BB) {750PredecessorBlocks.erase(Pair.first->getParent());751PredecessorBlocks.erase(Pair.first->getSuccessor(0));752} else {753PredecessorBlocks.erase(Pair.first->getSuccessor(0));754PredecessorBlocks.erase(Pair.first->getSuccessor(1));755}756}757}758// PredecessorBlocks will now be empty if for every predecessor of BB we759// found a hoistable branch source.760return PredecessorBlocks.empty();761}762763BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {764if (!ControlFlowHoisting)765return CurLoop->getLoopPreheader();766// If BB has already been hoisted, return that767if (HoistDestinationMap.count(BB))768return HoistDestinationMap[BB];769770// Check if this block is conditional based on a pending branch771auto HasBBAsSuccessor =772[&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {773return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||774Pair.first->getSuccessor(1) == BB);775};776auto It = llvm::find_if(HoistableBranches, HasBBAsSuccessor);777778// If not involved in a pending branch, hoist to preheader779BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();780if (It == HoistableBranches.end()) {781LLVM_DEBUG(dbgs() << "LICM using "782<< InitialPreheader->getNameOrAsOperand()783<< " as hoist destination for "784<< BB->getNameOrAsOperand() << "\n");785HoistDestinationMap[BB] = InitialPreheader;786return InitialPreheader;787}788BranchInst *BI = It->first;789assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==790HoistableBranches.end() &&791"BB is expected to be the target of at most one branch");792793LLVMContext &C = BB->getContext();794BasicBlock *TrueDest = BI->getSuccessor(0);795BasicBlock *FalseDest = BI->getSuccessor(1);796BasicBlock *CommonSucc = HoistableBranches[BI];797BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());798799// Create hoisted versions of blocks that currently don't have them800auto CreateHoistedBlock = [&](BasicBlock *Orig) {801if (HoistDestinationMap.count(Orig))802return HoistDestinationMap[Orig];803BasicBlock *New =804BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());805HoistDestinationMap[Orig] = New;806DT->addNewBlock(New, HoistTarget);807if (CurLoop->getParentLoop())808CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);809++NumCreatedBlocks;810LLVM_DEBUG(dbgs() << "LICM created " << New->getName()811<< " as hoist destination for " << Orig->getName()812<< "\n");813return New;814};815BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);816BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);817BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);818819// Link up these blocks with branches.820if (!HoistCommonSucc->getTerminator()) {821// The new common successor we've generated will branch to whatever that822// hoist target branched to.823BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();824assert(TargetSucc && "Expected hoist target to have a single successor");825HoistCommonSucc->moveBefore(TargetSucc);826BranchInst::Create(TargetSucc, HoistCommonSucc);827}828if (!HoistTrueDest->getTerminator()) {829HoistTrueDest->moveBefore(HoistCommonSucc);830BranchInst::Create(HoistCommonSucc, HoistTrueDest);831}832if (!HoistFalseDest->getTerminator()) {833HoistFalseDest->moveBefore(HoistCommonSucc);834BranchInst::Create(HoistCommonSucc, HoistFalseDest);835}836837// If BI is being cloned to what was originally the preheader then838// HoistCommonSucc will now be the new preheader.839if (HoistTarget == InitialPreheader) {840// Phis in the loop header now need to use the new preheader.841InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);842MSSAU.wireOldPredecessorsToNewImmediatePredecessor(843HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});844// The new preheader dominates the loop header.845DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);846DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());847DT->changeImmediateDominator(HeaderNode, PreheaderNode);848// The preheader hoist destination is now the new preheader, with the849// exception of the hoist destination of this branch.850for (auto &Pair : HoistDestinationMap)851if (Pair.second == InitialPreheader && Pair.first != BI->getParent())852Pair.second = HoistCommonSucc;853}854855// Now finally clone BI.856ReplaceInstWithInst(857HoistTarget->getTerminator(),858BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));859++NumClonedBranches;860861assert(CurLoop->getLoopPreheader() &&862"Hoisting blocks should not have destroyed preheader");863return HoistDestinationMap[BB];864}865};866} // namespace867868/// Walk the specified region of the CFG (defined by all blocks dominated by869/// the specified block, and that are in the current loop) in depth first870/// order w.r.t the DominatorTree. This allows us to visit definitions before871/// uses, allowing us to hoist a loop body in one pass without iteration.872///873bool llvm::hoistRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,874DominatorTree *DT, AssumptionCache *AC,875TargetLibraryInfo *TLI, Loop *CurLoop,876MemorySSAUpdater &MSSAU, ScalarEvolution *SE,877ICFLoopSafetyInfo *SafetyInfo,878SinkAndHoistLICMFlags &Flags,879OptimizationRemarkEmitter *ORE, bool LoopNestMode,880bool AllowSpeculation) {881// Verify inputs.882assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&883CurLoop != nullptr && SafetyInfo != nullptr &&884"Unexpected input to hoistRegion.");885886ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);887888// Keep track of instructions that have been hoisted, as they may need to be889// re-hoisted if they end up not dominating all of their uses.890SmallVector<Instruction *, 16> HoistedInstructions;891892// For PHI hoisting to work we need to hoist blocks before their successors.893// We can do this by iterating through the blocks in the loop in reverse894// post-order.895LoopBlocksRPO Worklist(CurLoop);896Worklist.perform(LI);897bool Changed = false;898BasicBlock *Preheader = CurLoop->getLoopPreheader();899for (BasicBlock *BB : Worklist) {900// Only need to process the contents of this block if it is not part of a901// subloop (which would already have been processed).902if (!LoopNestMode && inSubLoop(BB, CurLoop, LI))903continue;904905for (Instruction &I : llvm::make_early_inc_range(*BB)) {906// Try hoisting the instruction out to the preheader. We can only do907// this if all of the operands of the instruction are loop invariant and908// if it is safe to hoist the instruction. We also check block frequency909// to make sure instruction only gets hoisted into colder blocks.910// TODO: It may be safe to hoist if we are hoisting to a conditional block911// and we have accurately duplicated the control flow from the loop header912// to that block.913if (CurLoop->hasLoopInvariantOperands(&I) &&914canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE) &&915isSafeToExecuteUnconditionally(916I, DT, TLI, CurLoop, SafetyInfo, ORE,917Preheader->getTerminator(), AC, AllowSpeculation)) {918hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,919MSSAU, SE, ORE);920HoistedInstructions.push_back(&I);921Changed = true;922continue;923}924925// Attempt to remove floating point division out of the loop by926// converting it to a reciprocal multiplication.927if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&928CurLoop->isLoopInvariant(I.getOperand(1))) {929auto Divisor = I.getOperand(1);930auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);931auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);932ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());933SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());934ReciprocalDivisor->insertBefore(&I);935ReciprocalDivisor->setDebugLoc(I.getDebugLoc());936937auto Product =938BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);939Product->setFastMathFlags(I.getFastMathFlags());940SafetyInfo->insertInstructionTo(Product, I.getParent());941Product->insertAfter(&I);942Product->setDebugLoc(I.getDebugLoc());943I.replaceAllUsesWith(Product);944eraseInstruction(I, *SafetyInfo, MSSAU);945946hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),947SafetyInfo, MSSAU, SE, ORE);948HoistedInstructions.push_back(ReciprocalDivisor);949Changed = true;950continue;951}952953auto IsInvariantStart = [&](Instruction &I) {954using namespace PatternMatch;955return I.use_empty() &&956match(&I, m_Intrinsic<Intrinsic::invariant_start>());957};958auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {959return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&960SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop);961};962if ((IsInvariantStart(I) || isGuard(&I)) &&963CurLoop->hasLoopInvariantOperands(&I) &&964MustExecuteWithoutWritesBefore(I)) {965hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,966MSSAU, SE, ORE);967HoistedInstructions.push_back(&I);968Changed = true;969continue;970}971972if (PHINode *PN = dyn_cast<PHINode>(&I)) {973if (CFH.canHoistPHI(PN)) {974// Redirect incoming blocks first to ensure that we create hoisted975// versions of those blocks before we hoist the phi.976for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)977PN->setIncomingBlock(978i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));979hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,980MSSAU, SE, ORE);981assert(DT->dominates(PN, BB) && "Conditional PHIs not expected");982Changed = true;983continue;984}985}986987// Try to reassociate instructions so that part of computations can be988// done out of loop.989if (hoistArithmetics(I, *CurLoop, *SafetyInfo, MSSAU, AC, DT)) {990Changed = true;991continue;992}993994// Remember possibly hoistable branches so we can actually hoist them995// later if needed.996if (BranchInst *BI = dyn_cast<BranchInst>(&I))997CFH.registerPossiblyHoistableBranch(BI);998}999}10001001// If we hoisted instructions to a conditional block they may not dominate1002// their uses that weren't hoisted (such as phis where some operands are not1003// loop invariant). If so make them unconditional by moving them to their1004// immediate dominator. We iterate through the instructions in reverse order1005// which ensures that when we rehoist an instruction we rehoist its operands,1006// and also keep track of where in the block we are rehoisting to make sure1007// that we rehoist instructions before the instructions that use them.1008Instruction *HoistPoint = nullptr;1009if (ControlFlowHoisting) {1010for (Instruction *I : reverse(HoistedInstructions)) {1011if (!llvm::all_of(I->uses(),1012[&](Use &U) { return DT->dominates(I, U); })) {1013BasicBlock *Dominator =1014DT->getNode(I->getParent())->getIDom()->getBlock();1015if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {1016if (HoistPoint)1017assert(DT->dominates(Dominator, HoistPoint->getParent()) &&1018"New hoist point expected to dominate old hoist point");1019HoistPoint = Dominator->getTerminator();1020}1021LLVM_DEBUG(dbgs() << "LICM rehoisting to "1022<< HoistPoint->getParent()->getNameOrAsOperand()1023<< ": " << *I << "\n");1024moveInstructionBefore(*I, HoistPoint->getIterator(), *SafetyInfo, MSSAU,1025SE);1026HoistPoint = I;1027Changed = true;1028}1029}1030}1031if (VerifyMemorySSA)1032MSSAU.getMemorySSA()->verifyMemorySSA();10331034// Now that we've finished hoisting make sure that LI and DT are still1035// valid.1036#ifdef EXPENSIVE_CHECKS1037if (Changed) {1038assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&1039"Dominator tree verification failed");1040LI->verify(*DT);1041}1042#endif10431044return Changed;1045}10461047// Return true if LI is invariant within scope of the loop. LI is invariant if1048// CurLoop is dominated by an invariant.start representing the same memory1049// location and size as the memory location LI loads from, and also the1050// invariant.start has no uses.1051static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,1052Loop *CurLoop) {1053Value *Addr = LI->getPointerOperand();1054const DataLayout &DL = LI->getDataLayout();1055const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());10561057// It is not currently possible for clang to generate an invariant.start1058// intrinsic with scalable vector types because we don't support thread local1059// sizeless types and we don't permit sizeless types in structs or classes.1060// Furthermore, even if support is added for this in future the intrinsic1061// itself is defined to have a size of -1 for variable sized objects. This1062// makes it impossible to verify if the intrinsic envelops our region of1063// interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>1064// types would have a -1 parameter, but the former is clearly double the size1065// of the latter.1066if (LocSizeInBits.isScalable())1067return false;10681069// If we've ended up at a global/constant, bail. We shouldn't be looking at1070// uselists for non-local Values in a loop pass.1071if (isa<Constant>(Addr))1072return false;10731074unsigned UsesVisited = 0;1075// Traverse all uses of the load operand value, to see if invariant.start is1076// one of the uses, and whether it dominates the load instruction.1077for (auto *U : Addr->users()) {1078// Avoid traversing for Load operand with high number of users.1079if (++UsesVisited > MaxNumUsesTraversed)1080return false;1081IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);1082// If there are escaping uses of invariant.start instruction, the load maybe1083// non-invariant.1084if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||1085!II->use_empty())1086continue;1087ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));1088// The intrinsic supports having a -1 argument for variable sized objects1089// so we should check for that here.1090if (InvariantSize->isNegative())1091continue;1092uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;1093// Confirm the invariant.start location size contains the load operand size1094// in bits. Also, the invariant.start should dominate the load, and we1095// should not hoist the load out of a loop that contains this dominating1096// invariant.start.1097if (LocSizeInBits.getFixedValue() <= InvariantSizeInBits &&1098DT->properlyDominates(II->getParent(), CurLoop->getHeader()))1099return true;1100}11011102return false;1103}11041105namespace {1106/// Return true if-and-only-if we know how to (mechanically) both hoist and1107/// sink a given instruction out of a loop. Does not address legality1108/// concerns such as aliasing or speculation safety.1109bool isHoistableAndSinkableInst(Instruction &I) {1110// Only these instructions are hoistable/sinkable.1111return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||1112isa<FenceInst>(I) || isa<CastInst>(I) || isa<UnaryOperator>(I) ||1113isa<BinaryOperator>(I) || isa<SelectInst>(I) ||1114isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||1115isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||1116isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||1117isa<InsertValueInst>(I) || isa<FreezeInst>(I));1118}1119/// Return true if MSSA knows there are no MemoryDefs in the loop.1120bool isReadOnly(const MemorySSAUpdater &MSSAU, const Loop *L) {1121for (auto *BB : L->getBlocks())1122if (MSSAU.getMemorySSA()->getBlockDefs(BB))1123return false;1124return true;1125}11261127/// Return true if I is the only Instruction with a MemoryAccess in L.1128bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,1129const MemorySSAUpdater &MSSAU) {1130for (auto *BB : L->getBlocks())1131if (auto *Accs = MSSAU.getMemorySSA()->getBlockAccesses(BB)) {1132int NotAPhi = 0;1133for (const auto &Acc : *Accs) {1134if (isa<MemoryPhi>(&Acc))1135continue;1136const auto *MUD = cast<MemoryUseOrDef>(&Acc);1137if (MUD->getMemoryInst() != I || NotAPhi++ == 1)1138return false;1139}1140}1141return true;1142}1143}11441145static MemoryAccess *getClobberingMemoryAccess(MemorySSA &MSSA,1146BatchAAResults &BAA,1147SinkAndHoistLICMFlags &Flags,1148MemoryUseOrDef *MA) {1149// See declaration of SetLicmMssaOptCap for usage details.1150if (Flags.tooManyClobberingCalls())1151return MA->getDefiningAccess();11521153MemoryAccess *Source =1154MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(MA, BAA);1155Flags.incrementClobberingCalls();1156return Source;1157}11581159bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,1160Loop *CurLoop, MemorySSAUpdater &MSSAU,1161bool TargetExecutesOncePerLoop,1162SinkAndHoistLICMFlags &Flags,1163OptimizationRemarkEmitter *ORE) {1164// If we don't understand the instruction, bail early.1165if (!isHoistableAndSinkableInst(I))1166return false;11671168MemorySSA *MSSA = MSSAU.getMemorySSA();1169// Loads have extra constraints we have to verify before we can hoist them.1170if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {1171if (!LI->isUnordered())1172return false; // Don't sink/hoist volatile or ordered atomic loads!11731174// Loads from constant memory are always safe to move, even if they end up1175// in the same alias set as something that ends up being modified.1176if (!isModSet(AA->getModRefInfoMask(LI->getOperand(0))))1177return true;1178if (LI->hasMetadata(LLVMContext::MD_invariant_load))1179return true;11801181if (LI->isAtomic() && !TargetExecutesOncePerLoop)1182return false; // Don't risk duplicating unordered loads11831184// This checks for an invariant.start dominating the load.1185if (isLoadInvariantInLoop(LI, DT, CurLoop))1186return true;11871188auto MU = cast<MemoryUse>(MSSA->getMemoryAccess(LI));11891190bool InvariantGroup = LI->hasMetadata(LLVMContext::MD_invariant_group);11911192bool Invalidated = pointerInvalidatedByLoop(1193MSSA, MU, CurLoop, I, Flags, InvariantGroup);1194// Check loop-invariant address because this may also be a sinkable load1195// whose address is not necessarily loop-invariant.1196if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))1197ORE->emit([&]() {1198return OptimizationRemarkMissed(1199DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)1200<< "failed to move load with loop-invariant address "1201"because the loop may invalidate its value";1202});12031204return !Invalidated;1205} else if (CallInst *CI = dyn_cast<CallInst>(&I)) {1206// Don't sink or hoist dbg info; it's legal, but not useful.1207if (isa<DbgInfoIntrinsic>(I))1208return false;12091210// Don't sink calls which can throw.1211if (CI->mayThrow())1212return false;12131214// Convergent attribute has been used on operations that involve1215// inter-thread communication which results are implicitly affected by the1216// enclosing control flows. It is not safe to hoist or sink such operations1217// across control flow.1218if (CI->isConvergent())1219return false;12201221// FIXME: Current LLVM IR semantics don't work well with coroutines and1222// thread local globals. We currently treat getting the address of a thread1223// local global as not accessing memory, even though it may not be a1224// constant throughout a function with coroutines. Remove this check after1225// we better model semantics of thread local globals.1226if (CI->getFunction()->isPresplitCoroutine())1227return false;12281229using namespace PatternMatch;1230if (match(CI, m_Intrinsic<Intrinsic::assume>()))1231// Assumes don't actually alias anything or throw1232return true;12331234// Handle simple cases by querying alias analysis.1235MemoryEffects Behavior = AA->getMemoryEffects(CI);12361237if (Behavior.doesNotAccessMemory())1238return true;1239if (Behavior.onlyReadsMemory()) {1240// A readonly argmemonly function only reads from memory pointed to by1241// it's arguments with arbitrary offsets. If we can prove there are no1242// writes to this memory in the loop, we can hoist or sink.1243if (Behavior.onlyAccessesArgPointees()) {1244// TODO: expand to writeable arguments1245for (Value *Op : CI->args())1246if (Op->getType()->isPointerTy() &&1247pointerInvalidatedByLoop(1248MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, I,1249Flags, /*InvariantGroup=*/false))1250return false;1251return true;1252}12531254// If this call only reads from memory and there are no writes to memory1255// in the loop, we can hoist or sink the call as appropriate.1256if (isReadOnly(MSSAU, CurLoop))1257return true;1258}12591260// FIXME: This should use mod/ref information to see if we can hoist or1261// sink the call.12621263return false;1264} else if (auto *FI = dyn_cast<FenceInst>(&I)) {1265// Fences alias (most) everything to provide ordering. For the moment,1266// just give up if there are any other memory operations in the loop.1267return isOnlyMemoryAccess(FI, CurLoop, MSSAU);1268} else if (auto *SI = dyn_cast<StoreInst>(&I)) {1269if (!SI->isUnordered())1270return false; // Don't sink/hoist volatile or ordered atomic store!12711272// We can only hoist a store that we can prove writes a value which is not1273// read or overwritten within the loop. For those cases, we fallback to1274// load store promotion instead. TODO: We can extend this to cases where1275// there is exactly one write to the location and that write dominates an1276// arbitrary number of reads in the loop.1277if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))1278return true;1279// If there are more accesses than the Promotion cap, then give up as we're1280// not walking a list that long.1281if (Flags.tooManyMemoryAccesses())1282return false;12831284auto *SIMD = MSSA->getMemoryAccess(SI);1285BatchAAResults BAA(*AA);1286auto *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, SIMD);1287// Make sure there are no clobbers inside the loop.1288if (!MSSA->isLiveOnEntryDef(Source) &&1289CurLoop->contains(Source->getBlock()))1290return false;12911292// If there are interfering Uses (i.e. their defining access is in the1293// loop), or ordered loads (stored as Defs!), don't move this store.1294// Could do better here, but this is conservatively correct.1295// TODO: Cache set of Uses on the first walk in runOnLoop, update when1296// moving accesses. Can also extend to dominating uses.1297for (auto *BB : CurLoop->getBlocks())1298if (auto *Accesses = MSSA->getBlockAccesses(BB)) {1299for (const auto &MA : *Accesses)1300if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {1301auto *MD = getClobberingMemoryAccess(*MSSA, BAA, Flags,1302const_cast<MemoryUse *>(MU));1303if (!MSSA->isLiveOnEntryDef(MD) &&1304CurLoop->contains(MD->getBlock()))1305return false;1306// Disable hoisting past potentially interfering loads. Optimized1307// Uses may point to an access outside the loop, as getClobbering1308// checks the previous iteration when walking the backedge.1309// FIXME: More precise: no Uses that alias SI.1310if (!Flags.getIsSink() && !MSSA->dominates(SIMD, MU))1311return false;1312} else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) {1313if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {1314(void)LI; // Silence warning.1315assert(!LI->isUnordered() && "Expected unordered load");1316return false;1317}1318// Any call, while it may not be clobbering SI, it may be a use.1319if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {1320// Check if the call may read from the memory location written1321// to by SI. Check CI's attributes and arguments; the number of1322// such checks performed is limited above by NoOfMemAccTooLarge.1323ModRefInfo MRI = BAA.getModRefInfo(CI, MemoryLocation::get(SI));1324if (isModOrRefSet(MRI))1325return false;1326}1327}1328}1329return true;1330}13311332assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");13331334// We've established mechanical ability and aliasing, it's up to the caller1335// to check fault safety1336return true;1337}13381339/// Returns true if a PHINode is a trivially replaceable with an1340/// Instruction.1341/// This is true when all incoming values are that instruction.1342/// This pattern occurs most often with LCSSA PHI nodes.1343///1344static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {1345for (const Value *IncValue : PN.incoming_values())1346if (IncValue != &I)1347return false;13481349return true;1350}13511352/// Return true if the instruction is foldable in the loop.1353static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop,1354const TargetTransformInfo *TTI) {1355if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {1356InstructionCost CostI =1357TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);1358if (CostI != TargetTransformInfo::TCC_Free)1359return false;1360// For a GEP, we cannot simply use getInstructionCost because currently1361// it optimistically assumes that a GEP will fold into addressing mode1362// regardless of its users.1363const BasicBlock *BB = GEP->getParent();1364for (const User *U : GEP->users()) {1365const Instruction *UI = cast<Instruction>(U);1366if (CurLoop->contains(UI) &&1367(BB != UI->getParent() ||1368(!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))1369return false;1370}1371return true;1372}13731374return false;1375}13761377/// Return true if the only users of this instruction are outside of1378/// the loop. If this is true, we can sink the instruction to the exit1379/// blocks of the loop.1380///1381/// We also return true if the instruction could be folded away in lowering.1382/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).1383static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,1384const LoopSafetyInfo *SafetyInfo,1385TargetTransformInfo *TTI,1386bool &FoldableInLoop, bool LoopNestMode) {1387const auto &BlockColors = SafetyInfo->getBlockColors();1388bool IsFoldable = isFoldableInLoop(I, CurLoop, TTI);1389for (const User *U : I.users()) {1390const Instruction *UI = cast<Instruction>(U);1391if (const PHINode *PN = dyn_cast<PHINode>(UI)) {1392const BasicBlock *BB = PN->getParent();1393// We cannot sink uses in catchswitches.1394if (isa<CatchSwitchInst>(BB->getTerminator()))1395return false;13961397// We need to sink a callsite to a unique funclet. Avoid sinking if the1398// phi use is too muddled.1399if (isa<CallInst>(I))1400if (!BlockColors.empty() &&1401BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)1402return false;14031404if (LoopNestMode) {1405while (isa<PHINode>(UI) && UI->hasOneUser() &&1406UI->getNumOperands() == 1) {1407if (!CurLoop->contains(UI))1408break;1409UI = cast<Instruction>(UI->user_back());1410}1411}1412}14131414if (CurLoop->contains(UI)) {1415if (IsFoldable) {1416FoldableInLoop = true;1417continue;1418}1419return false;1420}1421}1422return true;1423}14241425static Instruction *cloneInstructionInExitBlock(1426Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,1427const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU) {1428Instruction *New;1429if (auto *CI = dyn_cast<CallInst>(&I)) {1430const auto &BlockColors = SafetyInfo->getBlockColors();14311432// Sinking call-sites need to be handled differently from other1433// instructions. The cloned call-site needs a funclet bundle operand1434// appropriate for its location in the CFG.1435SmallVector<OperandBundleDef, 1> OpBundles;1436for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();1437BundleIdx != BundleEnd; ++BundleIdx) {1438OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);1439if (Bundle.getTagID() == LLVMContext::OB_funclet)1440continue;14411442OpBundles.emplace_back(Bundle);1443}14441445if (!BlockColors.empty()) {1446const ColorVector &CV = BlockColors.find(&ExitBlock)->second;1447assert(CV.size() == 1 && "non-unique color for exit block!");1448BasicBlock *BBColor = CV.front();1449Instruction *EHPad = BBColor->getFirstNonPHI();1450if (EHPad->isEHPad())1451OpBundles.emplace_back("funclet", EHPad);1452}14531454New = CallInst::Create(CI, OpBundles);1455New->copyMetadata(*CI);1456} else {1457New = I.clone();1458}14591460New->insertInto(&ExitBlock, ExitBlock.getFirstInsertionPt());1461if (!I.getName().empty())1462New->setName(I.getName() + ".le");14631464if (MSSAU.getMemorySSA()->getMemoryAccess(&I)) {1465// Create a new MemoryAccess and let MemorySSA set its defining access.1466// After running some passes, MemorySSA might be outdated, and the1467// instruction `I` may have become a non-memory touching instruction.1468MemoryAccess *NewMemAcc = MSSAU.createMemoryAccessInBB(1469New, nullptr, New->getParent(), MemorySSA::Beginning,1470/*CreationMustSucceed=*/false);1471if (NewMemAcc) {1472if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))1473MSSAU.insertDef(MemDef, /*RenameUses=*/true);1474else {1475auto *MemUse = cast<MemoryUse>(NewMemAcc);1476MSSAU.insertUse(MemUse, /*RenameUses=*/true);1477}1478}1479}14801481// Build LCSSA PHI nodes for any in-loop operands (if legal). Note that1482// this is particularly cheap because we can rip off the PHI node that we're1483// replacing for the number and blocks of the predecessors.1484// OPT: If this shows up in a profile, we can instead finish sinking all1485// invariant instructions, and then walk their operands to re-establish1486// LCSSA. That will eliminate creating PHI nodes just to nuke them when1487// sinking bottom-up.1488for (Use &Op : New->operands())1489if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {1490auto *OInst = cast<Instruction>(Op.get());1491PHINode *OpPN =1492PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),1493OInst->getName() + ".lcssa");1494OpPN->insertBefore(ExitBlock.begin());1495for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)1496OpPN->addIncoming(OInst, PN.getIncomingBlock(i));1497Op = OpPN;1498}1499return New;1500}15011502static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,1503MemorySSAUpdater &MSSAU) {1504MSSAU.removeMemoryAccess(&I);1505SafetyInfo.removeInstruction(&I);1506I.eraseFromParent();1507}15081509static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest,1510ICFLoopSafetyInfo &SafetyInfo,1511MemorySSAUpdater &MSSAU,1512ScalarEvolution *SE) {1513SafetyInfo.removeInstruction(&I);1514SafetyInfo.insertInstructionTo(&I, Dest->getParent());1515I.moveBefore(*Dest->getParent(), Dest);1516if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(1517MSSAU.getMemorySSA()->getMemoryAccess(&I)))1518MSSAU.moveToPlace(OldMemAcc, Dest->getParent(),1519MemorySSA::BeforeTerminator);1520if (SE)1521SE->forgetBlockAndLoopDispositions(&I);1522}15231524static Instruction *sinkThroughTriviallyReplaceablePHI(1525PHINode *TPN, Instruction *I, LoopInfo *LI,1526SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,1527const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,1528MemorySSAUpdater &MSSAU) {1529assert(isTriviallyReplaceablePHI(*TPN, *I) &&1530"Expect only trivially replaceable PHI");1531BasicBlock *ExitBlock = TPN->getParent();1532Instruction *New;1533auto It = SunkCopies.find(ExitBlock);1534if (It != SunkCopies.end())1535New = It->second;1536else1537New = SunkCopies[ExitBlock] = cloneInstructionInExitBlock(1538*I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);1539return New;1540}15411542static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {1543BasicBlock *BB = PN->getParent();1544if (!BB->canSplitPredecessors())1545return false;1546// It's not impossible to split EHPad blocks, but if BlockColors already exist1547// it require updating BlockColors for all offspring blocks accordingly. By1548// skipping such corner case, we can make updating BlockColors after splitting1549// predecessor fairly simple.1550if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())1551return false;1552for (BasicBlock *BBPred : predecessors(BB)) {1553if (isa<IndirectBrInst>(BBPred->getTerminator()))1554return false;1555}1556return true;1557}15581559static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,1560LoopInfo *LI, const Loop *CurLoop,1561LoopSafetyInfo *SafetyInfo,1562MemorySSAUpdater *MSSAU) {1563#ifndef NDEBUG1564SmallVector<BasicBlock *, 32> ExitBlocks;1565CurLoop->getUniqueExitBlocks(ExitBlocks);1566SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),1567ExitBlocks.end());1568#endif1569BasicBlock *ExitBB = PN->getParent();1570assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");15711572// Split predecessors of the loop exit to make instructions in the loop are1573// exposed to exit blocks through trivially replaceable PHIs while keeping the1574// loop in the canonical form where each predecessor of each exit block should1575// be contained within the loop. For example, this will convert the loop below1576// from1577//1578// LB1:1579// %v1 =1580// br %LE, %LB21581// LB2:1582// %v2 =1583// br %LE, %LB11584// LE:1585// %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable1586//1587// to1588//1589// LB1:1590// %v1 =1591// br %LE.split, %LB21592// LB2:1593// %v2 =1594// br %LE.split2, %LB11595// LE.split:1596// %p1 = phi [%v1, %LB1] <-- trivially replaceable1597// br %LE1598// LE.split2:1599// %p2 = phi [%v2, %LB2] <-- trivially replaceable1600// br %LE1601// LE:1602// %p = phi [%p1, %LE.split], [%p2, %LE.split2]1603//1604const auto &BlockColors = SafetyInfo->getBlockColors();1605SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));1606while (!PredBBs.empty()) {1607BasicBlock *PredBB = *PredBBs.begin();1608assert(CurLoop->contains(PredBB) &&1609"Expect all predecessors are in the loop");1610if (PN->getBasicBlockIndex(PredBB) >= 0) {1611BasicBlock *NewPred = SplitBlockPredecessors(1612ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);1613// Since we do not allow splitting EH-block with BlockColors in1614// canSplitPredecessors(), we can simply assign predecessor's color to1615// the new block.1616if (!BlockColors.empty())1617// Grab a reference to the ColorVector to be inserted before getting the1618// reference to the vector we are copying because inserting the new1619// element in BlockColors might cause the map to be reallocated.1620SafetyInfo->copyColors(NewPred, PredBB);1621}1622PredBBs.remove(PredBB);1623}1624}16251626/// When an instruction is found to only be used outside of the loop, this1627/// function moves it to the exit blocks and patches up SSA form as needed.1628/// This method is guaranteed to remove the original instruction from its1629/// position, and may either delete it or move it to outside of the loop.1630///1631static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,1632const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,1633MemorySSAUpdater &MSSAU, OptimizationRemarkEmitter *ORE) {1634bool Changed = false;1635LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");16361637// Iterate over users to be ready for actual sinking. Replace users via1638// unreachable blocks with undef and make all user PHIs trivially replaceable.1639SmallPtrSet<Instruction *, 8> VisitedUsers;1640for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {1641auto *User = cast<Instruction>(*UI);1642Use &U = UI.getUse();1643++UI;16441645if (VisitedUsers.count(User) || CurLoop->contains(User))1646continue;16471648if (!DT->isReachableFromEntry(User->getParent())) {1649U = PoisonValue::get(I.getType());1650Changed = true;1651continue;1652}16531654// The user must be a PHI node.1655PHINode *PN = cast<PHINode>(User);16561657// Surprisingly, instructions can be used outside of loops without any1658// exits. This can only happen in PHI nodes if the incoming block is1659// unreachable.1660BasicBlock *BB = PN->getIncomingBlock(U);1661if (!DT->isReachableFromEntry(BB)) {1662U = PoisonValue::get(I.getType());1663Changed = true;1664continue;1665}16661667VisitedUsers.insert(PN);1668if (isTriviallyReplaceablePHI(*PN, I))1669continue;16701671if (!canSplitPredecessors(PN, SafetyInfo))1672return Changed;16731674// Split predecessors of the PHI so that we can make users trivially1675// replaceable.1676splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, &MSSAU);16771678// Should rebuild the iterators, as they may be invalidated by1679// splitPredecessorsOfLoopExit().1680UI = I.user_begin();1681UE = I.user_end();1682}16831684if (VisitedUsers.empty())1685return Changed;16861687ORE->emit([&]() {1688return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)1689<< "sinking " << ore::NV("Inst", &I);1690});1691if (isa<LoadInst>(I))1692++NumMovedLoads;1693else if (isa<CallInst>(I))1694++NumMovedCalls;1695++NumSunk;16961697#ifndef NDEBUG1698SmallVector<BasicBlock *, 32> ExitBlocks;1699CurLoop->getUniqueExitBlocks(ExitBlocks);1700SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),1701ExitBlocks.end());1702#endif17031704// Clones of this instruction. Don't create more than one per exit block!1705SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;17061707// If this instruction is only used outside of the loop, then all users are1708// PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of1709// the instruction.1710// First check if I is worth sinking for all uses. Sink only when it is worth1711// across all uses.1712SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());1713for (auto *UI : Users) {1714auto *User = cast<Instruction>(UI);17151716if (CurLoop->contains(User))1717continue;17181719PHINode *PN = cast<PHINode>(User);1720assert(ExitBlockSet.count(PN->getParent()) &&1721"The LCSSA PHI is not in an exit block!");17221723// The PHI must be trivially replaceable.1724Instruction *New = sinkThroughTriviallyReplaceablePHI(1725PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);1726// As we sink the instruction out of the BB, drop its debug location.1727New->dropLocation();1728PN->replaceAllUsesWith(New);1729eraseInstruction(*PN, *SafetyInfo, MSSAU);1730Changed = true;1731}1732return Changed;1733}17341735/// When an instruction is found to only use loop invariant operands that1736/// is safe to hoist, this instruction is called to do the dirty work.1737///1738static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,1739BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,1740MemorySSAUpdater &MSSAU, ScalarEvolution *SE,1741OptimizationRemarkEmitter *ORE) {1742LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "1743<< I << "\n");1744ORE->emit([&]() {1745return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "1746<< ore::NV("Inst", &I);1747});17481749// Metadata can be dependent on conditions we are hoisting above.1750// Conservatively strip all metadata on the instruction unless we were1751// guaranteed to execute I if we entered the loop, in which case the metadata1752// is valid in the loop preheader.1753// Similarly, If I is a call and it is not guaranteed to execute in the loop,1754// then moving to the preheader means we should strip attributes on the call1755// that can cause UB since we may be hoisting above conditions that allowed1756// inferring those attributes. They may not be valid at the preheader.1757if ((I.hasMetadataOtherThanDebugLoc() || isa<CallInst>(I)) &&1758// The check on hasMetadataOtherThanDebugLoc is to prevent us from burning1759// time in isGuaranteedToExecute if we don't actually have anything to1760// drop. It is a compile time optimization, not required for correctness.1761!SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))1762I.dropUBImplyingAttrsAndMetadata();17631764if (isa<PHINode>(I))1765// Move the new node to the end of the phi list in the destination block.1766moveInstructionBefore(I, Dest->getFirstNonPHIIt(), *SafetyInfo, MSSAU, SE);1767else1768// Move the new node to the destination block, before its terminator.1769moveInstructionBefore(I, Dest->getTerminator()->getIterator(), *SafetyInfo,1770MSSAU, SE);17711772I.updateLocationAfterHoist();17731774if (isa<LoadInst>(I))1775++NumMovedLoads;1776else if (isa<CallInst>(I))1777++NumMovedCalls;1778++NumHoisted;1779}17801781/// Only sink or hoist an instruction if it is not a trapping instruction,1782/// or if the instruction is known not to trap when moved to the preheader.1783/// or if it is a trapping instruction and is guaranteed to execute.1784static bool isSafeToExecuteUnconditionally(1785Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,1786const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,1787OptimizationRemarkEmitter *ORE, const Instruction *CtxI,1788AssumptionCache *AC, bool AllowSpeculation) {1789if (AllowSpeculation &&1790isSafeToSpeculativelyExecute(&Inst, CtxI, AC, DT, TLI))1791return true;17921793bool GuaranteedToExecute =1794SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);17951796if (!GuaranteedToExecute) {1797auto *LI = dyn_cast<LoadInst>(&Inst);1798if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))1799ORE->emit([&]() {1800return OptimizationRemarkMissed(1801DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)1802<< "failed to hoist load with loop-invariant address "1803"because load is conditionally executed";1804});1805}18061807return GuaranteedToExecute;1808}18091810namespace {1811class LoopPromoter : public LoadAndStorePromoter {1812Value *SomePtr; // Designated pointer to store to.1813SmallVectorImpl<BasicBlock *> &LoopExitBlocks;1814SmallVectorImpl<BasicBlock::iterator> &LoopInsertPts;1815SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;1816PredIteratorCache &PredCache;1817MemorySSAUpdater &MSSAU;1818LoopInfo &LI;1819DebugLoc DL;1820Align Alignment;1821bool UnorderedAtomic;1822AAMDNodes AATags;1823ICFLoopSafetyInfo &SafetyInfo;1824bool CanInsertStoresInExitBlocks;1825ArrayRef<const Instruction *> Uses;18261827// We're about to add a use of V in a loop exit block. Insert an LCSSA phi1828// (if legal) if doing so would add an out-of-loop use to an instruction1829// defined in-loop.1830Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {1831if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))1832return V;18331834Instruction *I = cast<Instruction>(V);1835// We need to create an LCSSA PHI node for the incoming value and1836// store that.1837PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),1838I->getName() + ".lcssa");1839PN->insertBefore(BB->begin());1840for (BasicBlock *Pred : PredCache.get(BB))1841PN->addIncoming(I, Pred);1842return PN;1843}18441845public:1846LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,1847SmallVectorImpl<BasicBlock *> &LEB,1848SmallVectorImpl<BasicBlock::iterator> &LIP,1849SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,1850MemorySSAUpdater &MSSAU, LoopInfo &li, DebugLoc dl,1851Align Alignment, bool UnorderedAtomic, const AAMDNodes &AATags,1852ICFLoopSafetyInfo &SafetyInfo, bool CanInsertStoresInExitBlocks)1853: LoadAndStorePromoter(Insts, S), SomePtr(SP), LoopExitBlocks(LEB),1854LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), PredCache(PIC), MSSAU(MSSAU),1855LI(li), DL(std::move(dl)), Alignment(Alignment),1856UnorderedAtomic(UnorderedAtomic), AATags(AATags),1857SafetyInfo(SafetyInfo),1858CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks), Uses(Insts) {}18591860void insertStoresInLoopExitBlocks() {1861// Insert stores after in the loop exit blocks. Each exit block gets a1862// store of the live-out values that feed them. Since we've already told1863// the SSA updater about the defs in the loop and the preheader1864// definition, it is all set and we can start using it.1865DIAssignID *NewID = nullptr;1866for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {1867BasicBlock *ExitBlock = LoopExitBlocks[i];1868Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);1869LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);1870Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);1871BasicBlock::iterator InsertPos = LoopInsertPts[i];1872StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);1873if (UnorderedAtomic)1874NewSI->setOrdering(AtomicOrdering::Unordered);1875NewSI->setAlignment(Alignment);1876NewSI->setDebugLoc(DL);1877// Attach DIAssignID metadata to the new store, generating it on the1878// first loop iteration.1879if (i == 0) {1880// NewSI will have its DIAssignID set here if there are any stores in1881// Uses with a DIAssignID attachment. This merged ID will then be1882// attached to the other inserted stores (in the branch below).1883NewSI->mergeDIAssignID(Uses);1884NewID = cast_or_null<DIAssignID>(1885NewSI->getMetadata(LLVMContext::MD_DIAssignID));1886} else {1887// Attach the DIAssignID (or nullptr) merged from Uses in the branch1888// above.1889NewSI->setMetadata(LLVMContext::MD_DIAssignID, NewID);1890}18911892if (AATags)1893NewSI->setAAMetadata(AATags);18941895MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];1896MemoryAccess *NewMemAcc;1897if (!MSSAInsertPoint) {1898NewMemAcc = MSSAU.createMemoryAccessInBB(1899NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);1900} else {1901NewMemAcc =1902MSSAU.createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);1903}1904MSSAInsertPts[i] = NewMemAcc;1905MSSAU.insertDef(cast<MemoryDef>(NewMemAcc), true);1906// FIXME: true for safety, false may still be correct.1907}1908}19091910void doExtraRewritesBeforeFinalDeletion() override {1911if (CanInsertStoresInExitBlocks)1912insertStoresInLoopExitBlocks();1913}19141915void instructionDeleted(Instruction *I) const override {1916SafetyInfo.removeInstruction(I);1917MSSAU.removeMemoryAccess(I);1918}19191920bool shouldDelete(Instruction *I) const override {1921if (isa<StoreInst>(I))1922return CanInsertStoresInExitBlocks;1923return true;1924}1925};19261927bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,1928DominatorTree *DT) {1929// We can perform the captured-before check against any instruction in the1930// loop header, as the loop header is reachable from any instruction inside1931// the loop.1932// TODO: ReturnCaptures=true shouldn't be necessary here.1933return !PointerMayBeCapturedBefore(V, /* ReturnCaptures */ true,1934/* StoreCaptures */ true,1935L->getHeader()->getTerminator(), DT);1936}19371938/// Return true if we can prove that a caller cannot inspect the object if an1939/// unwind occurs inside the loop.1940bool isNotVisibleOnUnwindInLoop(const Value *Object, const Loop *L,1941DominatorTree *DT) {1942bool RequiresNoCaptureBeforeUnwind;1943if (!isNotVisibleOnUnwind(Object, RequiresNoCaptureBeforeUnwind))1944return false;19451946return !RequiresNoCaptureBeforeUnwind ||1947isNotCapturedBeforeOrInLoop(Object, L, DT);1948}19491950bool isThreadLocalObject(const Value *Object, const Loop *L, DominatorTree *DT,1951TargetTransformInfo *TTI) {1952// The object must be function-local to start with, and then not captured1953// before/in the loop.1954return (isIdentifiedFunctionLocal(Object) &&1955isNotCapturedBeforeOrInLoop(Object, L, DT)) ||1956(TTI->isSingleThreaded() || SingleThread);1957}19581959} // namespace19601961/// Try to promote memory values to scalars by sinking stores out of the1962/// loop and moving loads to before the loop. We do this by looping over1963/// the stores in the loop, looking for stores to Must pointers which are1964/// loop invariant.1965///1966bool llvm::promoteLoopAccessesToScalars(1967const SmallSetVector<Value *, 8> &PointerMustAliases,1968SmallVectorImpl<BasicBlock *> &ExitBlocks,1969SmallVectorImpl<BasicBlock::iterator> &InsertPts,1970SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,1971LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,1972const TargetLibraryInfo *TLI, TargetTransformInfo *TTI, Loop *CurLoop,1973MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,1974OptimizationRemarkEmitter *ORE, bool AllowSpeculation,1975bool HasReadsOutsideSet) {1976// Verify inputs.1977assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&1978SafetyInfo != nullptr &&1979"Unexpected Input to promoteLoopAccessesToScalars");19801981LLVM_DEBUG({1982dbgs() << "Trying to promote set of must-aliased pointers:\n";1983for (Value *Ptr : PointerMustAliases)1984dbgs() << " " << *Ptr << "\n";1985});1986++NumPromotionCandidates;19871988Value *SomePtr = *PointerMustAliases.begin();1989BasicBlock *Preheader = CurLoop->getLoopPreheader();19901991// It is not safe to promote a load/store from the loop if the load/store is1992// conditional. For example, turning:1993//1994// for () { if (c) *P += 1; }1995//1996// into:1997//1998// tmp = *P; for () { if (c) tmp +=1; } *P = tmp;1999//2000// is not safe, because *P may only be valid to access if 'c' is true.2001//2002// The safety property divides into two parts:2003// p1) The memory may not be dereferenceable on entry to the loop. In this2004// case, we can't insert the required load in the preheader.2005// p2) The memory model does not allow us to insert a store along any dynamic2006// path which did not originally have one.2007//2008// If at least one store is guaranteed to execute, both properties are2009// satisfied, and promotion is legal.2010//2011// This, however, is not a necessary condition. Even if no store/load is2012// guaranteed to execute, we can still establish these properties.2013// We can establish (p1) by proving that hoisting the load into the preheader2014// is safe (i.e. proving dereferenceability on all paths through the loop). We2015// can use any access within the alias set to prove dereferenceability,2016// since they're all must alias.2017//2018// There are two ways establish (p2):2019// a) Prove the location is thread-local. In this case the memory model2020// requirement does not apply, and stores are safe to insert.2021// b) Prove a store dominates every exit block. In this case, if an exit2022// blocks is reached, the original dynamic path would have taken us through2023// the store, so inserting a store into the exit block is safe. Note that this2024// is different from the store being guaranteed to execute. For instance,2025// if an exception is thrown on the first iteration of the loop, the original2026// store is never executed, but the exit blocks are not executed either.20272028bool DereferenceableInPH = false;2029bool StoreIsGuanteedToExecute = false;2030bool FoundLoadToPromote = false;2031// Goes from Unknown to either Safe or Unsafe, but can't switch between them.2032enum {2033StoreSafe,2034StoreUnsafe,2035StoreSafetyUnknown,2036} StoreSafety = StoreSafetyUnknown;20372038SmallVector<Instruction *, 64> LoopUses;20392040// We start with an alignment of one and try to find instructions that allow2041// us to prove better alignment.2042Align Alignment;2043// Keep track of which types of access we see2044bool SawUnorderedAtomic = false;2045bool SawNotAtomic = false;2046AAMDNodes AATags;20472048const DataLayout &MDL = Preheader->getDataLayout();20492050// If there are reads outside the promoted set, then promoting stores is2051// definitely not safe.2052if (HasReadsOutsideSet)2053StoreSafety = StoreUnsafe;20542055if (StoreSafety == StoreSafetyUnknown && SafetyInfo->anyBlockMayThrow()) {2056// If a loop can throw, we have to insert a store along each unwind edge.2057// That said, we can't actually make the unwind edge explicit. Therefore,2058// we have to prove that the store is dead along the unwind edge. We do2059// this by proving that the caller can't have a reference to the object2060// after return and thus can't possibly load from the object.2061Value *Object = getUnderlyingObject(SomePtr);2062if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, DT))2063StoreSafety = StoreUnsafe;2064}20652066// Check that all accesses to pointers in the alias set use the same type.2067// We cannot (yet) promote a memory location that is loaded and stored in2068// different sizes. While we are at it, collect alignment and AA info.2069Type *AccessTy = nullptr;2070for (Value *ASIV : PointerMustAliases) {2071for (Use &U : ASIV->uses()) {2072// Ignore instructions that are outside the loop.2073Instruction *UI = dyn_cast<Instruction>(U.getUser());2074if (!UI || !CurLoop->contains(UI))2075continue;20762077// If there is an non-load/store instruction in the loop, we can't promote2078// it.2079if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {2080if (!Load->isUnordered())2081return false;20822083SawUnorderedAtomic |= Load->isAtomic();2084SawNotAtomic |= !Load->isAtomic();2085FoundLoadToPromote = true;20862087Align InstAlignment = Load->getAlign();20882089// Note that proving a load safe to speculate requires proving2090// sufficient alignment at the target location. Proving it guaranteed2091// to execute does as well. Thus we can increase our guaranteed2092// alignment as well.2093if (!DereferenceableInPH || (InstAlignment > Alignment))2094if (isSafeToExecuteUnconditionally(2095*Load, DT, TLI, CurLoop, SafetyInfo, ORE,2096Preheader->getTerminator(), AC, AllowSpeculation)) {2097DereferenceableInPH = true;2098Alignment = std::max(Alignment, InstAlignment);2099}2100} else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {2101// Stores *of* the pointer are not interesting, only stores *to* the2102// pointer.2103if (U.getOperandNo() != StoreInst::getPointerOperandIndex())2104continue;2105if (!Store->isUnordered())2106return false;21072108SawUnorderedAtomic |= Store->isAtomic();2109SawNotAtomic |= !Store->isAtomic();21102111// If the store is guaranteed to execute, both properties are satisfied.2112// We may want to check if a store is guaranteed to execute even if we2113// already know that promotion is safe, since it may have higher2114// alignment than any other guaranteed stores, in which case we can2115// raise the alignment on the promoted store.2116Align InstAlignment = Store->getAlign();2117bool GuaranteedToExecute =2118SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop);2119StoreIsGuanteedToExecute |= GuaranteedToExecute;2120if (GuaranteedToExecute) {2121DereferenceableInPH = true;2122if (StoreSafety == StoreSafetyUnknown)2123StoreSafety = StoreSafe;2124Alignment = std::max(Alignment, InstAlignment);2125}21262127// If a store dominates all exit blocks, it is safe to sink.2128// As explained above, if an exit block was executed, a dominating2129// store must have been executed at least once, so we are not2130// introducing stores on paths that did not have them.2131// Note that this only looks at explicit exit blocks. If we ever2132// start sinking stores into unwind edges (see above), this will break.2133if (StoreSafety == StoreSafetyUnknown &&2134llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {2135return DT->dominates(Store->getParent(), Exit);2136}))2137StoreSafety = StoreSafe;21382139// If the store is not guaranteed to execute, we may still get2140// deref info through it.2141if (!DereferenceableInPH) {2142DereferenceableInPH = isDereferenceableAndAlignedPointer(2143Store->getPointerOperand(), Store->getValueOperand()->getType(),2144Store->getAlign(), MDL, Preheader->getTerminator(), AC, DT, TLI);2145}2146} else2147continue; // Not a load or store.21482149if (!AccessTy)2150AccessTy = getLoadStoreType(UI);2151else if (AccessTy != getLoadStoreType(UI))2152return false;21532154// Merge the AA tags.2155if (LoopUses.empty()) {2156// On the first load/store, just take its AA tags.2157AATags = UI->getAAMetadata();2158} else if (AATags) {2159AATags = AATags.merge(UI->getAAMetadata());2160}21612162LoopUses.push_back(UI);2163}2164}21652166// If we found both an unordered atomic instruction and a non-atomic memory2167// access, bail. We can't blindly promote non-atomic to atomic since we2168// might not be able to lower the result. We can't downgrade since that2169// would violate memory model. Also, align 0 is an error for atomics.2170if (SawUnorderedAtomic && SawNotAtomic)2171return false;21722173// If we're inserting an atomic load in the preheader, we must be able to2174// lower it. We're only guaranteed to be able to lower naturally aligned2175// atomics.2176if (SawUnorderedAtomic && Alignment < MDL.getTypeStoreSize(AccessTy))2177return false;21782179// If we couldn't prove we can hoist the load, bail.2180if (!DereferenceableInPH) {2181LLVM_DEBUG(dbgs() << "Not promoting: Not dereferenceable in preheader\n");2182return false;2183}21842185// We know we can hoist the load, but don't have a guaranteed store.2186// Check whether the location is writable and thread-local. If it is, then we2187// can insert stores along paths which originally didn't have them without2188// violating the memory model.2189if (StoreSafety == StoreSafetyUnknown) {2190Value *Object = getUnderlyingObject(SomePtr);2191bool ExplicitlyDereferenceableOnly;2192if (isWritableObject(Object, ExplicitlyDereferenceableOnly) &&2193(!ExplicitlyDereferenceableOnly ||2194isDereferenceablePointer(SomePtr, AccessTy, MDL)) &&2195isThreadLocalObject(Object, CurLoop, DT, TTI))2196StoreSafety = StoreSafe;2197}21982199// If we've still failed to prove we can sink the store, hoist the load2200// only, if possible.2201if (StoreSafety != StoreSafe && !FoundLoadToPromote)2202// If we cannot hoist the load either, give up.2203return false;22042205// Lets do the promotion!2206if (StoreSafety == StoreSafe) {2207LLVM_DEBUG(dbgs() << "LICM: Promoting load/store of the value: " << *SomePtr2208<< '\n');2209++NumLoadStorePromoted;2210} else {2211LLVM_DEBUG(dbgs() << "LICM: Promoting load of the value: " << *SomePtr2212<< '\n');2213++NumLoadPromoted;2214}22152216ORE->emit([&]() {2217return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",2218LoopUses[0])2219<< "Moving accesses to memory location out of the loop";2220});22212222// Look at all the loop uses, and try to merge their locations.2223std::vector<DILocation *> LoopUsesLocs;2224for (auto *U : LoopUses)2225LoopUsesLocs.push_back(U->getDebugLoc().get());2226auto DL = DebugLoc(DILocation::getMergedLocations(LoopUsesLocs));22272228// We use the SSAUpdater interface to insert phi nodes as required.2229SmallVector<PHINode *, 16> NewPHIs;2230SSAUpdater SSA(&NewPHIs);2231LoopPromoter Promoter(SomePtr, LoopUses, SSA, ExitBlocks, InsertPts,2232MSSAInsertPts, PIC, MSSAU, *LI, DL, Alignment,2233SawUnorderedAtomic, AATags, *SafetyInfo,2234StoreSafety == StoreSafe);22352236// Set up the preheader to have a definition of the value. It is the live-out2237// value from the preheader that uses in the loop will use.2238LoadInst *PreheaderLoad = nullptr;2239if (FoundLoadToPromote || !StoreIsGuanteedToExecute) {2240PreheaderLoad =2241new LoadInst(AccessTy, SomePtr, SomePtr->getName() + ".promoted",2242Preheader->getTerminator()->getIterator());2243if (SawUnorderedAtomic)2244PreheaderLoad->setOrdering(AtomicOrdering::Unordered);2245PreheaderLoad->setAlignment(Alignment);2246PreheaderLoad->setDebugLoc(DebugLoc());2247if (AATags)2248PreheaderLoad->setAAMetadata(AATags);22492250MemoryAccess *PreheaderLoadMemoryAccess = MSSAU.createMemoryAccessInBB(2251PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);2252MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);2253MSSAU.insertUse(NewMemUse, /*RenameUses=*/true);2254SSA.AddAvailableValue(Preheader, PreheaderLoad);2255} else {2256SSA.AddAvailableValue(Preheader, PoisonValue::get(AccessTy));2257}22582259if (VerifyMemorySSA)2260MSSAU.getMemorySSA()->verifyMemorySSA();2261// Rewrite all the loads in the loop and remember all the definitions from2262// stores in the loop.2263Promoter.run(LoopUses);22642265if (VerifyMemorySSA)2266MSSAU.getMemorySSA()->verifyMemorySSA();2267// If the SSAUpdater didn't use the load in the preheader, just zap it now.2268if (PreheaderLoad && PreheaderLoad->use_empty())2269eraseInstruction(*PreheaderLoad, *SafetyInfo, MSSAU);22702271return true;2272}22732274static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,2275function_ref<void(Instruction *)> Fn) {2276for (const BasicBlock *BB : L->blocks())2277if (const auto *Accesses = MSSA->getBlockAccesses(BB))2278for (const auto &Access : *Accesses)2279if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))2280Fn(MUD->getMemoryInst());2281}22822283// The bool indicates whether there might be reads outside the set, in which2284// case only loads may be promoted.2285static SmallVector<PointersAndHasReadsOutsideSet, 0>2286collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L) {2287BatchAAResults BatchAA(*AA);2288AliasSetTracker AST(BatchAA);22892290auto IsPotentiallyPromotable = [L](const Instruction *I) {2291if (const auto *SI = dyn_cast<StoreInst>(I))2292return L->isLoopInvariant(SI->getPointerOperand());2293if (const auto *LI = dyn_cast<LoadInst>(I))2294return L->isLoopInvariant(LI->getPointerOperand());2295return false;2296};22972298// Populate AST with potentially promotable accesses.2299SmallPtrSet<Value *, 16> AttemptingPromotion;2300foreachMemoryAccess(MSSA, L, [&](Instruction *I) {2301if (IsPotentiallyPromotable(I)) {2302AttemptingPromotion.insert(I);2303AST.add(I);2304}2305});23062307// We're only interested in must-alias sets that contain a mod.2308SmallVector<PointerIntPair<const AliasSet *, 1, bool>, 8> Sets;2309for (AliasSet &AS : AST)2310if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())2311Sets.push_back({&AS, false});23122313if (Sets.empty())2314return {}; // Nothing to promote...23152316// Discard any sets for which there is an aliasing non-promotable access.2317foreachMemoryAccess(MSSA, L, [&](Instruction *I) {2318if (AttemptingPromotion.contains(I))2319return;23202321llvm::erase_if(Sets, [&](PointerIntPair<const AliasSet *, 1, bool> &Pair) {2322ModRefInfo MR = Pair.getPointer()->aliasesUnknownInst(I, BatchAA);2323// Cannot promote if there are writes outside the set.2324if (isModSet(MR))2325return true;2326if (isRefSet(MR)) {2327// Remember reads outside the set.2328Pair.setInt(true);2329// If this is a mod-only set and there are reads outside the set,2330// we will not be able to promote, so bail out early.2331return !Pair.getPointer()->isRef();2332}2333return false;2334});2335});23362337SmallVector<std::pair<SmallSetVector<Value *, 8>, bool>, 0> Result;2338for (auto [Set, HasReadsOutsideSet] : Sets) {2339SmallSetVector<Value *, 8> PointerMustAliases;2340for (const auto &MemLoc : *Set)2341PointerMustAliases.insert(const_cast<Value *>(MemLoc.Ptr));2342Result.emplace_back(std::move(PointerMustAliases), HasReadsOutsideSet);2343}23442345return Result;2346}23472348static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU,2349Loop *CurLoop, Instruction &I,2350SinkAndHoistLICMFlags &Flags,2351bool InvariantGroup) {2352// For hoisting, use the walker to determine safety2353if (!Flags.getIsSink()) {2354// If hoisting an invariant group, we only need to check that there2355// is no store to the loaded pointer between the start of the loop,2356// and the load (since all values must be the same).23572358// This can be checked in two conditions:2359// 1) if the memoryaccess is outside the loop2360// 2) the earliest access is at the loop header,2361// if the memory loaded is the phi node23622363BatchAAResults BAA(MSSA->getAA());2364MemoryAccess *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, MU);2365return !MSSA->isLiveOnEntryDef(Source) &&2366CurLoop->contains(Source->getBlock()) &&2367!(InvariantGroup && Source->getBlock() == CurLoop->getHeader() && isa<MemoryPhi>(Source));2368}23692370// For sinking, we'd need to check all Defs below this use. The getClobbering2371// call will look on the backedge of the loop, but will check aliasing with2372// the instructions on the previous iteration.2373// For example:2374// for (i ... )2375// load a[i] ( Use (LoE)2376// store a[i] ( 1 = Def (2), with 2 = Phi for the loop.2377// i++;2378// The load sees no clobbering inside the loop, as the backedge alias check2379// does phi translation, and will check aliasing against store a[i-1].2380// However sinking the load outside the loop, below the store is incorrect.23812382// For now, only sink if there are no Defs in the loop, and the existing ones2383// precede the use and are in the same block.2384// FIXME: Increase precision: Safe to sink if Use post dominates the Def;2385// needs PostDominatorTreeAnalysis.2386// FIXME: More precise: no Defs that alias this Use.2387if (Flags.tooManyMemoryAccesses())2388return true;2389for (auto *BB : CurLoop->getBlocks())2390if (pointerInvalidatedByBlock(*BB, *MSSA, *MU))2391return true;2392// When sinking, the source block may not be part of the loop so check it.2393if (!CurLoop->contains(&I))2394return pointerInvalidatedByBlock(*I.getParent(), *MSSA, *MU);23952396return false;2397}23982399bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA, MemoryUse &MU) {2400if (const auto *Accesses = MSSA.getBlockDefs(&BB))2401for (const auto &MA : *Accesses)2402if (const auto *MD = dyn_cast<MemoryDef>(&MA))2403if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))2404return true;2405return false;2406}24072408/// Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A <2409/// min(INV_1, INV_2)), if INV_1 and INV_2 are both loop invariants and their2410/// minimun can be computed outside of loop, and X is not a loop-invariant.2411static bool hoistMinMax(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,2412MemorySSAUpdater &MSSAU) {2413bool Inverse = false;2414using namespace PatternMatch;2415Value *Cond1, *Cond2;2416if (match(&I, m_LogicalOr(m_Value(Cond1), m_Value(Cond2)))) {2417Inverse = true;2418} else if (match(&I, m_LogicalAnd(m_Value(Cond1), m_Value(Cond2)))) {2419// Do nothing2420} else2421return false;24222423auto MatchICmpAgainstInvariant = [&](Value *C, ICmpInst::Predicate &P,2424Value *&LHS, Value *&RHS) {2425if (!match(C, m_OneUse(m_ICmp(P, m_Value(LHS), m_Value(RHS)))))2426return false;2427if (!LHS->getType()->isIntegerTy())2428return false;2429if (!ICmpInst::isRelational(P))2430return false;2431if (L.isLoopInvariant(LHS)) {2432std::swap(LHS, RHS);2433P = ICmpInst::getSwappedPredicate(P);2434}2435if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS))2436return false;2437if (Inverse)2438P = ICmpInst::getInversePredicate(P);2439return true;2440};2441ICmpInst::Predicate P1, P2;2442Value *LHS1, *LHS2, *RHS1, *RHS2;2443if (!MatchICmpAgainstInvariant(Cond1, P1, LHS1, RHS1) ||2444!MatchICmpAgainstInvariant(Cond2, P2, LHS2, RHS2))2445return false;2446if (P1 != P2 || LHS1 != LHS2)2447return false;24482449// Everything is fine, we can do the transform.2450bool UseMin = ICmpInst::isLT(P1) || ICmpInst::isLE(P1);2451assert(2452(UseMin || ICmpInst::isGT(P1) || ICmpInst::isGE(P1)) &&2453"Relational predicate is either less (or equal) or greater (or equal)!");2454Intrinsic::ID id = ICmpInst::isSigned(P1)2455? (UseMin ? Intrinsic::smin : Intrinsic::smax)2456: (UseMin ? Intrinsic::umin : Intrinsic::umax);2457auto *Preheader = L.getLoopPreheader();2458assert(Preheader && "Loop is not in simplify form?");2459IRBuilder<> Builder(Preheader->getTerminator());2460// We are about to create a new guaranteed use for RHS2 which might not exist2461// before (if it was a non-taken input of logical and/or instruction). If it2462// was poison, we need to freeze it. Note that no new use for LHS and RHS1 are2463// introduced, so they don't need this.2464if (isa<SelectInst>(I))2465RHS2 = Builder.CreateFreeze(RHS2, RHS2->getName() + ".fr");2466Value *NewRHS = Builder.CreateBinaryIntrinsic(2467id, RHS1, RHS2, nullptr, StringRef("invariant.") +2468(ICmpInst::isSigned(P1) ? "s" : "u") +2469(UseMin ? "min" : "max"));2470Builder.SetInsertPoint(&I);2471ICmpInst::Predicate P = P1;2472if (Inverse)2473P = ICmpInst::getInversePredicate(P);2474Value *NewCond = Builder.CreateICmp(P, LHS1, NewRHS);2475NewCond->takeName(&I);2476I.replaceAllUsesWith(NewCond);2477eraseInstruction(I, SafetyInfo, MSSAU);2478eraseInstruction(*cast<Instruction>(Cond1), SafetyInfo, MSSAU);2479eraseInstruction(*cast<Instruction>(Cond2), SafetyInfo, MSSAU);2480return true;2481}24822483/// Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if2484/// this allows hoisting the inner GEP.2485static bool hoistGEP(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,2486MemorySSAUpdater &MSSAU, AssumptionCache *AC,2487DominatorTree *DT) {2488auto *GEP = dyn_cast<GetElementPtrInst>(&I);2489if (!GEP)2490return false;24912492auto *Src = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());2493if (!Src || !Src->hasOneUse() || !L.contains(Src))2494return false;24952496Value *SrcPtr = Src->getPointerOperand();2497auto LoopInvariant = [&](Value *V) { return L.isLoopInvariant(V); };2498if (!L.isLoopInvariant(SrcPtr) || !all_of(GEP->indices(), LoopInvariant))2499return false;25002501// This can only happen if !AllowSpeculation, otherwise this would already be2502// handled.2503// FIXME: Should we respect AllowSpeculation in these reassociation folds?2504// The flag exists to prevent metadata dropping, which is not relevant here.2505if (all_of(Src->indices(), LoopInvariant))2506return false;25072508// The swapped GEPs are inbounds if both original GEPs are inbounds2509// and the sign of the offsets is the same. For simplicity, only2510// handle both offsets being non-negative.2511const DataLayout &DL = GEP->getDataLayout();2512auto NonNegative = [&](Value *V) {2513return isKnownNonNegative(V, SimplifyQuery(DL, DT, AC, GEP));2514};2515bool IsInBounds = Src->isInBounds() && GEP->isInBounds() &&2516all_of(Src->indices(), NonNegative) &&2517all_of(GEP->indices(), NonNegative);25182519BasicBlock *Preheader = L.getLoopPreheader();2520IRBuilder<> Builder(Preheader->getTerminator());2521Value *NewSrc = Builder.CreateGEP(GEP->getSourceElementType(), SrcPtr,2522SmallVector<Value *>(GEP->indices()),2523"invariant.gep", IsInBounds);2524Builder.SetInsertPoint(GEP);2525Value *NewGEP = Builder.CreateGEP(Src->getSourceElementType(), NewSrc,2526SmallVector<Value *>(Src->indices()), "gep",2527IsInBounds);2528GEP->replaceAllUsesWith(NewGEP);2529eraseInstruction(*GEP, SafetyInfo, MSSAU);2530eraseInstruction(*Src, SafetyInfo, MSSAU);2531return true;2532}25332534/// Try to turn things like "LV + C1 < C2" into "LV < C2 - C1". Here2535/// C1 and C2 are loop invariants and LV is a loop-variant.2536static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS,2537Value *InvariantRHS, ICmpInst &ICmp, Loop &L,2538ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,2539AssumptionCache *AC, DominatorTree *DT) {2540assert(ICmpInst::isSigned(Pred) && "Not supported yet!");2541assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");2542assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");25432544// Try to represent VariantLHS as sum of invariant and variant operands.2545using namespace PatternMatch;2546Value *VariantOp, *InvariantOp;2547if (!match(VariantLHS, m_NSWAdd(m_Value(VariantOp), m_Value(InvariantOp))))2548return false;25492550// LHS itself is a loop-variant, try to represent it in the form:2551// "VariantOp + InvariantOp". If it is possible, then we can reassociate.2552if (L.isLoopInvariant(VariantOp))2553std::swap(VariantOp, InvariantOp);2554if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))2555return false;25562557// In order to turn "LV + C1 < C2" into "LV < C2 - C1", we need to be able to2558// freely move values from left side of inequality to right side (just as in2559// normal linear arithmetics). Overflows make things much more complicated, so2560// we want to avoid this.2561auto &DL = L.getHeader()->getDataLayout();2562bool ProvedNoOverflowAfterReassociate =2563computeOverflowForSignedSub(InvariantRHS, InvariantOp,2564SimplifyQuery(DL, DT, AC, &ICmp)) ==2565llvm::OverflowResult::NeverOverflows;2566if (!ProvedNoOverflowAfterReassociate)2567return false;2568auto *Preheader = L.getLoopPreheader();2569assert(Preheader && "Loop is not in simplify form?");2570IRBuilder<> Builder(Preheader->getTerminator());2571Value *NewCmpOp = Builder.CreateSub(InvariantRHS, InvariantOp, "invariant.op",2572/*HasNUW*/ false, /*HasNSW*/ true);2573ICmp.setPredicate(Pred);2574ICmp.setOperand(0, VariantOp);2575ICmp.setOperand(1, NewCmpOp);2576eraseInstruction(cast<Instruction>(*VariantLHS), SafetyInfo, MSSAU);2577return true;2578}25792580/// Try to reassociate and hoist the following two patterns:2581/// LV - C1 < C2 --> LV < C1 + C2,2582/// C1 - LV < C2 --> LV > C1 - C2.2583static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS,2584Value *InvariantRHS, ICmpInst &ICmp, Loop &L,2585ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,2586AssumptionCache *AC, DominatorTree *DT) {2587assert(ICmpInst::isSigned(Pred) && "Not supported yet!");2588assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");2589assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");25902591// Try to represent VariantLHS as sum of invariant and variant operands.2592using namespace PatternMatch;2593Value *VariantOp, *InvariantOp;2594if (!match(VariantLHS, m_NSWSub(m_Value(VariantOp), m_Value(InvariantOp))))2595return false;25962597bool VariantSubtracted = false;2598// LHS itself is a loop-variant, try to represent it in the form:2599// "VariantOp + InvariantOp". If it is possible, then we can reassociate. If2600// the variant operand goes with minus, we use a slightly different scheme.2601if (L.isLoopInvariant(VariantOp)) {2602std::swap(VariantOp, InvariantOp);2603VariantSubtracted = true;2604Pred = ICmpInst::getSwappedPredicate(Pred);2605}2606if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))2607return false;26082609// In order to turn "LV - C1 < C2" into "LV < C2 + C1", we need to be able to2610// freely move values from left side of inequality to right side (just as in2611// normal linear arithmetics). Overflows make things much more complicated, so2612// we want to avoid this. Likewise, for "C1 - LV < C2" we need to prove that2613// "C1 - C2" does not overflow.2614auto &DL = L.getHeader()->getDataLayout();2615SimplifyQuery SQ(DL, DT, AC, &ICmp);2616if (VariantSubtracted) {2617// C1 - LV < C2 --> LV > C1 - C22618if (computeOverflowForSignedSub(InvariantOp, InvariantRHS, SQ) !=2619llvm::OverflowResult::NeverOverflows)2620return false;2621} else {2622// LV - C1 < C2 --> LV < C1 + C22623if (computeOverflowForSignedAdd(InvariantOp, InvariantRHS, SQ) !=2624llvm::OverflowResult::NeverOverflows)2625return false;2626}2627auto *Preheader = L.getLoopPreheader();2628assert(Preheader && "Loop is not in simplify form?");2629IRBuilder<> Builder(Preheader->getTerminator());2630Value *NewCmpOp =2631VariantSubtracted2632? Builder.CreateSub(InvariantOp, InvariantRHS, "invariant.op",2633/*HasNUW*/ false, /*HasNSW*/ true)2634: Builder.CreateAdd(InvariantOp, InvariantRHS, "invariant.op",2635/*HasNUW*/ false, /*HasNSW*/ true);2636ICmp.setPredicate(Pred);2637ICmp.setOperand(0, VariantOp);2638ICmp.setOperand(1, NewCmpOp);2639eraseInstruction(cast<Instruction>(*VariantLHS), SafetyInfo, MSSAU);2640return true;2641}26422643/// Reassociate and hoist add/sub expressions.2644static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,2645MemorySSAUpdater &MSSAU, AssumptionCache *AC,2646DominatorTree *DT) {2647using namespace PatternMatch;2648ICmpInst::Predicate Pred;2649Value *LHS, *RHS;2650if (!match(&I, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))2651return false;26522653// TODO: Support unsigned predicates?2654if (!ICmpInst::isSigned(Pred))2655return false;26562657// Put variant operand to LHS position.2658if (L.isLoopInvariant(LHS)) {2659std::swap(LHS, RHS);2660Pred = ICmpInst::getSwappedPredicate(Pred);2661}2662// We want to delete the initial operation after reassociation, so only do it2663// if it has no other uses.2664if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS) || !LHS->hasOneUse())2665return false;26662667// TODO: We could go with smarter context, taking common dominator of all I's2668// users instead of I itself.2669if (hoistAdd(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))2670return true;26712672if (hoistSub(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))2673return true;26742675return false;2676}26772678static bool isReassociableOp(Instruction *I, unsigned IntOpcode,2679unsigned FPOpcode) {2680if (I->getOpcode() == IntOpcode)2681return true;2682if (I->getOpcode() == FPOpcode && I->hasAllowReassoc() &&2683I->hasNoSignedZeros())2684return true;2685return false;2686}26872688/// Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where2689/// A1, A2, ... and C are loop invariants into expressions like2690/// ((A1 * C * B1) + (A2 * C * B2) + ...) and hoist the (A1 * C), (A2 * C), ...2691/// invariant expressions. This functions returns true only if any hoisting has2692/// actually occured.2693static bool hoistMulAddAssociation(Instruction &I, Loop &L,2694ICFLoopSafetyInfo &SafetyInfo,2695MemorySSAUpdater &MSSAU, AssumptionCache *AC,2696DominatorTree *DT) {2697if (!isReassociableOp(&I, Instruction::Mul, Instruction::FMul))2698return false;2699Value *VariantOp = I.getOperand(0);2700Value *InvariantOp = I.getOperand(1);2701if (L.isLoopInvariant(VariantOp))2702std::swap(VariantOp, InvariantOp);2703if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))2704return false;2705Value *Factor = InvariantOp;27062707// First, we need to make sure we should do the transformation.2708SmallVector<Use *> Changes;2709SmallVector<BinaryOperator *> Adds;2710SmallVector<BinaryOperator *> Worklist;2711if (BinaryOperator *VariantBinOp = dyn_cast<BinaryOperator>(VariantOp))2712Worklist.push_back(VariantBinOp);2713while (!Worklist.empty()) {2714BinaryOperator *BO = Worklist.pop_back_val();2715if (!BO->hasOneUse())2716return false;2717if (isReassociableOp(BO, Instruction::Add, Instruction::FAdd) &&2718isa<BinaryOperator>(BO->getOperand(0)) &&2719isa<BinaryOperator>(BO->getOperand(1))) {2720Worklist.push_back(cast<BinaryOperator>(BO->getOperand(0)));2721Worklist.push_back(cast<BinaryOperator>(BO->getOperand(1)));2722Adds.push_back(BO);2723continue;2724}2725if (!isReassociableOp(BO, Instruction::Mul, Instruction::FMul) ||2726L.isLoopInvariant(BO))2727return false;2728Use &U0 = BO->getOperandUse(0);2729Use &U1 = BO->getOperandUse(1);2730if (L.isLoopInvariant(U0))2731Changes.push_back(&U0);2732else if (L.isLoopInvariant(U1))2733Changes.push_back(&U1);2734else2735return false;2736unsigned Limit = I.getType()->isIntOrIntVectorTy()2737? IntAssociationUpperLimit2738: FPAssociationUpperLimit;2739if (Changes.size() > Limit)2740return false;2741}2742if (Changes.empty())2743return false;27442745// Drop the poison flags for any adds we looked through.2746if (I.getType()->isIntOrIntVectorTy()) {2747for (auto *Add : Adds)2748Add->dropPoisonGeneratingFlags();2749}27502751// We know we should do it so let's do the transformation.2752auto *Preheader = L.getLoopPreheader();2753assert(Preheader && "Loop is not in simplify form?");2754IRBuilder<> Builder(Preheader->getTerminator());2755for (auto *U : Changes) {2756assert(L.isLoopInvariant(U->get()));2757auto *Ins = cast<BinaryOperator>(U->getUser());2758Value *Mul;2759if (I.getType()->isIntOrIntVectorTy()) {2760Mul = Builder.CreateMul(U->get(), Factor, "factor.op.mul");2761// Drop the poison flags on the original multiply.2762Ins->dropPoisonGeneratingFlags();2763} else2764Mul = Builder.CreateFMulFMF(U->get(), Factor, Ins, "factor.op.fmul");27652766// Rewrite the reassociable instruction.2767unsigned OpIdx = U->getOperandNo();2768auto *LHS = OpIdx == 0 ? Mul : Ins->getOperand(0);2769auto *RHS = OpIdx == 1 ? Mul : Ins->getOperand(1);2770auto *NewBO = BinaryOperator::Create(Ins->getOpcode(), LHS, RHS,2771Ins->getName() + ".reass", Ins);2772NewBO->copyIRFlags(Ins);2773if (VariantOp == Ins)2774VariantOp = NewBO;2775Ins->replaceAllUsesWith(NewBO);2776eraseInstruction(*Ins, SafetyInfo, MSSAU);2777}27782779I.replaceAllUsesWith(VariantOp);2780eraseInstruction(I, SafetyInfo, MSSAU);2781return true;2782}27832784static bool hoistArithmetics(Instruction &I, Loop &L,2785ICFLoopSafetyInfo &SafetyInfo,2786MemorySSAUpdater &MSSAU, AssumptionCache *AC,2787DominatorTree *DT) {2788// Optimize complex patterns, such as (x < INV1 && x < INV2), turning them2789// into (x < min(INV1, INV2)), and hoisting the invariant part of this2790// expression out of the loop.2791if (hoistMinMax(I, L, SafetyInfo, MSSAU)) {2792++NumHoisted;2793++NumMinMaxHoisted;2794return true;2795}27962797// Try to hoist GEPs by reassociation.2798if (hoistGEP(I, L, SafetyInfo, MSSAU, AC, DT)) {2799++NumHoisted;2800++NumGEPsHoisted;2801return true;2802}28032804// Try to hoist add/sub's by reassociation.2805if (hoistAddSub(I, L, SafetyInfo, MSSAU, AC, DT)) {2806++NumHoisted;2807++NumAddSubHoisted;2808return true;2809}28102811bool IsInt = I.getType()->isIntOrIntVectorTy();2812if (hoistMulAddAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {2813++NumHoisted;2814if (IsInt)2815++NumIntAssociationsHoisted;2816else2817++NumFPAssociationsHoisted;2818return true;2819}28202821return false;2822}28232824/// Little predicate that returns true if the specified basic block is in2825/// a subloop of the current one, not the current one itself.2826///2827static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {2828assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");2829return LI->getLoopFor(BB) != CurLoop;2830}283128322833