1e8d8bef9SDimitry Andric //===- LoopPeel.cpp -------------------------------------------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric // 9e8d8bef9SDimitry Andric // Loop Peeling Utilities. 10e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 11e8d8bef9SDimitry Andric 12e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopPeel.h" 13e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 14e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 15e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 16349cc55cSDimitry Andric #include "llvm/Analysis/Loads.h" 17e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 18e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopIterator.h" 19e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 20e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 21e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 22e8d8bef9SDimitry Andric #include "llvm/IR/BasicBlock.h" 23e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 24e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 25e8d8bef9SDimitry Andric #include "llvm/IR/InstrTypes.h" 26e8d8bef9SDimitry Andric #include "llvm/IR/Instruction.h" 27e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h" 28e8d8bef9SDimitry Andric #include "llvm/IR/LLVMContext.h" 29e8d8bef9SDimitry Andric #include "llvm/IR/MDBuilder.h" 30e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 31bdd1243dSDimitry Andric #include "llvm/IR/ProfDataUtils.h" 32e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 33e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 34e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 35e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 36e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 38e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h" 39e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 40e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 41e8d8bef9SDimitry Andric #include <algorithm> 42e8d8bef9SDimitry Andric #include <cassert> 43e8d8bef9SDimitry Andric #include <cstdint> 44bdd1243dSDimitry Andric #include <optional> 45e8d8bef9SDimitry Andric 46e8d8bef9SDimitry Andric using namespace llvm; 47e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 48e8d8bef9SDimitry Andric 49e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-peel" 50e8d8bef9SDimitry Andric 51e8d8bef9SDimitry Andric STATISTIC(NumPeeled, "Number of loops peeled"); 52e8d8bef9SDimitry Andric 53e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelCount( 54e8d8bef9SDimitry Andric "unroll-peel-count", cl::Hidden, 55e8d8bef9SDimitry Andric cl::desc("Set the unroll peeling count, for testing purposes")); 56e8d8bef9SDimitry Andric 57e8d8bef9SDimitry Andric static cl::opt<bool> 58e8d8bef9SDimitry Andric UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 59e8d8bef9SDimitry Andric cl::desc("Allows loops to be peeled when the dynamic " 60e8d8bef9SDimitry Andric "trip count is known to be low.")); 61e8d8bef9SDimitry Andric 62e8d8bef9SDimitry Andric static cl::opt<bool> 63e8d8bef9SDimitry Andric UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 64e8d8bef9SDimitry Andric cl::init(false), cl::Hidden, 65e8d8bef9SDimitry Andric cl::desc("Allows loop nests to be peeled.")); 66e8d8bef9SDimitry Andric 67e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelMaxCount( 68e8d8bef9SDimitry Andric "unroll-peel-max-count", cl::init(7), cl::Hidden, 69e8d8bef9SDimitry Andric cl::desc("Max average trip count which will cause loop peeling.")); 70e8d8bef9SDimitry Andric 71e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollForcePeelCount( 72e8d8bef9SDimitry Andric "unroll-force-peel-count", cl::init(0), cl::Hidden, 73e8d8bef9SDimitry Andric cl::desc("Force a peel count regardless of profiling information.")); 74e8d8bef9SDimitry Andric 75bdd1243dSDimitry Andric static cl::opt<bool> DisableAdvancedPeeling( 76bdd1243dSDimitry Andric "disable-advanced-peeling", cl::init(false), cl::Hidden, 77bdd1243dSDimitry Andric cl::desc( 78bdd1243dSDimitry Andric "Disable advance peeling. Issues for convergent targets (D134803).")); 79bdd1243dSDimitry Andric 80e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 81e8d8bef9SDimitry Andric 82e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop. 83bdd1243dSDimitry Andric bool llvm::canPeel(const Loop *L) { 84e8d8bef9SDimitry Andric // Make sure the loop is in simplified form 85e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) 86e8d8bef9SDimitry Andric return false; 87bdd1243dSDimitry Andric if (!DisableAdvancedPeeling) 88bdd1243dSDimitry Andric return true; 89e8d8bef9SDimitry Andric 90349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 91349cc55cSDimitry Andric L->getUniqueNonLatchExitBlocks(Exits); 92349cc55cSDimitry Andric // The latch must either be the only exiting block or all non-latch exit 93349cc55cSDimitry Andric // blocks have either a deopt or unreachable terminator or compose a chain of 94349cc55cSDimitry Andric // blocks where the last one is either deopt or unreachable terminated. Both 95349cc55cSDimitry Andric // deopt and unreachable terminators are a strong indication they are not 96349cc55cSDimitry Andric // taken. Note that this is a profitability check, not a legality check. Also 97349cc55cSDimitry Andric // note that LoopPeeling currently can only update the branch weights of latch 98349cc55cSDimitry Andric // blocks and branch weights to blocks with deopt or unreachable do not need 99349cc55cSDimitry Andric // updating. 1000eae32dcSDimitry Andric return llvm::all_of(Exits, IsBlockFollowedByDeoptOrUnreachable); 101e8d8bef9SDimitry Andric } 102e8d8bef9SDimitry Andric 103bdd1243dSDimitry Andric namespace { 104bdd1243dSDimitry Andric 105bdd1243dSDimitry Andric // As a loop is peeled, it may be the case that Phi nodes become 106bdd1243dSDimitry Andric // loop-invariant (ie, known because there is only one choice). 107bdd1243dSDimitry Andric // For example, consider the following function: 108bdd1243dSDimitry Andric // void g(int); 109bdd1243dSDimitry Andric // void binary() { 110bdd1243dSDimitry Andric // int x = 0; 111bdd1243dSDimitry Andric // int y = 0; 112bdd1243dSDimitry Andric // int a = 0; 113bdd1243dSDimitry Andric // for(int i = 0; i <100000; ++i) { 114bdd1243dSDimitry Andric // g(x); 115bdd1243dSDimitry Andric // x = y; 116bdd1243dSDimitry Andric // g(a); 117bdd1243dSDimitry Andric // y = a + 1; 118bdd1243dSDimitry Andric // a = 5; 119bdd1243dSDimitry Andric // } 120bdd1243dSDimitry Andric // } 121bdd1243dSDimitry Andric // Peeling 3 iterations is beneficial because the values for x, y and a 122bdd1243dSDimitry Andric // become known. The IR for this loop looks something like the following: 123bdd1243dSDimitry Andric // 124bdd1243dSDimitry Andric // %i = phi i32 [ 0, %entry ], [ %inc, %if.end ] 125bdd1243dSDimitry Andric // %a = phi i32 [ 0, %entry ], [ 5, %if.end ] 126bdd1243dSDimitry Andric // %y = phi i32 [ 0, %entry ], [ %add, %if.end ] 127bdd1243dSDimitry Andric // %x = phi i32 [ 0, %entry ], [ %y, %if.end ] 128bdd1243dSDimitry Andric // ... 129bdd1243dSDimitry Andric // tail call void @_Z1gi(i32 signext %x) 130bdd1243dSDimitry Andric // tail call void @_Z1gi(i32 signext %a) 131bdd1243dSDimitry Andric // %add = add nuw nsw i32 %a, 1 132bdd1243dSDimitry Andric // %inc = add nuw nsw i32 %i, 1 133bdd1243dSDimitry Andric // %exitcond = icmp eq i32 %inc, 100000 134bdd1243dSDimitry Andric // br i1 %exitcond, label %for.cond.cleanup, label %for.body 135bdd1243dSDimitry Andric // 136bdd1243dSDimitry Andric // The arguments for the calls to g will become known after 3 iterations 137bdd1243dSDimitry Andric // of the loop, because the phi nodes values become known after 3 iterations 138bdd1243dSDimitry Andric // of the loop (ie, they are known on the 4th iteration, so peel 3 iterations). 139bdd1243dSDimitry Andric // The first iteration has g(0), g(0); the second has g(0), g(5); the 140bdd1243dSDimitry Andric // third has g(1), g(5) and the fourth (and all subsequent) have g(6), g(5). 141bdd1243dSDimitry Andric // Now consider the phi nodes: 142bdd1243dSDimitry Andric // %a is a phi with constants so it is determined after iteration 1. 143bdd1243dSDimitry Andric // %y is a phi based on a constant and %a so it is determined on 144bdd1243dSDimitry Andric // the iteration after %a is determined, so iteration 2. 145bdd1243dSDimitry Andric // %x is a phi based on a constant and %y so it is determined on 146bdd1243dSDimitry Andric // the iteration after %y, so iteration 3. 147bdd1243dSDimitry Andric // %i is based on itself (and is an induction variable) so it is 148bdd1243dSDimitry Andric // never determined. 149bdd1243dSDimitry Andric // This means that peeling off 3 iterations will result in being able to 150bdd1243dSDimitry Andric // remove the phi nodes for %a, %y, and %x. The arguments for the 151bdd1243dSDimitry Andric // corresponding calls to g are determined and the code for computing 152bdd1243dSDimitry Andric // x, y, and a can be removed. 153bdd1243dSDimitry Andric // 154bdd1243dSDimitry Andric // The PhiAnalyzer class calculates how many times a loop should be 155bdd1243dSDimitry Andric // peeled based on the above analysis of the phi nodes in the loop while 156bdd1243dSDimitry Andric // respecting the maximum specified. 157bdd1243dSDimitry Andric class PhiAnalyzer { 158bdd1243dSDimitry Andric public: 159bdd1243dSDimitry Andric PhiAnalyzer(const Loop &L, unsigned MaxIterations); 160bdd1243dSDimitry Andric 161bdd1243dSDimitry Andric // Calculate the sufficient minimum number of iterations of the loop to peel 162bdd1243dSDimitry Andric // such that phi instructions become determined (subject to allowable limits) 163bdd1243dSDimitry Andric std::optional<unsigned> calculateIterationsToPeel(); 164bdd1243dSDimitry Andric 165bdd1243dSDimitry Andric protected: 166bdd1243dSDimitry Andric using PeelCounter = std::optional<unsigned>; 167bdd1243dSDimitry Andric const PeelCounter Unknown = std::nullopt; 168bdd1243dSDimitry Andric 169bdd1243dSDimitry Andric // Add 1 respecting Unknown and return Unknown if result over MaxIterations 170bdd1243dSDimitry Andric PeelCounter addOne(PeelCounter PC) const { 171bdd1243dSDimitry Andric if (PC == Unknown) 172bdd1243dSDimitry Andric return Unknown; 173bdd1243dSDimitry Andric return (*PC + 1 <= MaxIterations) ? PeelCounter{*PC + 1} : Unknown; 174bdd1243dSDimitry Andric } 175bdd1243dSDimitry Andric 176bdd1243dSDimitry Andric // Calculate the number of iterations after which the given value 177bdd1243dSDimitry Andric // becomes an invariant. 178bdd1243dSDimitry Andric PeelCounter calculate(const Value &); 179bdd1243dSDimitry Andric 180bdd1243dSDimitry Andric const Loop &L; 181bdd1243dSDimitry Andric const unsigned MaxIterations; 182bdd1243dSDimitry Andric 183bdd1243dSDimitry Andric // Map of Values to number of iterations to invariance 184bdd1243dSDimitry Andric SmallDenseMap<const Value *, PeelCounter> IterationsToInvariance; 185bdd1243dSDimitry Andric }; 186bdd1243dSDimitry Andric 187bdd1243dSDimitry Andric PhiAnalyzer::PhiAnalyzer(const Loop &L, unsigned MaxIterations) 188bdd1243dSDimitry Andric : L(L), MaxIterations(MaxIterations) { 189bdd1243dSDimitry Andric assert(canPeel(&L) && "loop is not suitable for peeling"); 190bdd1243dSDimitry Andric assert(MaxIterations > 0 && "no peeling is allowed?"); 191bdd1243dSDimitry Andric } 192bdd1243dSDimitry Andric 193bdd1243dSDimitry Andric // This function calculates the number of iterations after which the value 194bdd1243dSDimitry Andric // becomes an invariant. The pre-calculated values are memorized in a map. 195bdd1243dSDimitry Andric // N.B. This number will be Unknown or <= MaxIterations. 196bdd1243dSDimitry Andric // The function is calculated according to the following definition: 197e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 198bdd1243dSDimitry Andric // F(%x) = G(%y) + 1 (N.B. [MaxIterations | Unknown] + 1 => Unknown) 199bdd1243dSDimitry Andric // G(%y) = 0 if %y is a loop invariant 200bdd1243dSDimitry Andric // G(%y) = G(%BackEdgeValue) if %y is a phi in the header block 201bdd1243dSDimitry Andric // G(%y) = TODO: if %y is an expression based on phis and loop invariants 202bdd1243dSDimitry Andric // The example looks like: 203bdd1243dSDimitry Andric // %x = phi(0, %a) <-- becomes invariant starting from 3rd iteration. 204bdd1243dSDimitry Andric // %y = phi(0, 5) 205bdd1243dSDimitry Andric // %a = %y + 1 206bdd1243dSDimitry Andric // G(%y) = Unknown otherwise (including phi not in header block) 207bdd1243dSDimitry Andric PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(const Value &V) { 208e8d8bef9SDimitry Andric // If we already know the answer, take it from the map. 209bdd1243dSDimitry Andric auto I = IterationsToInvariance.find(&V); 210e8d8bef9SDimitry Andric if (I != IterationsToInvariance.end()) 211e8d8bef9SDimitry Andric return I->second; 212e8d8bef9SDimitry Andric 213bdd1243dSDimitry Andric // Place Unknown to map to avoid infinite recursion. Such 214e8d8bef9SDimitry Andric // cycles can never stop on an invariant. 215bdd1243dSDimitry Andric IterationsToInvariance[&V] = Unknown; 216e8d8bef9SDimitry Andric 217bdd1243dSDimitry Andric if (L.isLoopInvariant(&V)) 218bdd1243dSDimitry Andric // Loop invariant so known at start. 219bdd1243dSDimitry Andric return (IterationsToInvariance[&V] = 0); 220bdd1243dSDimitry Andric if (const PHINode *Phi = dyn_cast<PHINode>(&V)) { 221bdd1243dSDimitry Andric if (Phi->getParent() != L.getHeader()) { 222bdd1243dSDimitry Andric // Phi is not in header block so Unknown. 223bdd1243dSDimitry Andric assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 224bdd1243dSDimitry Andric return Unknown; 225bdd1243dSDimitry Andric } 226bdd1243dSDimitry Andric // We need to analyze the input from the back edge and add 1. 227bdd1243dSDimitry Andric Value *Input = Phi->getIncomingValueForBlock(L.getLoopLatch()); 228bdd1243dSDimitry Andric PeelCounter Iterations = calculate(*Input); 229bdd1243dSDimitry Andric assert(IterationsToInvariance[Input] == Iterations && 230bdd1243dSDimitry Andric "unexpected value saved"); 231bdd1243dSDimitry Andric return (IterationsToInvariance[Phi] = addOne(Iterations)); 232bdd1243dSDimitry Andric } 233bdd1243dSDimitry Andric if (const Instruction *I = dyn_cast<Instruction>(&V)) { 234bdd1243dSDimitry Andric if (isa<CmpInst>(I) || I->isBinaryOp()) { 235bdd1243dSDimitry Andric // Binary instructions get the max of the operands. 236bdd1243dSDimitry Andric PeelCounter LHS = calculate(*I->getOperand(0)); 237bdd1243dSDimitry Andric if (LHS == Unknown) 238bdd1243dSDimitry Andric return Unknown; 239bdd1243dSDimitry Andric PeelCounter RHS = calculate(*I->getOperand(1)); 240bdd1243dSDimitry Andric if (RHS == Unknown) 241bdd1243dSDimitry Andric return Unknown; 242bdd1243dSDimitry Andric return (IterationsToInvariance[I] = {std::max(*LHS, *RHS)}); 243bdd1243dSDimitry Andric } 244bdd1243dSDimitry Andric if (I->isCast()) 245bdd1243dSDimitry Andric // Cast instructions get the value of the operand. 246bdd1243dSDimitry Andric return (IterationsToInvariance[I] = calculate(*I->getOperand(0))); 247bdd1243dSDimitry Andric } 248bdd1243dSDimitry Andric // TODO: handle more expressions 249bdd1243dSDimitry Andric 250bdd1243dSDimitry Andric // Everything else is Unknown. 251bdd1243dSDimitry Andric assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 252bdd1243dSDimitry Andric return Unknown; 253e8d8bef9SDimitry Andric } 254e8d8bef9SDimitry Andric 255bdd1243dSDimitry Andric std::optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() { 256bdd1243dSDimitry Andric unsigned Iterations = 0; 257bdd1243dSDimitry Andric for (auto &PHI : L.getHeader()->phis()) { 258bdd1243dSDimitry Andric PeelCounter ToInvariance = calculate(PHI); 259bdd1243dSDimitry Andric if (ToInvariance != Unknown) { 260bdd1243dSDimitry Andric assert(*ToInvariance <= MaxIterations && "bad result in phi analysis"); 261bdd1243dSDimitry Andric Iterations = std::max(Iterations, *ToInvariance); 262bdd1243dSDimitry Andric if (Iterations == MaxIterations) 263bdd1243dSDimitry Andric break; 264e8d8bef9SDimitry Andric } 265bdd1243dSDimitry Andric } 266bdd1243dSDimitry Andric assert((Iterations <= MaxIterations) && "bad result in phi analysis"); 267bdd1243dSDimitry Andric return Iterations ? std::optional<unsigned>(Iterations) : std::nullopt; 268bdd1243dSDimitry Andric } 269bdd1243dSDimitry Andric 270bdd1243dSDimitry Andric } // unnamed namespace 271e8d8bef9SDimitry Andric 272349cc55cSDimitry Andric // Try to find any invariant memory reads that will become dereferenceable in 273349cc55cSDimitry Andric // the remainder loop after peeling. The load must also be used (transitively) 274349cc55cSDimitry Andric // by an exit condition. Returns the number of iterations to peel off (at the 275349cc55cSDimitry Andric // moment either 0 or 1). 276349cc55cSDimitry Andric static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 277bdd1243dSDimitry Andric DominatorTree &DT, 278bdd1243dSDimitry Andric AssumptionCache *AC) { 279349cc55cSDimitry Andric // Skip loops with a single exiting block, because there should be no benefit 280349cc55cSDimitry Andric // for the heuristic below. 281349cc55cSDimitry Andric if (L.getExitingBlock()) 282349cc55cSDimitry Andric return 0; 283349cc55cSDimitry Andric 284349cc55cSDimitry Andric // All non-latch exit blocks must have an UnreachableInst terminator. 285349cc55cSDimitry Andric // Otherwise the heuristic below may not be profitable. 286349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 287349cc55cSDimitry Andric L.getUniqueNonLatchExitBlocks(Exits); 288349cc55cSDimitry Andric if (any_of(Exits, [](const BasicBlock *BB) { 289349cc55cSDimitry Andric return !isa<UnreachableInst>(BB->getTerminator()); 290349cc55cSDimitry Andric })) 291349cc55cSDimitry Andric return 0; 292349cc55cSDimitry Andric 293349cc55cSDimitry Andric // Now look for invariant loads that dominate the latch and are not known to 294349cc55cSDimitry Andric // be dereferenceable. If there are such loads and no writes, they will become 295349cc55cSDimitry Andric // dereferenceable in the loop if the first iteration is peeled off. Also 296349cc55cSDimitry Andric // collect the set of instructions controlled by such loads. Only peel if an 297349cc55cSDimitry Andric // exit condition uses (transitively) such a load. 298349cc55cSDimitry Andric BasicBlock *Header = L.getHeader(); 299349cc55cSDimitry Andric BasicBlock *Latch = L.getLoopLatch(); 300349cc55cSDimitry Andric SmallPtrSet<Value *, 8> LoadUsers; 3010fca6ea1SDimitry Andric const DataLayout &DL = L.getHeader()->getDataLayout(); 302349cc55cSDimitry Andric for (BasicBlock *BB : L.blocks()) { 303349cc55cSDimitry Andric for (Instruction &I : *BB) { 304349cc55cSDimitry Andric if (I.mayWriteToMemory()) 305349cc55cSDimitry Andric return 0; 306349cc55cSDimitry Andric 307349cc55cSDimitry Andric auto Iter = LoadUsers.find(&I); 308349cc55cSDimitry Andric if (Iter != LoadUsers.end()) { 309349cc55cSDimitry Andric for (Value *U : I.users()) 310349cc55cSDimitry Andric LoadUsers.insert(U); 311349cc55cSDimitry Andric } 312349cc55cSDimitry Andric // Do not look for reads in the header; they can already be hoisted 313349cc55cSDimitry Andric // without peeling. 314349cc55cSDimitry Andric if (BB == Header) 315349cc55cSDimitry Andric continue; 316349cc55cSDimitry Andric if (auto *LI = dyn_cast<LoadInst>(&I)) { 317349cc55cSDimitry Andric Value *Ptr = LI->getPointerOperand(); 318349cc55cSDimitry Andric if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 319bdd1243dSDimitry Andric !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, AC, &DT)) 320349cc55cSDimitry Andric for (Value *U : I.users()) 321349cc55cSDimitry Andric LoadUsers.insert(U); 322349cc55cSDimitry Andric } 323349cc55cSDimitry Andric } 324349cc55cSDimitry Andric } 325349cc55cSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 326349cc55cSDimitry Andric L.getExitingBlocks(ExitingBlocks); 327349cc55cSDimitry Andric if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 328349cc55cSDimitry Andric return LoadUsers.contains(Exiting->getTerminator()); 329349cc55cSDimitry Andric })) 330349cc55cSDimitry Andric return 1; 331349cc55cSDimitry Andric return 0; 332349cc55cSDimitry Andric } 333349cc55cSDimitry Andric 334e8d8bef9SDimitry Andric // Return the number of iterations to peel off that make conditions in the 335e8d8bef9SDimitry Andric // body true/false. For example, if we peel 2 iterations off the loop below, 336e8d8bef9SDimitry Andric // the condition i < 2 can be evaluated at compile time. 337e8d8bef9SDimitry Andric // for (i = 0; i < n; i++) 338e8d8bef9SDimitry Andric // if (i < 2) 339e8d8bef9SDimitry Andric // .. 340e8d8bef9SDimitry Andric // else 341e8d8bef9SDimitry Andric // .. 342e8d8bef9SDimitry Andric // } 343e8d8bef9SDimitry Andric static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 344e8d8bef9SDimitry Andric ScalarEvolution &SE) { 345e8d8bef9SDimitry Andric assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 346e8d8bef9SDimitry Andric unsigned DesiredPeelCount = 0; 347e8d8bef9SDimitry Andric 34806c3fb27SDimitry Andric // Do not peel the entire loop. 34906c3fb27SDimitry Andric const SCEV *BE = SE.getConstantMaxBackedgeTakenCount(&L); 35006c3fb27SDimitry Andric if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(BE)) 35106c3fb27SDimitry Andric MaxPeelCount = 35206c3fb27SDimitry Andric std::min((unsigned)SC->getAPInt().getLimitedValue() - 1, MaxPeelCount); 353e8d8bef9SDimitry Andric 3540fca6ea1SDimitry Andric // Increase PeelCount while (IterVal Pred BoundSCEV) condition is satisfied; 3550fca6ea1SDimitry Andric // return true if inversed condition become known before reaching the 3560fca6ea1SDimitry Andric // MaxPeelCount limit. 3570fca6ea1SDimitry Andric auto PeelWhilePredicateIsKnown = 3580fca6ea1SDimitry Andric [&](unsigned &PeelCount, const SCEV *&IterVal, const SCEV *BoundSCEV, 3590fca6ea1SDimitry Andric const SCEV *Step, ICmpInst::Predicate Pred) { 3600fca6ea1SDimitry Andric while (PeelCount < MaxPeelCount && 3610fca6ea1SDimitry Andric SE.isKnownPredicate(Pred, IterVal, BoundSCEV)) { 3620fca6ea1SDimitry Andric IterVal = SE.getAddExpr(IterVal, Step); 3630fca6ea1SDimitry Andric ++PeelCount; 3640fca6ea1SDimitry Andric } 3650fca6ea1SDimitry Andric return SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 3660fca6ea1SDimitry Andric BoundSCEV); 3670fca6ea1SDimitry Andric }; 3680fca6ea1SDimitry Andric 3695f757f3fSDimitry Andric const unsigned MaxDepth = 4; 3705f757f3fSDimitry Andric std::function<void(Value *, unsigned)> ComputePeelCount = 3715f757f3fSDimitry Andric [&](Value *Condition, unsigned Depth) -> void { 3725f757f3fSDimitry Andric if (!Condition->getType()->isIntegerTy() || Depth >= MaxDepth) 37306c3fb27SDimitry Andric return; 374e8d8bef9SDimitry Andric 375e8d8bef9SDimitry Andric Value *LeftVal, *RightVal; 3765f757f3fSDimitry Andric if (match(Condition, m_And(m_Value(LeftVal), m_Value(RightVal))) || 3775f757f3fSDimitry Andric match(Condition, m_Or(m_Value(LeftVal), m_Value(RightVal)))) { 3785f757f3fSDimitry Andric ComputePeelCount(LeftVal, Depth + 1); 3795f757f3fSDimitry Andric ComputePeelCount(RightVal, Depth + 1); 3805f757f3fSDimitry Andric return; 3815f757f3fSDimitry Andric } 3825f757f3fSDimitry Andric 383e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 384e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 38506c3fb27SDimitry Andric return; 386e8d8bef9SDimitry Andric 387e8d8bef9SDimitry Andric const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 388e8d8bef9SDimitry Andric const SCEV *RightSCEV = SE.getSCEV(RightVal); 389e8d8bef9SDimitry Andric 390e8d8bef9SDimitry Andric // Do not consider predicates that are known to be true or false 391e8d8bef9SDimitry Andric // independently of the loop iteration. 392fe6060f1SDimitry Andric if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 39306c3fb27SDimitry Andric return; 394e8d8bef9SDimitry Andric 395e8d8bef9SDimitry Andric // Check if we have a condition with one AddRec and one non AddRec 396e8d8bef9SDimitry Andric // expression. Normalize LeftSCEV to be the AddRec. 397e8d8bef9SDimitry Andric if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 398e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(RightSCEV)) { 399e8d8bef9SDimitry Andric std::swap(LeftSCEV, RightSCEV); 400e8d8bef9SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 401e8d8bef9SDimitry Andric } else 40206c3fb27SDimitry Andric return; 403e8d8bef9SDimitry Andric } 404e8d8bef9SDimitry Andric 405e8d8bef9SDimitry Andric const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 406e8d8bef9SDimitry Andric 407e8d8bef9SDimitry Andric // Avoid huge SCEV computations in the loop below, make sure we only 408e8d8bef9SDimitry Andric // consider AddRecs of the loop we are trying to peel. 409e8d8bef9SDimitry Andric if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 41006c3fb27SDimitry Andric return; 411e8d8bef9SDimitry Andric if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 412e8d8bef9SDimitry Andric !SE.getMonotonicPredicateType(LeftAR, Pred)) 41306c3fb27SDimitry Andric return; 414e8d8bef9SDimitry Andric 415e8d8bef9SDimitry Andric // Check if extending the current DesiredPeelCount lets us evaluate Pred 416e8d8bef9SDimitry Andric // or !Pred in the loop body statically. 417e8d8bef9SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 418e8d8bef9SDimitry Andric 419e8d8bef9SDimitry Andric const SCEV *IterVal = LeftAR->evaluateAtIteration( 420e8d8bef9SDimitry Andric SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 421e8d8bef9SDimitry Andric 422e8d8bef9SDimitry Andric // If the original condition is not known, get the negated predicate 423e8d8bef9SDimitry Andric // (which holds on the else branch) and check if it is known. This allows 424e8d8bef9SDimitry Andric // us to peel of iterations that make the original condition false. 425e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 426e8d8bef9SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred); 427e8d8bef9SDimitry Andric 428e8d8bef9SDimitry Andric const SCEV *Step = LeftAR->getStepRecurrence(SE); 4290fca6ea1SDimitry Andric if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, RightSCEV, Step, 4300fca6ea1SDimitry Andric Pred)) 4310fca6ea1SDimitry Andric return; 432e8d8bef9SDimitry Andric 433e8d8bef9SDimitry Andric // However, for equality comparisons, that isn't always sufficient to 434e8d8bef9SDimitry Andric // eliminate the comparsion in loop body, we may need to peel one more 435e8d8bef9SDimitry Andric // iteration. See if that makes !Pred become unknown again. 4360fca6ea1SDimitry Andric const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 437e8d8bef9SDimitry Andric if (ICmpInst::isEquality(Pred) && 438e8d8bef9SDimitry Andric !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 439e8d8bef9SDimitry Andric RightSCEV) && 440e8d8bef9SDimitry Andric !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 441e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 4420fca6ea1SDimitry Andric if (NewPeelCount >= MaxPeelCount) 44306c3fb27SDimitry Andric return; // Need to peel one more iteration, but can't. Give up. 4440fca6ea1SDimitry Andric ++NewPeelCount; // Great! 445e8d8bef9SDimitry Andric } 446e8d8bef9SDimitry Andric 447e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 44806c3fb27SDimitry Andric }; 44906c3fb27SDimitry Andric 4500fca6ea1SDimitry Andric auto ComputePeelCountMinMax = [&](MinMaxIntrinsic *MinMax) { 4510fca6ea1SDimitry Andric if (!MinMax->getType()->isIntegerTy()) 4520fca6ea1SDimitry Andric return; 4530fca6ea1SDimitry Andric Value *LHS = MinMax->getLHS(), *RHS = MinMax->getRHS(); 4540fca6ea1SDimitry Andric const SCEV *BoundSCEV, *IterSCEV; 4550fca6ea1SDimitry Andric if (L.isLoopInvariant(LHS)) { 4560fca6ea1SDimitry Andric BoundSCEV = SE.getSCEV(LHS); 4570fca6ea1SDimitry Andric IterSCEV = SE.getSCEV(RHS); 4580fca6ea1SDimitry Andric } else if (L.isLoopInvariant(RHS)) { 4590fca6ea1SDimitry Andric BoundSCEV = SE.getSCEV(RHS); 4600fca6ea1SDimitry Andric IterSCEV = SE.getSCEV(LHS); 4610fca6ea1SDimitry Andric } else 4620fca6ea1SDimitry Andric return; 4630fca6ea1SDimitry Andric const auto *AddRec = dyn_cast<SCEVAddRecExpr>(IterSCEV); 4640fca6ea1SDimitry Andric // For simplicity, we support only affine recurrences. 4650fca6ea1SDimitry Andric if (!AddRec || !AddRec->isAffine() || AddRec->getLoop() != &L) 4660fca6ea1SDimitry Andric return; 4670fca6ea1SDimitry Andric const SCEV *Step = AddRec->getStepRecurrence(SE); 4680fca6ea1SDimitry Andric bool IsSigned = MinMax->isSigned(); 4690fca6ea1SDimitry Andric // To minimize number of peeled iterations, we use strict relational 4700fca6ea1SDimitry Andric // predicates here. 4710fca6ea1SDimitry Andric ICmpInst::Predicate Pred; 4720fca6ea1SDimitry Andric if (SE.isKnownPositive(Step)) 4730fca6ea1SDimitry Andric Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 4740fca6ea1SDimitry Andric else if (SE.isKnownNegative(Step)) 4750fca6ea1SDimitry Andric Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 4760fca6ea1SDimitry Andric else 4770fca6ea1SDimitry Andric return; 4780fca6ea1SDimitry Andric // Check that AddRec is not wrapping. 4790fca6ea1SDimitry Andric if (!(IsSigned ? AddRec->hasNoSignedWrap() : AddRec->hasNoUnsignedWrap())) 4800fca6ea1SDimitry Andric return; 4810fca6ea1SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 4820fca6ea1SDimitry Andric const SCEV *IterVal = AddRec->evaluateAtIteration( 4830fca6ea1SDimitry Andric SE.getConstant(AddRec->getType(), NewPeelCount), SE); 4840fca6ea1SDimitry Andric if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, BoundSCEV, Step, 4850fca6ea1SDimitry Andric Pred)) 4860fca6ea1SDimitry Andric return; 4870fca6ea1SDimitry Andric DesiredPeelCount = NewPeelCount; 4880fca6ea1SDimitry Andric }; 4890fca6ea1SDimitry Andric 49006c3fb27SDimitry Andric for (BasicBlock *BB : L.blocks()) { 49106c3fb27SDimitry Andric for (Instruction &I : *BB) { 49206c3fb27SDimitry Andric if (SelectInst *SI = dyn_cast<SelectInst>(&I)) 4935f757f3fSDimitry Andric ComputePeelCount(SI->getCondition(), 0); 4940fca6ea1SDimitry Andric if (MinMaxIntrinsic *MinMax = dyn_cast<MinMaxIntrinsic>(&I)) 4950fca6ea1SDimitry Andric ComputePeelCountMinMax(MinMax); 49606c3fb27SDimitry Andric } 49706c3fb27SDimitry Andric 49806c3fb27SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 49906c3fb27SDimitry Andric if (!BI || BI->isUnconditional()) 50006c3fb27SDimitry Andric continue; 50106c3fb27SDimitry Andric 50206c3fb27SDimitry Andric // Ignore loop exit condition. 50306c3fb27SDimitry Andric if (L.getLoopLatch() == BB) 50406c3fb27SDimitry Andric continue; 50506c3fb27SDimitry Andric 5065f757f3fSDimitry Andric ComputePeelCount(BI->getCondition(), 0); 507e8d8bef9SDimitry Andric } 508e8d8bef9SDimitry Andric 509e8d8bef9SDimitry Andric return DesiredPeelCount; 510e8d8bef9SDimitry Andric } 511e8d8bef9SDimitry Andric 5120eae32dcSDimitry Andric /// This "heuristic" exactly matches implicit behavior which used to exist 5130eae32dcSDimitry Andric /// inside getLoopEstimatedTripCount. It was added here to keep an 514bdd1243dSDimitry Andric /// improvement inside that API from causing peeling to become more aggressive. 5150eae32dcSDimitry Andric /// This should probably be removed. 5160eae32dcSDimitry Andric static bool violatesLegacyMultiExitLoopCheck(Loop *L) { 5170eae32dcSDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 5180eae32dcSDimitry Andric if (!Latch) 5190eae32dcSDimitry Andric return true; 5200eae32dcSDimitry Andric 5210eae32dcSDimitry Andric BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 5220eae32dcSDimitry Andric if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 5230eae32dcSDimitry Andric return true; 5240eae32dcSDimitry Andric 5250eae32dcSDimitry Andric assert((LatchBR->getSuccessor(0) == L->getHeader() || 5260eae32dcSDimitry Andric LatchBR->getSuccessor(1) == L->getHeader()) && 5270eae32dcSDimitry Andric "At least one edge out of the latch must go to the header"); 5280eae32dcSDimitry Andric 5290eae32dcSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks; 5300eae32dcSDimitry Andric L->getUniqueNonLatchExitBlocks(ExitBlocks); 5310eae32dcSDimitry Andric return any_of(ExitBlocks, [](const BasicBlock *EB) { 5320eae32dcSDimitry Andric return !EB->getTerminatingDeoptimizeCall(); 5330eae32dcSDimitry Andric }); 5340eae32dcSDimitry Andric } 5350eae32dcSDimitry Andric 5360eae32dcSDimitry Andric 537e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off. 538e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize, 539e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences &PP, 54004eeddc0SDimitry Andric unsigned TripCount, DominatorTree &DT, 541bdd1243dSDimitry Andric ScalarEvolution &SE, AssumptionCache *AC, 542bdd1243dSDimitry Andric unsigned Threshold) { 543e8d8bef9SDimitry Andric assert(LoopSize > 0 && "Zero loop size is not allowed!"); 544e8d8bef9SDimitry Andric // Save the PP.PeelCount value set by the target in 545e8d8bef9SDimitry Andric // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 546e8d8bef9SDimitry Andric unsigned TargetPeelCount = PP.PeelCount; 547e8d8bef9SDimitry Andric PP.PeelCount = 0; 548e8d8bef9SDimitry Andric if (!canPeel(L)) 549e8d8bef9SDimitry Andric return; 550e8d8bef9SDimitry Andric 551e8d8bef9SDimitry Andric // Only try to peel innermost loops by default. 55204eeddc0SDimitry Andric // The constraint can be relaxed by the target in TTI.getPeelingPreferences 553e8d8bef9SDimitry Andric // or by the flag -unroll-allow-loop-nests-peeling. 554e8d8bef9SDimitry Andric if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 555e8d8bef9SDimitry Andric return; 556e8d8bef9SDimitry Andric 557e8d8bef9SDimitry Andric // If the user provided a peel count, use that. 558e8d8bef9SDimitry Andric bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 559e8d8bef9SDimitry Andric if (UserPeelCount) { 560e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 561e8d8bef9SDimitry Andric << " iterations.\n"); 562e8d8bef9SDimitry Andric PP.PeelCount = UnrollForcePeelCount; 563e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 564e8d8bef9SDimitry Andric return; 565e8d8bef9SDimitry Andric } 566e8d8bef9SDimitry Andric 567e8d8bef9SDimitry Andric // Skip peeling if it's disabled. 568e8d8bef9SDimitry Andric if (!PP.AllowPeeling) 569e8d8bef9SDimitry Andric return; 570e8d8bef9SDimitry Andric 57181ad6265SDimitry Andric // Check that we can peel at least one iteration. 57281ad6265SDimitry Andric if (2 * LoopSize > Threshold) 57381ad6265SDimitry Andric return; 57481ad6265SDimitry Andric 575e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 576e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 577e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 578e8d8bef9SDimitry Andric // Stop if we already peeled off the maximum number of iterations. 579e8d8bef9SDimitry Andric if (AlreadyPeeled >= UnrollPeelMaxCount) 580e8d8bef9SDimitry Andric return; 581e8d8bef9SDimitry Andric 582bdd1243dSDimitry Andric // Pay respect to limitations implied by loop size and the max peel count. 583bdd1243dSDimitry Andric unsigned MaxPeelCount = UnrollPeelMaxCount; 584bdd1243dSDimitry Andric MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 585bdd1243dSDimitry Andric 586bdd1243dSDimitry Andric // Start the max computation with the PP.PeelCount value set by the target 587bdd1243dSDimitry Andric // in TTI.getPeelingPreferences or by the flag -unroll-peel-count. 588bdd1243dSDimitry Andric unsigned DesiredPeelCount = TargetPeelCount; 589bdd1243dSDimitry Andric 590e8d8bef9SDimitry Andric // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 591e8d8bef9SDimitry Andric // iterations of the loop. For this we compute the number for iterations after 592e8d8bef9SDimitry Andric // which every Phi is guaranteed to become an invariant, and try to peel the 593e8d8bef9SDimitry Andric // maximum number of iterations among these values, thus turning all those 594e8d8bef9SDimitry Andric // Phis into invariants. 595bdd1243dSDimitry Andric if (MaxPeelCount > DesiredPeelCount) { 596bdd1243dSDimitry Andric // Check how many iterations are useful for resolving Phis 597bdd1243dSDimitry Andric auto NumPeels = PhiAnalyzer(*L, MaxPeelCount).calculateIterationsToPeel(); 598bdd1243dSDimitry Andric if (NumPeels) 599bdd1243dSDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels); 600e8d8bef9SDimitry Andric } 601e8d8bef9SDimitry Andric 602e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, 603e8d8bef9SDimitry Andric countToEliminateCompares(*L, MaxPeelCount, SE)); 604e8d8bef9SDimitry Andric 605349cc55cSDimitry Andric if (DesiredPeelCount == 0) 606bdd1243dSDimitry Andric DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT, AC); 607349cc55cSDimitry Andric 608e8d8bef9SDimitry Andric if (DesiredPeelCount > 0) { 609e8d8bef9SDimitry Andric DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 610e8d8bef9SDimitry Andric // Consider max peel count limitation. 611e8d8bef9SDimitry Andric assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 612e8d8bef9SDimitry Andric if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 613e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 614e8d8bef9SDimitry Andric << " iteration(s) to turn" 615e8d8bef9SDimitry Andric << " some Phis into invariants.\n"); 616e8d8bef9SDimitry Andric PP.PeelCount = DesiredPeelCount; 617e8d8bef9SDimitry Andric PP.PeelProfiledIterations = false; 618e8d8bef9SDimitry Andric return; 619e8d8bef9SDimitry Andric } 620e8d8bef9SDimitry Andric } 621e8d8bef9SDimitry Andric 622e8d8bef9SDimitry Andric // Bail if we know the statically calculated trip count. 623e8d8bef9SDimitry Andric // In this case we rather prefer partial unrolling. 624e8d8bef9SDimitry Andric if (TripCount) 625e8d8bef9SDimitry Andric return; 626e8d8bef9SDimitry Andric 627e8d8bef9SDimitry Andric // Do not apply profile base peeling if it is disabled. 628e8d8bef9SDimitry Andric if (!PP.PeelProfiledIterations) 629e8d8bef9SDimitry Andric return; 630e8d8bef9SDimitry Andric // If we don't know the trip count, but have reason to believe the average 631e8d8bef9SDimitry Andric // trip count is low, peeling should be beneficial, since we will usually 632e8d8bef9SDimitry Andric // hit the peeled section. 633e8d8bef9SDimitry Andric // We only do this in the presence of profile information, since otherwise 634e8d8bef9SDimitry Andric // our estimates of the trip count are not reliable enough. 635e8d8bef9SDimitry Andric if (L->getHeader()->getParent()->hasProfileData()) { 6360eae32dcSDimitry Andric if (violatesLegacyMultiExitLoopCheck(L)) 6370eae32dcSDimitry Andric return; 638bdd1243dSDimitry Andric std::optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L); 63981ad6265SDimitry Andric if (!EstimatedTripCount) 640e8d8bef9SDimitry Andric return; 641e8d8bef9SDimitry Andric 64281ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " 64381ad6265SDimitry Andric << *EstimatedTripCount << "\n"); 644e8d8bef9SDimitry Andric 64581ad6265SDimitry Andric if (*EstimatedTripCount) { 64681ad6265SDimitry Andric if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) { 64781ad6265SDimitry Andric unsigned PeelCount = *EstimatedTripCount; 64881ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n"); 64981ad6265SDimitry Andric PP.PeelCount = PeelCount; 650e8d8bef9SDimitry Andric return; 651e8d8bef9SDimitry Andric } 652e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 653e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 65481ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n"); 655e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 65681ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count by cost: " 65781ad6265SDimitry Andric << (Threshold / LoopSize - 1) << "\n"); 658e8d8bef9SDimitry Andric } 659e8d8bef9SDimitry Andric } 660e8d8bef9SDimitry Andric } 661e8d8bef9SDimitry Andric 662bdd1243dSDimitry Andric struct WeightInfo { 663bdd1243dSDimitry Andric // Weights for current iteration. 664bdd1243dSDimitry Andric SmallVector<uint32_t> Weights; 665bdd1243dSDimitry Andric // Weights to subtract after each iteration. 666bdd1243dSDimitry Andric const SmallVector<uint32_t> SubWeights; 667bdd1243dSDimitry Andric }; 668bdd1243dSDimitry Andric 669bdd1243dSDimitry Andric /// Update the branch weights of an exiting block of a peeled-off loop 670e8d8bef9SDimitry Andric /// iteration. 671bdd1243dSDimitry Andric /// Let F is a weight of the edge to continue (fallthrough) into the loop. 672bdd1243dSDimitry Andric /// Let E is a weight of the edge to an exit. 673e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 674e8d8bef9SDimitry Andric /// go to exit. 675bdd1243dSDimitry Andric /// Then, Estimated ExitCount = F / E. 6765f757f3fSDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the weights for 677bdd1243dSDimitry Andric /// the peeled exit as (EC - I, 1). It gives us reasonable distribution, 678bdd1243dSDimitry Andric /// The probability to go to exit 1/(EC-I) increases. At the same time 679bdd1243dSDimitry Andric /// the estimated exit count in the remainder loop reduces by I. 680e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part 681e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E). 682bdd1243dSDimitry Andric static void updateBranchWeights(Instruction *Term, WeightInfo &Info) { 6830fca6ea1SDimitry Andric setBranchWeights(*Term, Info.Weights, /*IsExpected=*/false); 684bdd1243dSDimitry Andric for (auto [Idx, SubWeight] : enumerate(Info.SubWeights)) 685bdd1243dSDimitry Andric if (SubWeight != 0) 6865f757f3fSDimitry Andric // Don't set the probability of taking the edge from latch to loop header 6875f757f3fSDimitry Andric // to less than 1:1 ratio (meaning Weight should not be lower than 6885f757f3fSDimitry Andric // SubWeight), as this could significantly reduce the loop's hotness, 6895f757f3fSDimitry Andric // which would be incorrect in the case of underestimating the trip count. 6905f757f3fSDimitry Andric Info.Weights[Idx] = 6915f757f3fSDimitry Andric Info.Weights[Idx] > SubWeight 6925f757f3fSDimitry Andric ? std::max(Info.Weights[Idx] - SubWeight, SubWeight) 6935f757f3fSDimitry Andric : SubWeight; 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696bdd1243dSDimitry Andric /// Initialize the weights for all exiting blocks. 697bdd1243dSDimitry Andric static void initBranchWeights(DenseMap<Instruction *, WeightInfo> &WeightInfos, 698bdd1243dSDimitry Andric Loop *L) { 699bdd1243dSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 700bdd1243dSDimitry Andric L->getExitingBlocks(ExitingBlocks); 701bdd1243dSDimitry Andric for (BasicBlock *ExitingBlock : ExitingBlocks) { 702bdd1243dSDimitry Andric Instruction *Term = ExitingBlock->getTerminator(); 703bdd1243dSDimitry Andric SmallVector<uint32_t> Weights; 704bdd1243dSDimitry Andric if (!extractBranchWeights(*Term, Weights)) 705bdd1243dSDimitry Andric continue; 706bdd1243dSDimitry Andric 707bdd1243dSDimitry Andric // See the comment on updateBranchWeights() for an explanation of what we 708bdd1243dSDimitry Andric // do here. 709bdd1243dSDimitry Andric uint32_t FallThroughWeights = 0; 710bdd1243dSDimitry Andric uint32_t ExitWeights = 0; 711bdd1243dSDimitry Andric for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 712bdd1243dSDimitry Andric if (L->contains(Succ)) 713bdd1243dSDimitry Andric FallThroughWeights += Weight; 714bdd1243dSDimitry Andric else 715bdd1243dSDimitry Andric ExitWeights += Weight; 716e8d8bef9SDimitry Andric } 717e8d8bef9SDimitry Andric 718bdd1243dSDimitry Andric // Don't try to update weights for degenerate case. 719bdd1243dSDimitry Andric if (FallThroughWeights == 0) 720bdd1243dSDimitry Andric continue; 721e8d8bef9SDimitry Andric 722bdd1243dSDimitry Andric SmallVector<uint32_t> SubWeights; 723bdd1243dSDimitry Andric for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 724bdd1243dSDimitry Andric if (!L->contains(Succ)) { 725bdd1243dSDimitry Andric // Exit weights stay the same. 726bdd1243dSDimitry Andric SubWeights.push_back(0); 727bdd1243dSDimitry Andric continue; 728bdd1243dSDimitry Andric } 729bdd1243dSDimitry Andric 730bdd1243dSDimitry Andric // Subtract exit weights on each iteration, distributed across all 731bdd1243dSDimitry Andric // fallthrough edges. 732bdd1243dSDimitry Andric double W = (double)Weight / (double)FallThroughWeights; 733bdd1243dSDimitry Andric SubWeights.push_back((uint32_t)(ExitWeights * W)); 734bdd1243dSDimitry Andric } 735bdd1243dSDimitry Andric 736bdd1243dSDimitry Andric WeightInfos.insert({Term, {std::move(Weights), std::move(SubWeights)}}); 737bdd1243dSDimitry Andric } 738bdd1243dSDimitry Andric } 739bdd1243dSDimitry Andric 740e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p 741e8d8bef9SDimitry Andric /// InsertBot. 742e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being 743e8d8bef9SDimitry Andric /// peeled off. 744e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop. 745e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone 746e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone. 747e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop. 748e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to 749e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration. 750e8d8bef9SDimitry Andric static void cloneLoopBlocks( 751e8d8bef9SDimitry Andric Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 752e8d8bef9SDimitry Andric SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 753e8d8bef9SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 754e8d8bef9SDimitry Andric ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 75581ad6265SDimitry Andric LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes, 75681ad6265SDimitry Andric ScalarEvolution &SE) { 757e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 758e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 759e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 760e8d8bef9SDimitry Andric 761e8d8bef9SDimitry Andric Function *F = Header->getParent(); 762e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 763e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 764e8d8bef9SDimitry Andric Loop *ParentLoop = L->getParentLoop(); 765e8d8bef9SDimitry Andric 766e8d8bef9SDimitry Andric // For each block in the original loop, create a new copy, 767e8d8bef9SDimitry Andric // and update the value map with the newly created values. 768e8d8bef9SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 769e8d8bef9SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 770e8d8bef9SDimitry Andric NewBlocks.push_back(NewBB); 771e8d8bef9SDimitry Andric 772e8d8bef9SDimitry Andric // If an original block is an immediate child of the loop L, its copy 773e8d8bef9SDimitry Andric // is a child of a ParentLoop after peeling. If a block is a child of 774e8d8bef9SDimitry Andric // a nested loop, it is handled in the cloneLoop() call below. 775e8d8bef9SDimitry Andric if (ParentLoop && LI->getLoopFor(*BB) == L) 776e8d8bef9SDimitry Andric ParentLoop->addBasicBlockToLoop(NewBB, *LI); 777e8d8bef9SDimitry Andric 778e8d8bef9SDimitry Andric VMap[*BB] = NewBB; 779e8d8bef9SDimitry Andric 780e8d8bef9SDimitry Andric // If dominator tree is available, insert nodes to represent cloned blocks. 781e8d8bef9SDimitry Andric if (DT) { 782e8d8bef9SDimitry Andric if (Header == *BB) 783e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, InsertTop); 784e8d8bef9SDimitry Andric else { 785e8d8bef9SDimitry Andric DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 786e8d8bef9SDimitry Andric // VMap must contain entry for IDom, as the iteration order is RPO. 787e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 788e8d8bef9SDimitry Andric } 789e8d8bef9SDimitry Andric } 790e8d8bef9SDimitry Andric } 791e8d8bef9SDimitry Andric 792d409305fSDimitry Andric { 793d409305fSDimitry Andric // Identify what other metadata depends on the cloned version. After 794d409305fSDimitry Andric // cloning, replace the metadata with the corrected version for both 795d409305fSDimitry Andric // memory instructions and noalias intrinsics. 796d409305fSDimitry Andric std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 797d409305fSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 798d409305fSDimitry Andric Header->getContext(), Ext); 799d409305fSDimitry Andric } 800d409305fSDimitry Andric 801e8d8bef9SDimitry Andric // Recursively create the new Loop objects for nested loops, if any, 802e8d8bef9SDimitry Andric // to preserve LoopInfo. 803e8d8bef9SDimitry Andric for (Loop *ChildLoop : *L) { 804e8d8bef9SDimitry Andric cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 805e8d8bef9SDimitry Andric } 806e8d8bef9SDimitry Andric 807e8d8bef9SDimitry Andric // Hook-up the control flow for the newly inserted blocks. 808e8d8bef9SDimitry Andric // The new header is hooked up directly to the "top", which is either 809e8d8bef9SDimitry Andric // the original loop preheader (for the first iteration) or the previous 810e8d8bef9SDimitry Andric // iteration's exiting block (for every other iteration) 811e8d8bef9SDimitry Andric InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 812e8d8bef9SDimitry Andric 813e8d8bef9SDimitry Andric // Similarly, for the latch: 814e8d8bef9SDimitry Andric // The original exiting edge is still hooked up to the loop exit. 815e8d8bef9SDimitry Andric // The backedge now goes to the "bottom", which is either the loop's real 816e8d8bef9SDimitry Andric // header (for the last peeled iteration) or the copied header of the next 817e8d8bef9SDimitry Andric // iteration (for every other iteration) 818e8d8bef9SDimitry Andric BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 819bdd1243dSDimitry Andric auto *LatchTerm = cast<Instruction>(NewLatch->getTerminator()); 820bdd1243dSDimitry Andric for (unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx) 821bdd1243dSDimitry Andric if (LatchTerm->getSuccessor(idx) == Header) { 822bdd1243dSDimitry Andric LatchTerm->setSuccessor(idx, InsertBot); 823e8d8bef9SDimitry Andric break; 824e8d8bef9SDimitry Andric } 825e8d8bef9SDimitry Andric if (DT) 826e8d8bef9SDimitry Andric DT->changeImmediateDominator(InsertBot, NewLatch); 827e8d8bef9SDimitry Andric 828e8d8bef9SDimitry Andric // The new copy of the loop body starts with a bunch of PHI nodes 829e8d8bef9SDimitry Andric // that pick an incoming value from either the preheader, or the previous 830e8d8bef9SDimitry Andric // loop iteration. Since this copy is no longer part of the loop, we 831e8d8bef9SDimitry Andric // resolve this statically: 832e8d8bef9SDimitry Andric // For the first iteration, we use the value from the preheader directly. 833e8d8bef9SDimitry Andric // For any other iteration, we replace the phi with the value generated by 834e8d8bef9SDimitry Andric // the immediately preceding clone of the loop body (which represents 835e8d8bef9SDimitry Andric // the previous iteration). 836e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 837e8d8bef9SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 838e8d8bef9SDimitry Andric if (IterNumber == 0) { 839e8d8bef9SDimitry Andric VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 840e8d8bef9SDimitry Andric } else { 841e8d8bef9SDimitry Andric Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 842e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 843e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 844e8d8bef9SDimitry Andric VMap[&*I] = LVMap[LatchInst]; 845e8d8bef9SDimitry Andric else 846e8d8bef9SDimitry Andric VMap[&*I] = LatchVal; 847e8d8bef9SDimitry Andric } 848bdd1243dSDimitry Andric NewPHI->eraseFromParent(); 849e8d8bef9SDimitry Andric } 850e8d8bef9SDimitry Andric 851e8d8bef9SDimitry Andric // Fix up the outgoing values - we need to add a value for the iteration 852e8d8bef9SDimitry Andric // we've just created. Note that this must happen *after* the incoming 853e8d8bef9SDimitry Andric // values are adjusted, since the value going out of the latch may also be 854e8d8bef9SDimitry Andric // a value coming into the header. 855e8d8bef9SDimitry Andric for (auto Edge : ExitEdges) 856e8d8bef9SDimitry Andric for (PHINode &PHI : Edge.second->phis()) { 857e8d8bef9SDimitry Andric Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 858e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 859e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 860e8d8bef9SDimitry Andric LatchVal = VMap[LatchVal]; 861e8d8bef9SDimitry Andric PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 862*6e516c87SDimitry Andric SE.forgetLcssaPhiWithNewPredecessor(L, &PHI); 863e8d8bef9SDimitry Andric } 864e8d8bef9SDimitry Andric 865e8d8bef9SDimitry Andric // LastValueMap is updated with the values for the current loop 866e8d8bef9SDimitry Andric // which are used the next time this function is called. 867e8d8bef9SDimitry Andric for (auto KV : VMap) 868e8d8bef9SDimitry Andric LVMap[KV.first] = KV.second; 869e8d8bef9SDimitry Andric } 870e8d8bef9SDimitry Andric 871bdd1243dSDimitry Andric TargetTransformInfo::PeelingPreferences 872bdd1243dSDimitry Andric llvm::gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, 873bdd1243dSDimitry Andric const TargetTransformInfo &TTI, 874bdd1243dSDimitry Andric std::optional<bool> UserAllowPeeling, 875bdd1243dSDimitry Andric std::optional<bool> UserAllowProfileBasedPeeling, 876bdd1243dSDimitry Andric bool UnrollingSpecficValues) { 877e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences PP; 878e8d8bef9SDimitry Andric 879e8d8bef9SDimitry Andric // Set the default values. 880e8d8bef9SDimitry Andric PP.PeelCount = 0; 881e8d8bef9SDimitry Andric PP.AllowPeeling = true; 882e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = false; 883e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 884e8d8bef9SDimitry Andric 885e8d8bef9SDimitry Andric // Get the target specifc values. 886e8d8bef9SDimitry Andric TTI.getPeelingPreferences(L, SE, PP); 887e8d8bef9SDimitry Andric 888e8d8bef9SDimitry Andric // User specified values using cl::opt. 889e8d8bef9SDimitry Andric if (UnrollingSpecficValues) { 890e8d8bef9SDimitry Andric if (UnrollPeelCount.getNumOccurrences() > 0) 891e8d8bef9SDimitry Andric PP.PeelCount = UnrollPeelCount; 892e8d8bef9SDimitry Andric if (UnrollAllowPeeling.getNumOccurrences() > 0) 893e8d8bef9SDimitry Andric PP.AllowPeeling = UnrollAllowPeeling; 894e8d8bef9SDimitry Andric if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 895e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 896e8d8bef9SDimitry Andric } 897e8d8bef9SDimitry Andric 898e8d8bef9SDimitry Andric // User specifed values provided by argument. 89981ad6265SDimitry Andric if (UserAllowPeeling) 900e8d8bef9SDimitry Andric PP.AllowPeeling = *UserAllowPeeling; 90181ad6265SDimitry Andric if (UserAllowProfileBasedPeeling) 902e8d8bef9SDimitry Andric PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 903e8d8bef9SDimitry Andric 904e8d8bef9SDimitry Andric return PP; 905e8d8bef9SDimitry Andric } 906e8d8bef9SDimitry Andric 907e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L. 908e8d8bef9SDimitry Andric /// 909e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block. 910e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the 911e8d8bef9SDimitry Andric /// exit condition. 912e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less 913e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account 914e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar 915e8d8bef9SDimitry Andric /// optimizations. 916e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 9171fd87a68SDimitry Andric ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, 918bdd1243dSDimitry Andric bool PreserveLCSSA, ValueToValueMapTy &LVMap) { 919e8d8bef9SDimitry Andric assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 920e8d8bef9SDimitry Andric assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 921e8d8bef9SDimitry Andric 922e8d8bef9SDimitry Andric LoopBlocksDFS LoopBlocks(L); 923e8d8bef9SDimitry Andric LoopBlocks.perform(LI); 924e8d8bef9SDimitry Andric 925e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 926e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 927e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 928e8d8bef9SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 929e8d8bef9SDimitry Andric L->getExitEdges(ExitEdges); 930e8d8bef9SDimitry Andric 931349cc55cSDimitry Andric // Remember dominators of blocks we might reach through exits to change them 932349cc55cSDimitry Andric // later. Immediate dominator of such block might change, because we add more 933349cc55cSDimitry Andric // routes which can lead to the exit: we can reach it from the peeled 934349cc55cSDimitry Andric // iterations too. 935349cc55cSDimitry Andric DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 936349cc55cSDimitry Andric for (auto *BB : L->blocks()) { 9371fd87a68SDimitry Andric auto *BBDomNode = DT.getNode(BB); 938349cc55cSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate; 939349cc55cSDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) { 940349cc55cSDimitry Andric auto *ChildBB = ChildDomNode->getBlock(); 941349cc55cSDimitry Andric if (!L->contains(ChildBB)) 942349cc55cSDimitry Andric ChildrenToUpdate.push_back(ChildBB); 943349cc55cSDimitry Andric } 944349cc55cSDimitry Andric // The new idom of the block will be the nearest common dominator 945349cc55cSDimitry Andric // of all copies of the previous idom. This is equivalent to the 946349cc55cSDimitry Andric // nearest common dominator of the previous idom and the first latch, 947349cc55cSDimitry Andric // which dominates all copies of the previous idom. 9481fd87a68SDimitry Andric BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch); 949349cc55cSDimitry Andric for (auto *ChildBB : ChildrenToUpdate) 950349cc55cSDimitry Andric NonLoopBlocksIDom[ChildBB] = NewIDom; 951e8d8bef9SDimitry Andric } 952e8d8bef9SDimitry Andric 953e8d8bef9SDimitry Andric Function *F = Header->getParent(); 954e8d8bef9SDimitry Andric 955e8d8bef9SDimitry Andric // Set up all the necessary basic blocks. It is convenient to split the 956e8d8bef9SDimitry Andric // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 957e8d8bef9SDimitry Andric // body, and a new preheader for the "real" loop. 958e8d8bef9SDimitry Andric 959e8d8bef9SDimitry Andric // Peeling the first iteration transforms. 960e8d8bef9SDimitry Andric // 961e8d8bef9SDimitry Andric // PreHeader: 962e8d8bef9SDimitry Andric // ... 963e8d8bef9SDimitry Andric // Header: 964e8d8bef9SDimitry Andric // LoopBody 965e8d8bef9SDimitry Andric // If (cond) goto Header 966e8d8bef9SDimitry Andric // Exit: 967e8d8bef9SDimitry Andric // 968e8d8bef9SDimitry Andric // into 969e8d8bef9SDimitry Andric // 970e8d8bef9SDimitry Andric // InsertTop: 971e8d8bef9SDimitry Andric // LoopBody 972e8d8bef9SDimitry Andric // If (!cond) goto Exit 973e8d8bef9SDimitry Andric // InsertBot: 974e8d8bef9SDimitry Andric // NewPreHeader: 975e8d8bef9SDimitry Andric // ... 976e8d8bef9SDimitry Andric // Header: 977e8d8bef9SDimitry Andric // LoopBody 978e8d8bef9SDimitry Andric // If (cond) goto Header 979e8d8bef9SDimitry Andric // Exit: 980e8d8bef9SDimitry Andric // 981e8d8bef9SDimitry Andric // Each following iteration will split the current bottom anchor in two, 982e8d8bef9SDimitry Andric // and put the new copy of the loop body between these two blocks. That is, 983e8d8bef9SDimitry Andric // after peeling another iteration from the example above, we'll split 984e8d8bef9SDimitry Andric // InsertBot, and get: 985e8d8bef9SDimitry Andric // 986e8d8bef9SDimitry Andric // InsertTop: 987e8d8bef9SDimitry Andric // LoopBody 988e8d8bef9SDimitry Andric // If (!cond) goto Exit 989e8d8bef9SDimitry Andric // InsertBot: 990e8d8bef9SDimitry Andric // LoopBody 991e8d8bef9SDimitry Andric // If (!cond) goto Exit 992e8d8bef9SDimitry Andric // InsertBot.next: 993e8d8bef9SDimitry Andric // NewPreHeader: 994e8d8bef9SDimitry Andric // ... 995e8d8bef9SDimitry Andric // Header: 996e8d8bef9SDimitry Andric // LoopBody 997e8d8bef9SDimitry Andric // If (cond) goto Header 998e8d8bef9SDimitry Andric // Exit: 999e8d8bef9SDimitry Andric 10001fd87a68SDimitry Andric BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI); 1001e8d8bef9SDimitry Andric BasicBlock *InsertBot = 10021fd87a68SDimitry Andric SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI); 1003e8d8bef9SDimitry Andric BasicBlock *NewPreHeader = 10041fd87a68SDimitry Andric SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 1005e8d8bef9SDimitry Andric 1006e8d8bef9SDimitry Andric InsertTop->setName(Header->getName() + ".peel.begin"); 1007e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 1008e8d8bef9SDimitry Andric NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 1009e8d8bef9SDimitry Andric 1010bdd1243dSDimitry Andric Instruction *LatchTerm = 1011bdd1243dSDimitry Andric cast<Instruction>(cast<BasicBlock>(Latch)->getTerminator()); 1012e8d8bef9SDimitry Andric 1013e8d8bef9SDimitry Andric // If we have branch weight information, we'll want to update it for the 1014e8d8bef9SDimitry Andric // newly created branches. 1015bdd1243dSDimitry Andric DenseMap<Instruction *, WeightInfo> Weights; 1016bdd1243dSDimitry Andric initBranchWeights(Weights, L); 1017e8d8bef9SDimitry Andric 1018d409305fSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the 1019d409305fSDimitry Andric // loop, the associated metadata must be cloned for each iteration. 1020d409305fSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 1021d409305fSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 1022d409305fSDimitry Andric 1023e8d8bef9SDimitry Andric // For each peeled-off iteration, make a copy of the loop. 1024e8d8bef9SDimitry Andric for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 1025e8d8bef9SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks; 1026e8d8bef9SDimitry Andric ValueToValueMapTy VMap; 1027e8d8bef9SDimitry Andric 1028e8d8bef9SDimitry Andric cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 10291fd87a68SDimitry Andric LoopBlocks, VMap, LVMap, &DT, LI, 103081ad6265SDimitry Andric LoopLocalNoAliasDeclScopes, *SE); 1031e8d8bef9SDimitry Andric 1032e8d8bef9SDimitry Andric // Remap to use values from the current iteration instead of the 1033e8d8bef9SDimitry Andric // previous one. 1034e8d8bef9SDimitry Andric remapInstructionsInBlocks(NewBlocks, VMap); 1035e8d8bef9SDimitry Andric 1036349cc55cSDimitry Andric // Update IDoms of the blocks reachable through exits. 1037e8d8bef9SDimitry Andric if (Iter == 0) 1038349cc55cSDimitry Andric for (auto BBIDom : NonLoopBlocksIDom) 10391fd87a68SDimitry Andric DT.changeImmediateDominator(BBIDom.first, 1040349cc55cSDimitry Andric cast<BasicBlock>(LVMap[BBIDom.second])); 1041e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS 10421fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 1043e8d8bef9SDimitry Andric #endif 1044e8d8bef9SDimitry Andric 1045bdd1243dSDimitry Andric for (auto &[Term, Info] : Weights) { 1046bdd1243dSDimitry Andric auto *TermCopy = cast<Instruction>(VMap[Term]); 1047bdd1243dSDimitry Andric updateBranchWeights(TermCopy, Info); 1048bdd1243dSDimitry Andric } 1049bdd1243dSDimitry Andric 1050e8d8bef9SDimitry Andric // Remove Loop metadata from the latch branch instruction 1051e8d8bef9SDimitry Andric // because it is not the Loop's latch branch anymore. 1052bdd1243dSDimitry Andric auto *LatchTermCopy = cast<Instruction>(VMap[LatchTerm]); 1053bdd1243dSDimitry Andric LatchTermCopy->setMetadata(LLVMContext::MD_loop, nullptr); 1054e8d8bef9SDimitry Andric 1055e8d8bef9SDimitry Andric InsertTop = InsertBot; 10561fd87a68SDimitry Andric InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 1057e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 1058e8d8bef9SDimitry Andric 1059bdd1243dSDimitry Andric F->splice(InsertTop->getIterator(), F, NewBlocks[0]->getIterator(), 1060bdd1243dSDimitry Andric F->end()); 1061e8d8bef9SDimitry Andric } 1062e8d8bef9SDimitry Andric 1063e8d8bef9SDimitry Andric // Now adjust the phi nodes in the loop header to get their initial values 1064e8d8bef9SDimitry Andric // from the last peeled-off iteration instead of the preheader. 1065e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 1066e8d8bef9SDimitry Andric PHINode *PHI = cast<PHINode>(I); 1067e8d8bef9SDimitry Andric Value *NewVal = PHI->getIncomingValueForBlock(Latch); 1068e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 1069e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 1070e8d8bef9SDimitry Andric NewVal = LVMap[LatchInst]; 1071e8d8bef9SDimitry Andric 1072e8d8bef9SDimitry Andric PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 1073e8d8bef9SDimitry Andric } 1074e8d8bef9SDimitry Andric 10755f757f3fSDimitry Andric for (const auto &[Term, Info] : Weights) { 10760fca6ea1SDimitry Andric setBranchWeights(*Term, Info.Weights, /*IsExpected=*/false); 10775f757f3fSDimitry Andric } 1078e8d8bef9SDimitry Andric 1079e8d8bef9SDimitry Andric // Update Metadata for count of peeled off iterations. 1080e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 1081e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 1082e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 1083e8d8bef9SDimitry Andric addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 1084e8d8bef9SDimitry Andric 1085e8d8bef9SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) 1086e8d8bef9SDimitry Andric L = ParentLoop; 1087e8d8bef9SDimitry Andric 1088e8d8bef9SDimitry Andric // We modified the loop, update SE. 1089e8d8bef9SDimitry Andric SE->forgetTopmostLoop(L); 109006c3fb27SDimitry Andric SE->forgetBlockAndLoopDispositions(); 1091e8d8bef9SDimitry Andric 109281ad6265SDimitry Andric #ifdef EXPENSIVE_CHECKS 1093e8d8bef9SDimitry Andric // Finally DomtTree must be correct. 10941fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 109581ad6265SDimitry Andric #endif 1096e8d8bef9SDimitry Andric 1097e8d8bef9SDimitry Andric // FIXME: Incrementally update loop-simplify 10981fd87a68SDimitry Andric simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA); 1099e8d8bef9SDimitry Andric 1100e8d8bef9SDimitry Andric NumPeeled++; 1101e8d8bef9SDimitry Andric 1102e8d8bef9SDimitry Andric return true; 1103e8d8bef9SDimitry Andric } 1104