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/Optional.h" 15e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 16e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 17349cc55cSDimitry Andric #include "llvm/Analysis/Loads.h" 18e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 19e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopIterator.h" 20e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 21e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 22e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 23e8d8bef9SDimitry Andric #include "llvm/IR/BasicBlock.h" 24e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 25e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 26e8d8bef9SDimitry Andric #include "llvm/IR/InstrTypes.h" 27e8d8bef9SDimitry Andric #include "llvm/IR/Instruction.h" 28e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h" 29e8d8bef9SDimitry Andric #include "llvm/IR/LLVMContext.h" 30e8d8bef9SDimitry Andric #include "llvm/IR/MDBuilder.h" 31e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.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> 44e8d8bef9SDimitry Andric 45e8d8bef9SDimitry Andric using namespace llvm; 46e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 47e8d8bef9SDimitry Andric 48e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-peel" 49e8d8bef9SDimitry Andric 50e8d8bef9SDimitry Andric STATISTIC(NumPeeled, "Number of loops peeled"); 51e8d8bef9SDimitry Andric 52e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelCount( 53e8d8bef9SDimitry Andric "unroll-peel-count", cl::Hidden, 54e8d8bef9SDimitry Andric cl::desc("Set the unroll peeling count, for testing purposes")); 55e8d8bef9SDimitry Andric 56e8d8bef9SDimitry Andric static cl::opt<bool> 57e8d8bef9SDimitry Andric UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 58e8d8bef9SDimitry Andric cl::desc("Allows loops to be peeled when the dynamic " 59e8d8bef9SDimitry Andric "trip count is known to be low.")); 60e8d8bef9SDimitry Andric 61e8d8bef9SDimitry Andric static cl::opt<bool> 62e8d8bef9SDimitry Andric UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 63e8d8bef9SDimitry Andric cl::init(false), cl::Hidden, 64e8d8bef9SDimitry Andric cl::desc("Allows loop nests to be peeled.")); 65e8d8bef9SDimitry Andric 66e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelMaxCount( 67e8d8bef9SDimitry Andric "unroll-peel-max-count", cl::init(7), cl::Hidden, 68e8d8bef9SDimitry Andric cl::desc("Max average trip count which will cause loop peeling.")); 69e8d8bef9SDimitry Andric 70e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollForcePeelCount( 71e8d8bef9SDimitry Andric "unroll-force-peel-count", cl::init(0), cl::Hidden, 72e8d8bef9SDimitry Andric cl::desc("Force a peel count regardless of profiling information.")); 73e8d8bef9SDimitry Andric 74e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 75e8d8bef9SDimitry Andric 76e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop. 77e8d8bef9SDimitry Andric bool llvm::canPeel(Loop *L) { 78e8d8bef9SDimitry Andric // Make sure the loop is in simplified form 79e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) 80e8d8bef9SDimitry Andric return false; 81e8d8bef9SDimitry Andric 82e8d8bef9SDimitry Andric // Don't try to peel loops where the latch is not the exiting block. 83e8d8bef9SDimitry Andric // This can be an indication of two different things: 84e8d8bef9SDimitry Andric // 1) The loop is not rotated. 85e8d8bef9SDimitry Andric // 2) The loop contains irreducible control flow that involves the latch. 86e8d8bef9SDimitry Andric const BasicBlock *Latch = L->getLoopLatch(); 87349cc55cSDimitry Andric if (!L->isLoopExiting(Latch)) 88e8d8bef9SDimitry Andric return false; 89e8d8bef9SDimitry Andric 90e8d8bef9SDimitry Andric // Peeling is only supported if the latch is a branch. 91e8d8bef9SDimitry Andric if (!isa<BranchInst>(Latch->getTerminator())) 92e8d8bef9SDimitry Andric return false; 93e8d8bef9SDimitry Andric 94349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 95349cc55cSDimitry Andric L->getUniqueNonLatchExitBlocks(Exits); 96349cc55cSDimitry Andric // The latch must either be the only exiting block or all non-latch exit 97349cc55cSDimitry Andric // blocks have either a deopt or unreachable terminator or compose a chain of 98349cc55cSDimitry Andric // blocks where the last one is either deopt or unreachable terminated. Both 99349cc55cSDimitry Andric // deopt and unreachable terminators are a strong indication they are not 100349cc55cSDimitry Andric // taken. Note that this is a profitability check, not a legality check. Also 101349cc55cSDimitry Andric // note that LoopPeeling currently can only update the branch weights of latch 102349cc55cSDimitry Andric // blocks and branch weights to blocks with deopt or unreachable do not need 103349cc55cSDimitry Andric // updating. 1040eae32dcSDimitry Andric return llvm::all_of(Exits, IsBlockFollowedByDeoptOrUnreachable); 105e8d8bef9SDimitry Andric } 106e8d8bef9SDimitry Andric 107e8d8bef9SDimitry Andric // This function calculates the number of iterations after which the given Phi 108e8d8bef9SDimitry Andric // becomes an invariant. The pre-calculated values are memorized in the map. The 109e8d8bef9SDimitry Andric // function (shortcut is I) is calculated according to the following definition: 110e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 111e8d8bef9SDimitry Andric // If %y is a loop invariant, then I(%x) = 1. 112e8d8bef9SDimitry Andric // If %y is a Phi from the loop header, I(%x) = I(%y) + 1. 113e8d8bef9SDimitry Andric // Otherwise, I(%x) is infinite. 114e8d8bef9SDimitry Andric // TODO: Actually if %y is an expression that depends only on Phi %z and some 115e8d8bef9SDimitry Andric // loop invariants, we can estimate I(%x) = I(%z) + 1. The example 116e8d8bef9SDimitry Andric // looks like: 117e8d8bef9SDimitry Andric // %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration. 118e8d8bef9SDimitry Andric // %y = phi(0, 5), 119e8d8bef9SDimitry Andric // %a = %y + 1. 120349cc55cSDimitry Andric static Optional<unsigned> calculateIterationsToInvariance( 121e8d8bef9SDimitry Andric PHINode *Phi, Loop *L, BasicBlock *BackEdge, 122349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned> > &IterationsToInvariance) { 123e8d8bef9SDimitry Andric assert(Phi->getParent() == L->getHeader() && 124e8d8bef9SDimitry Andric "Non-loop Phi should not be checked for turning into invariant."); 125e8d8bef9SDimitry Andric assert(BackEdge == L->getLoopLatch() && "Wrong latch?"); 126e8d8bef9SDimitry Andric // If we already know the answer, take it from the map. 127e8d8bef9SDimitry Andric auto I = IterationsToInvariance.find(Phi); 128e8d8bef9SDimitry Andric if (I != IterationsToInvariance.end()) 129e8d8bef9SDimitry Andric return I->second; 130e8d8bef9SDimitry Andric 131e8d8bef9SDimitry Andric // Otherwise we need to analyze the input from the back edge. 132e8d8bef9SDimitry Andric Value *Input = Phi->getIncomingValueForBlock(BackEdge); 133e8d8bef9SDimitry Andric // Place infinity to map to avoid infinite recursion for cycled Phis. Such 134e8d8bef9SDimitry Andric // cycles can never stop on an invariant. 135349cc55cSDimitry Andric IterationsToInvariance[Phi] = None; 136349cc55cSDimitry Andric Optional<unsigned> ToInvariance = None; 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric if (L->isLoopInvariant(Input)) 139e8d8bef9SDimitry Andric ToInvariance = 1u; 140e8d8bef9SDimitry Andric else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) { 141e8d8bef9SDimitry Andric // Only consider Phis in header block. 142e8d8bef9SDimitry Andric if (IncPhi->getParent() != L->getHeader()) 143349cc55cSDimitry Andric return None; 144e8d8bef9SDimitry Andric // If the input becomes an invariant after X iterations, then our Phi 145e8d8bef9SDimitry Andric // becomes an invariant after X + 1 iterations. 146349cc55cSDimitry Andric auto InputToInvariance = calculateIterationsToInvariance( 147e8d8bef9SDimitry Andric IncPhi, L, BackEdge, IterationsToInvariance); 148349cc55cSDimitry Andric if (InputToInvariance) 149349cc55cSDimitry Andric ToInvariance = *InputToInvariance + 1u; 150e8d8bef9SDimitry Andric } 151e8d8bef9SDimitry Andric 152e8d8bef9SDimitry Andric // If we found that this Phi lies in an invariant chain, update the map. 153349cc55cSDimitry Andric if (ToInvariance) 154e8d8bef9SDimitry Andric IterationsToInvariance[Phi] = ToInvariance; 155e8d8bef9SDimitry Andric return ToInvariance; 156e8d8bef9SDimitry Andric } 157e8d8bef9SDimitry Andric 158349cc55cSDimitry Andric // Try to find any invariant memory reads that will become dereferenceable in 159349cc55cSDimitry Andric // the remainder loop after peeling. The load must also be used (transitively) 160349cc55cSDimitry Andric // by an exit condition. Returns the number of iterations to peel off (at the 161349cc55cSDimitry Andric // moment either 0 or 1). 162349cc55cSDimitry Andric static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 163349cc55cSDimitry Andric DominatorTree &DT) { 164349cc55cSDimitry Andric // Skip loops with a single exiting block, because there should be no benefit 165349cc55cSDimitry Andric // for the heuristic below. 166349cc55cSDimitry Andric if (L.getExitingBlock()) 167349cc55cSDimitry Andric return 0; 168349cc55cSDimitry Andric 169349cc55cSDimitry Andric // All non-latch exit blocks must have an UnreachableInst terminator. 170349cc55cSDimitry Andric // Otherwise the heuristic below may not be profitable. 171349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 172349cc55cSDimitry Andric L.getUniqueNonLatchExitBlocks(Exits); 173349cc55cSDimitry Andric if (any_of(Exits, [](const BasicBlock *BB) { 174349cc55cSDimitry Andric return !isa<UnreachableInst>(BB->getTerminator()); 175349cc55cSDimitry Andric })) 176349cc55cSDimitry Andric return 0; 177349cc55cSDimitry Andric 178349cc55cSDimitry Andric // Now look for invariant loads that dominate the latch and are not known to 179349cc55cSDimitry Andric // be dereferenceable. If there are such loads and no writes, they will become 180349cc55cSDimitry Andric // dereferenceable in the loop if the first iteration is peeled off. Also 181349cc55cSDimitry Andric // collect the set of instructions controlled by such loads. Only peel if an 182349cc55cSDimitry Andric // exit condition uses (transitively) such a load. 183349cc55cSDimitry Andric BasicBlock *Header = L.getHeader(); 184349cc55cSDimitry Andric BasicBlock *Latch = L.getLoopLatch(); 185349cc55cSDimitry Andric SmallPtrSet<Value *, 8> LoadUsers; 186349cc55cSDimitry Andric const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 187349cc55cSDimitry Andric for (BasicBlock *BB : L.blocks()) { 188349cc55cSDimitry Andric for (Instruction &I : *BB) { 189349cc55cSDimitry Andric if (I.mayWriteToMemory()) 190349cc55cSDimitry Andric return 0; 191349cc55cSDimitry Andric 192349cc55cSDimitry Andric auto Iter = LoadUsers.find(&I); 193349cc55cSDimitry Andric if (Iter != LoadUsers.end()) { 194349cc55cSDimitry Andric for (Value *U : I.users()) 195349cc55cSDimitry Andric LoadUsers.insert(U); 196349cc55cSDimitry Andric } 197349cc55cSDimitry Andric // Do not look for reads in the header; they can already be hoisted 198349cc55cSDimitry Andric // without peeling. 199349cc55cSDimitry Andric if (BB == Header) 200349cc55cSDimitry Andric continue; 201349cc55cSDimitry Andric if (auto *LI = dyn_cast<LoadInst>(&I)) { 202349cc55cSDimitry Andric Value *Ptr = LI->getPointerOperand(); 203349cc55cSDimitry Andric if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 204349cc55cSDimitry Andric !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, &DT)) 205349cc55cSDimitry Andric for (Value *U : I.users()) 206349cc55cSDimitry Andric LoadUsers.insert(U); 207349cc55cSDimitry Andric } 208349cc55cSDimitry Andric } 209349cc55cSDimitry Andric } 210349cc55cSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 211349cc55cSDimitry Andric L.getExitingBlocks(ExitingBlocks); 212349cc55cSDimitry Andric if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 213349cc55cSDimitry Andric return LoadUsers.contains(Exiting->getTerminator()); 214349cc55cSDimitry Andric })) 215349cc55cSDimitry Andric return 1; 216349cc55cSDimitry Andric return 0; 217349cc55cSDimitry Andric } 218349cc55cSDimitry Andric 219e8d8bef9SDimitry Andric // Return the number of iterations to peel off that make conditions in the 220e8d8bef9SDimitry Andric // body true/false. For example, if we peel 2 iterations off the loop below, 221e8d8bef9SDimitry Andric // the condition i < 2 can be evaluated at compile time. 222e8d8bef9SDimitry Andric // for (i = 0; i < n; i++) 223e8d8bef9SDimitry Andric // if (i < 2) 224e8d8bef9SDimitry Andric // .. 225e8d8bef9SDimitry Andric // else 226e8d8bef9SDimitry Andric // .. 227e8d8bef9SDimitry Andric // } 228e8d8bef9SDimitry Andric static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 229e8d8bef9SDimitry Andric ScalarEvolution &SE) { 230e8d8bef9SDimitry Andric assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 231e8d8bef9SDimitry Andric unsigned DesiredPeelCount = 0; 232e8d8bef9SDimitry Andric 233e8d8bef9SDimitry Andric for (auto *BB : L.blocks()) { 234e8d8bef9SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 235e8d8bef9SDimitry Andric if (!BI || BI->isUnconditional()) 236e8d8bef9SDimitry Andric continue; 237e8d8bef9SDimitry Andric 238e8d8bef9SDimitry Andric // Ignore loop exit condition. 239e8d8bef9SDimitry Andric if (L.getLoopLatch() == BB) 240e8d8bef9SDimitry Andric continue; 241e8d8bef9SDimitry Andric 242e8d8bef9SDimitry Andric Value *Condition = BI->getCondition(); 243e8d8bef9SDimitry Andric Value *LeftVal, *RightVal; 244e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 245e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 246e8d8bef9SDimitry Andric continue; 247e8d8bef9SDimitry Andric 248e8d8bef9SDimitry Andric const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 249e8d8bef9SDimitry Andric const SCEV *RightSCEV = SE.getSCEV(RightVal); 250e8d8bef9SDimitry Andric 251e8d8bef9SDimitry Andric // Do not consider predicates that are known to be true or false 252e8d8bef9SDimitry Andric // independently of the loop iteration. 253fe6060f1SDimitry Andric if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 254e8d8bef9SDimitry Andric continue; 255e8d8bef9SDimitry Andric 256e8d8bef9SDimitry Andric // Check if we have a condition with one AddRec and one non AddRec 257e8d8bef9SDimitry Andric // expression. Normalize LeftSCEV to be the AddRec. 258e8d8bef9SDimitry Andric if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 259e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(RightSCEV)) { 260e8d8bef9SDimitry Andric std::swap(LeftSCEV, RightSCEV); 261e8d8bef9SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 262e8d8bef9SDimitry Andric } else 263e8d8bef9SDimitry Andric continue; 264e8d8bef9SDimitry Andric } 265e8d8bef9SDimitry Andric 266e8d8bef9SDimitry Andric const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 267e8d8bef9SDimitry Andric 268e8d8bef9SDimitry Andric // Avoid huge SCEV computations in the loop below, make sure we only 269e8d8bef9SDimitry Andric // consider AddRecs of the loop we are trying to peel. 270e8d8bef9SDimitry Andric if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 271e8d8bef9SDimitry Andric continue; 272e8d8bef9SDimitry Andric if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 273e8d8bef9SDimitry Andric !SE.getMonotonicPredicateType(LeftAR, Pred)) 274e8d8bef9SDimitry Andric continue; 275e8d8bef9SDimitry Andric 276e8d8bef9SDimitry Andric // Check if extending the current DesiredPeelCount lets us evaluate Pred 277e8d8bef9SDimitry Andric // or !Pred in the loop body statically. 278e8d8bef9SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 279e8d8bef9SDimitry Andric 280e8d8bef9SDimitry Andric const SCEV *IterVal = LeftAR->evaluateAtIteration( 281e8d8bef9SDimitry Andric SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 282e8d8bef9SDimitry Andric 283e8d8bef9SDimitry Andric // If the original condition is not known, get the negated predicate 284e8d8bef9SDimitry Andric // (which holds on the else branch) and check if it is known. This allows 285e8d8bef9SDimitry Andric // us to peel of iterations that make the original condition false. 286e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 287e8d8bef9SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred); 288e8d8bef9SDimitry Andric 289e8d8bef9SDimitry Andric const SCEV *Step = LeftAR->getStepRecurrence(SE); 290e8d8bef9SDimitry Andric const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 291e8d8bef9SDimitry Andric auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 292e8d8bef9SDimitry Andric &NewPeelCount]() { 293e8d8bef9SDimitry Andric IterVal = NextIterVal; 294e8d8bef9SDimitry Andric NextIterVal = SE.getAddExpr(IterVal, Step); 295e8d8bef9SDimitry Andric NewPeelCount++; 296e8d8bef9SDimitry Andric }; 297e8d8bef9SDimitry Andric 298e8d8bef9SDimitry Andric auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 299e8d8bef9SDimitry Andric return NewPeelCount < MaxPeelCount; 300e8d8bef9SDimitry Andric }; 301e8d8bef9SDimitry Andric 302e8d8bef9SDimitry Andric while (CanPeelOneMoreIteration() && 303e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 304e8d8bef9SDimitry Andric PeelOneMoreIteration(); 305e8d8bef9SDimitry Andric 306e8d8bef9SDimitry Andric // With *that* peel count, does the predicate !Pred become known in the 307e8d8bef9SDimitry Andric // first iteration of the loop body after peeling? 308e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 309e8d8bef9SDimitry Andric RightSCEV)) 310e8d8bef9SDimitry Andric continue; // If not, give up. 311e8d8bef9SDimitry Andric 312e8d8bef9SDimitry Andric // However, for equality comparisons, that isn't always sufficient to 313e8d8bef9SDimitry Andric // eliminate the comparsion in loop body, we may need to peel one more 314e8d8bef9SDimitry Andric // iteration. See if that makes !Pred become unknown again. 315e8d8bef9SDimitry Andric if (ICmpInst::isEquality(Pred) && 316e8d8bef9SDimitry Andric !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 317e8d8bef9SDimitry Andric RightSCEV) && 318e8d8bef9SDimitry Andric !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 319e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 320e8d8bef9SDimitry Andric if (!CanPeelOneMoreIteration()) 321e8d8bef9SDimitry Andric continue; // Need to peel one more iteration, but can't. Give up. 322e8d8bef9SDimitry Andric PeelOneMoreIteration(); // Great! 323e8d8bef9SDimitry Andric } 324e8d8bef9SDimitry Andric 325e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 326e8d8bef9SDimitry Andric } 327e8d8bef9SDimitry Andric 328e8d8bef9SDimitry Andric return DesiredPeelCount; 329e8d8bef9SDimitry Andric } 330e8d8bef9SDimitry Andric 3310eae32dcSDimitry Andric /// This "heuristic" exactly matches implicit behavior which used to exist 3320eae32dcSDimitry Andric /// inside getLoopEstimatedTripCount. It was added here to keep an 3330eae32dcSDimitry Andric /// improvement inside that API from causing peeling to become more agressive. 3340eae32dcSDimitry Andric /// This should probably be removed. 3350eae32dcSDimitry Andric static bool violatesLegacyMultiExitLoopCheck(Loop *L) { 3360eae32dcSDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 3370eae32dcSDimitry Andric if (!Latch) 3380eae32dcSDimitry Andric return true; 3390eae32dcSDimitry Andric 3400eae32dcSDimitry Andric BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 3410eae32dcSDimitry Andric if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 3420eae32dcSDimitry Andric return true; 3430eae32dcSDimitry Andric 3440eae32dcSDimitry Andric assert((LatchBR->getSuccessor(0) == L->getHeader() || 3450eae32dcSDimitry Andric LatchBR->getSuccessor(1) == L->getHeader()) && 3460eae32dcSDimitry Andric "At least one edge out of the latch must go to the header"); 3470eae32dcSDimitry Andric 3480eae32dcSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks; 3490eae32dcSDimitry Andric L->getUniqueNonLatchExitBlocks(ExitBlocks); 3500eae32dcSDimitry Andric return any_of(ExitBlocks, [](const BasicBlock *EB) { 3510eae32dcSDimitry Andric return !EB->getTerminatingDeoptimizeCall(); 3520eae32dcSDimitry Andric }); 3530eae32dcSDimitry Andric } 3540eae32dcSDimitry Andric 3550eae32dcSDimitry Andric 356e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off. 357e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize, 358e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences &PP, 35904eeddc0SDimitry Andric unsigned TripCount, DominatorTree &DT, 360349cc55cSDimitry Andric ScalarEvolution &SE, unsigned Threshold) { 361e8d8bef9SDimitry Andric assert(LoopSize > 0 && "Zero loop size is not allowed!"); 362e8d8bef9SDimitry Andric // Save the PP.PeelCount value set by the target in 363e8d8bef9SDimitry Andric // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 364e8d8bef9SDimitry Andric unsigned TargetPeelCount = PP.PeelCount; 365e8d8bef9SDimitry Andric PP.PeelCount = 0; 366e8d8bef9SDimitry Andric if (!canPeel(L)) 367e8d8bef9SDimitry Andric return; 368e8d8bef9SDimitry Andric 369e8d8bef9SDimitry Andric // Only try to peel innermost loops by default. 37004eeddc0SDimitry Andric // The constraint can be relaxed by the target in TTI.getPeelingPreferences 371e8d8bef9SDimitry Andric // or by the flag -unroll-allow-loop-nests-peeling. 372e8d8bef9SDimitry Andric if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 373e8d8bef9SDimitry Andric return; 374e8d8bef9SDimitry Andric 375e8d8bef9SDimitry Andric // If the user provided a peel count, use that. 376e8d8bef9SDimitry Andric bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 377e8d8bef9SDimitry Andric if (UserPeelCount) { 378e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 379e8d8bef9SDimitry Andric << " iterations.\n"); 380e8d8bef9SDimitry Andric PP.PeelCount = UnrollForcePeelCount; 381e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 382e8d8bef9SDimitry Andric return; 383e8d8bef9SDimitry Andric } 384e8d8bef9SDimitry Andric 385e8d8bef9SDimitry Andric // Skip peeling if it's disabled. 386e8d8bef9SDimitry Andric if (!PP.AllowPeeling) 387e8d8bef9SDimitry Andric return; 388e8d8bef9SDimitry Andric 389*81ad6265SDimitry Andric // Check that we can peel at least one iteration. 390*81ad6265SDimitry Andric if (2 * LoopSize > Threshold) 391*81ad6265SDimitry Andric return; 392*81ad6265SDimitry Andric 393e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 394e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 395e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 396e8d8bef9SDimitry Andric // Stop if we already peeled off the maximum number of iterations. 397e8d8bef9SDimitry Andric if (AlreadyPeeled >= UnrollPeelMaxCount) 398e8d8bef9SDimitry Andric return; 399e8d8bef9SDimitry Andric 400e8d8bef9SDimitry Andric // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 401e8d8bef9SDimitry Andric // iterations of the loop. For this we compute the number for iterations after 402e8d8bef9SDimitry Andric // which every Phi is guaranteed to become an invariant, and try to peel the 403e8d8bef9SDimitry Andric // maximum number of iterations among these values, thus turning all those 404e8d8bef9SDimitry Andric // Phis into invariants. 405*81ad6265SDimitry Andric 406e8d8bef9SDimitry Andric // Store the pre-calculated values here. 407349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned>> IterationsToInvariance; 408e8d8bef9SDimitry Andric // Now go through all Phis to calculate their the number of iterations they 409e8d8bef9SDimitry Andric // need to become invariants. 41004eeddc0SDimitry Andric // Start the max computation with the PP.PeelCount value set by the target 41104eeddc0SDimitry Andric // in TTI.getPeelingPreferences or by the flag -unroll-peel-count. 412e8d8bef9SDimitry Andric unsigned DesiredPeelCount = TargetPeelCount; 413e8d8bef9SDimitry Andric BasicBlock *BackEdge = L->getLoopLatch(); 414e8d8bef9SDimitry Andric assert(BackEdge && "Loop is not in simplified form?"); 415e8d8bef9SDimitry Andric for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) { 416e8d8bef9SDimitry Andric PHINode *Phi = cast<PHINode>(&*BI); 417*81ad6265SDimitry Andric auto ToInvariance = calculateIterationsToInvariance(Phi, L, BackEdge, 418*81ad6265SDimitry Andric IterationsToInvariance); 419349cc55cSDimitry Andric if (ToInvariance) 420349cc55cSDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, *ToInvariance); 421e8d8bef9SDimitry Andric } 422e8d8bef9SDimitry Andric 423e8d8bef9SDimitry Andric // Pay respect to limitations implied by loop size and the max peel count. 424e8d8bef9SDimitry Andric unsigned MaxPeelCount = UnrollPeelMaxCount; 425e8d8bef9SDimitry Andric MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 426e8d8bef9SDimitry Andric 427e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, 428e8d8bef9SDimitry Andric countToEliminateCompares(*L, MaxPeelCount, SE)); 429e8d8bef9SDimitry Andric 430349cc55cSDimitry Andric if (DesiredPeelCount == 0) 431349cc55cSDimitry Andric DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT); 432349cc55cSDimitry Andric 433e8d8bef9SDimitry Andric if (DesiredPeelCount > 0) { 434e8d8bef9SDimitry Andric DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 435e8d8bef9SDimitry Andric // Consider max peel count limitation. 436e8d8bef9SDimitry Andric assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 437e8d8bef9SDimitry Andric if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 438e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 439e8d8bef9SDimitry Andric << " iteration(s) to turn" 440e8d8bef9SDimitry Andric << " some Phis into invariants.\n"); 441e8d8bef9SDimitry Andric PP.PeelCount = DesiredPeelCount; 442e8d8bef9SDimitry Andric PP.PeelProfiledIterations = false; 443e8d8bef9SDimitry Andric return; 444e8d8bef9SDimitry Andric } 445e8d8bef9SDimitry Andric } 446e8d8bef9SDimitry Andric 447e8d8bef9SDimitry Andric // Bail if we know the statically calculated trip count. 448e8d8bef9SDimitry Andric // In this case we rather prefer partial unrolling. 449e8d8bef9SDimitry Andric if (TripCount) 450e8d8bef9SDimitry Andric return; 451e8d8bef9SDimitry Andric 452e8d8bef9SDimitry Andric // Do not apply profile base peeling if it is disabled. 453e8d8bef9SDimitry Andric if (!PP.PeelProfiledIterations) 454e8d8bef9SDimitry Andric return; 455e8d8bef9SDimitry Andric // If we don't know the trip count, but have reason to believe the average 456e8d8bef9SDimitry Andric // trip count is low, peeling should be beneficial, since we will usually 457e8d8bef9SDimitry Andric // hit the peeled section. 458e8d8bef9SDimitry Andric // We only do this in the presence of profile information, since otherwise 459e8d8bef9SDimitry Andric // our estimates of the trip count are not reliable enough. 460e8d8bef9SDimitry Andric if (L->getHeader()->getParent()->hasProfileData()) { 4610eae32dcSDimitry Andric if (violatesLegacyMultiExitLoopCheck(L)) 4620eae32dcSDimitry Andric return; 463*81ad6265SDimitry Andric Optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L); 464*81ad6265SDimitry Andric if (!EstimatedTripCount) 465e8d8bef9SDimitry Andric return; 466e8d8bef9SDimitry Andric 467*81ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " 468*81ad6265SDimitry Andric << *EstimatedTripCount << "\n"); 469e8d8bef9SDimitry Andric 470*81ad6265SDimitry Andric if (*EstimatedTripCount) { 471*81ad6265SDimitry Andric if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) { 472*81ad6265SDimitry Andric unsigned PeelCount = *EstimatedTripCount; 473*81ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n"); 474*81ad6265SDimitry Andric PP.PeelCount = PeelCount; 475e8d8bef9SDimitry Andric return; 476e8d8bef9SDimitry Andric } 477e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 478e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 479*81ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n"); 480e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 481*81ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count by cost: " 482*81ad6265SDimitry Andric << (Threshold / LoopSize - 1) << "\n"); 483e8d8bef9SDimitry Andric } 484e8d8bef9SDimitry Andric } 485e8d8bef9SDimitry Andric } 486e8d8bef9SDimitry Andric 487e8d8bef9SDimitry Andric /// Update the branch weights of the latch of a peeled-off loop 488e8d8bef9SDimitry Andric /// iteration. 489e8d8bef9SDimitry Andric /// This sets the branch weights for the latch of the recently peeled off loop 490e8d8bef9SDimitry Andric /// iteration correctly. 491e8d8bef9SDimitry Andric /// Let F is a weight of the edge from latch to header. 492e8d8bef9SDimitry Andric /// Let E is a weight of the edge from latch to exit. 493e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 494e8d8bef9SDimitry Andric /// go to exit. 495e8d8bef9SDimitry Andric /// Then, Estimated TripCount = F / E. 496e8d8bef9SDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the the weights for 497e8d8bef9SDimitry Andric /// the peeled latch as (TC - I, 1). It gives us reasonable distribution, 498e8d8bef9SDimitry Andric /// The probability to go to exit 1/(TC-I) increases. At the same time 499e8d8bef9SDimitry Andric /// the estimated trip count of remaining loop reduces by I. 500e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part 501e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E). 502e8d8bef9SDimitry Andric /// 503e8d8bef9SDimitry Andric /// \param Header The copy of the header block that belongs to next iteration. 504e8d8bef9SDimitry Andric /// \param LatchBR The copy of the latch branch that belongs to this iteration. 505e8d8bef9SDimitry Andric /// \param[in,out] FallThroughWeight The weight of the edge from latch to 506e8d8bef9SDimitry Andric /// header before peeling (in) and after peeled off one iteration (out). 507e8d8bef9SDimitry Andric static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 508e8d8bef9SDimitry Andric uint64_t ExitWeight, 509e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 510e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 511e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 512e8d8bef9SDimitry Andric if (!FallThroughWeight) 513e8d8bef9SDimitry Andric return; 514e8d8bef9SDimitry Andric 515e8d8bef9SDimitry Andric unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1); 516e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 517e8d8bef9SDimitry Andric MDNode *WeightNode = 518e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 519e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 520e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 521e8d8bef9SDimitry Andric FallThroughWeight = 522e8d8bef9SDimitry Andric FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1; 523e8d8bef9SDimitry Andric } 524e8d8bef9SDimitry Andric 525e8d8bef9SDimitry Andric /// Initialize the weights. 526e8d8bef9SDimitry Andric /// 527e8d8bef9SDimitry Andric /// \param Header The header block. 528e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 529e8d8bef9SDimitry Andric /// \param[out] ExitWeight The weight of the edge from Latch to Exit. 530e8d8bef9SDimitry Andric /// \param[out] FallThroughWeight The weight of the edge from Latch to Header. 531e8d8bef9SDimitry Andric static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 532e8d8bef9SDimitry Andric uint64_t &ExitWeight, 533e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 534e8d8bef9SDimitry Andric uint64_t TrueWeight, FalseWeight; 535e8d8bef9SDimitry Andric if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) 536e8d8bef9SDimitry Andric return; 537e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 538e8d8bef9SDimitry Andric ExitWeight = HeaderIdx ? TrueWeight : FalseWeight; 539e8d8bef9SDimitry Andric FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight; 540e8d8bef9SDimitry Andric } 541e8d8bef9SDimitry Andric 542e8d8bef9SDimitry Andric /// Update the weights of original Latch block after peeling off all iterations. 543e8d8bef9SDimitry Andric /// 544e8d8bef9SDimitry Andric /// \param Header The header block. 545e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 546e8d8bef9SDimitry Andric /// \param ExitWeight The weight of the edge from Latch to Exit. 547e8d8bef9SDimitry Andric /// \param FallThroughWeight The weight of the edge from Latch to Header. 548e8d8bef9SDimitry Andric static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 549e8d8bef9SDimitry Andric uint64_t ExitWeight, 550e8d8bef9SDimitry Andric uint64_t FallThroughWeight) { 551e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 552e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 553e8d8bef9SDimitry Andric if (!FallThroughWeight) 554e8d8bef9SDimitry Andric return; 555e8d8bef9SDimitry Andric 556e8d8bef9SDimitry Andric // Sets the branch weights on the loop exit. 557e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 558e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 559e8d8bef9SDimitry Andric MDNode *WeightNode = 560e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 561e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 562e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 563e8d8bef9SDimitry Andric } 564e8d8bef9SDimitry Andric 565e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p 566e8d8bef9SDimitry Andric /// InsertBot. 567e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being 568e8d8bef9SDimitry Andric /// peeled off. 569e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop. 570e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone 571e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone. 572e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop. 573e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to 574e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration. 575e8d8bef9SDimitry Andric static void cloneLoopBlocks( 576e8d8bef9SDimitry Andric Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 577e8d8bef9SDimitry Andric SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 578e8d8bef9SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 579e8d8bef9SDimitry Andric ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 580*81ad6265SDimitry Andric LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes, 581*81ad6265SDimitry Andric ScalarEvolution &SE) { 582e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 583e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 584e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 585e8d8bef9SDimitry Andric 586e8d8bef9SDimitry Andric Function *F = Header->getParent(); 587e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 588e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 589e8d8bef9SDimitry Andric Loop *ParentLoop = L->getParentLoop(); 590e8d8bef9SDimitry Andric 591e8d8bef9SDimitry Andric // For each block in the original loop, create a new copy, 592e8d8bef9SDimitry Andric // and update the value map with the newly created values. 593e8d8bef9SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 594e8d8bef9SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 595e8d8bef9SDimitry Andric NewBlocks.push_back(NewBB); 596e8d8bef9SDimitry Andric 597e8d8bef9SDimitry Andric // If an original block is an immediate child of the loop L, its copy 598e8d8bef9SDimitry Andric // is a child of a ParentLoop after peeling. If a block is a child of 599e8d8bef9SDimitry Andric // a nested loop, it is handled in the cloneLoop() call below. 600e8d8bef9SDimitry Andric if (ParentLoop && LI->getLoopFor(*BB) == L) 601e8d8bef9SDimitry Andric ParentLoop->addBasicBlockToLoop(NewBB, *LI); 602e8d8bef9SDimitry Andric 603e8d8bef9SDimitry Andric VMap[*BB] = NewBB; 604e8d8bef9SDimitry Andric 605e8d8bef9SDimitry Andric // If dominator tree is available, insert nodes to represent cloned blocks. 606e8d8bef9SDimitry Andric if (DT) { 607e8d8bef9SDimitry Andric if (Header == *BB) 608e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, InsertTop); 609e8d8bef9SDimitry Andric else { 610e8d8bef9SDimitry Andric DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 611e8d8bef9SDimitry Andric // VMap must contain entry for IDom, as the iteration order is RPO. 612e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 613e8d8bef9SDimitry Andric } 614e8d8bef9SDimitry Andric } 615e8d8bef9SDimitry Andric } 616e8d8bef9SDimitry Andric 617d409305fSDimitry Andric { 618d409305fSDimitry Andric // Identify what other metadata depends on the cloned version. After 619d409305fSDimitry Andric // cloning, replace the metadata with the corrected version for both 620d409305fSDimitry Andric // memory instructions and noalias intrinsics. 621d409305fSDimitry Andric std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 622d409305fSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 623d409305fSDimitry Andric Header->getContext(), Ext); 624d409305fSDimitry Andric } 625d409305fSDimitry Andric 626e8d8bef9SDimitry Andric // Recursively create the new Loop objects for nested loops, if any, 627e8d8bef9SDimitry Andric // to preserve LoopInfo. 628e8d8bef9SDimitry Andric for (Loop *ChildLoop : *L) { 629e8d8bef9SDimitry Andric cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 630e8d8bef9SDimitry Andric } 631e8d8bef9SDimitry Andric 632e8d8bef9SDimitry Andric // Hook-up the control flow for the newly inserted blocks. 633e8d8bef9SDimitry Andric // The new header is hooked up directly to the "top", which is either 634e8d8bef9SDimitry Andric // the original loop preheader (for the first iteration) or the previous 635e8d8bef9SDimitry Andric // iteration's exiting block (for every other iteration) 636e8d8bef9SDimitry Andric InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 637e8d8bef9SDimitry Andric 638e8d8bef9SDimitry Andric // Similarly, for the latch: 639e8d8bef9SDimitry Andric // The original exiting edge is still hooked up to the loop exit. 640e8d8bef9SDimitry Andric // The backedge now goes to the "bottom", which is either the loop's real 641e8d8bef9SDimitry Andric // header (for the last peeled iteration) or the copied header of the next 642e8d8bef9SDimitry Andric // iteration (for every other iteration) 643e8d8bef9SDimitry Andric BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 644e8d8bef9SDimitry Andric BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator()); 645e8d8bef9SDimitry Andric for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx) 646e8d8bef9SDimitry Andric if (LatchBR->getSuccessor(idx) == Header) { 647e8d8bef9SDimitry Andric LatchBR->setSuccessor(idx, InsertBot); 648e8d8bef9SDimitry Andric break; 649e8d8bef9SDimitry Andric } 650e8d8bef9SDimitry Andric if (DT) 651e8d8bef9SDimitry Andric DT->changeImmediateDominator(InsertBot, NewLatch); 652e8d8bef9SDimitry Andric 653e8d8bef9SDimitry Andric // The new copy of the loop body starts with a bunch of PHI nodes 654e8d8bef9SDimitry Andric // that pick an incoming value from either the preheader, or the previous 655e8d8bef9SDimitry Andric // loop iteration. Since this copy is no longer part of the loop, we 656e8d8bef9SDimitry Andric // resolve this statically: 657e8d8bef9SDimitry Andric // For the first iteration, we use the value from the preheader directly. 658e8d8bef9SDimitry Andric // For any other iteration, we replace the phi with the value generated by 659e8d8bef9SDimitry Andric // the immediately preceding clone of the loop body (which represents 660e8d8bef9SDimitry Andric // the previous iteration). 661e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 662e8d8bef9SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 663e8d8bef9SDimitry Andric if (IterNumber == 0) { 664e8d8bef9SDimitry Andric VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 665e8d8bef9SDimitry Andric } else { 666e8d8bef9SDimitry Andric Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 667e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 668e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 669e8d8bef9SDimitry Andric VMap[&*I] = LVMap[LatchInst]; 670e8d8bef9SDimitry Andric else 671e8d8bef9SDimitry Andric VMap[&*I] = LatchVal; 672e8d8bef9SDimitry Andric } 673e8d8bef9SDimitry Andric cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 674e8d8bef9SDimitry Andric } 675e8d8bef9SDimitry Andric 676e8d8bef9SDimitry Andric // Fix up the outgoing values - we need to add a value for the iteration 677e8d8bef9SDimitry Andric // we've just created. Note that this must happen *after* the incoming 678e8d8bef9SDimitry Andric // values are adjusted, since the value going out of the latch may also be 679e8d8bef9SDimitry Andric // a value coming into the header. 680e8d8bef9SDimitry Andric for (auto Edge : ExitEdges) 681e8d8bef9SDimitry Andric for (PHINode &PHI : Edge.second->phis()) { 682e8d8bef9SDimitry Andric Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 683e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 684e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 685e8d8bef9SDimitry Andric LatchVal = VMap[LatchVal]; 686e8d8bef9SDimitry Andric PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 687*81ad6265SDimitry Andric SE.forgetValue(&PHI); 688e8d8bef9SDimitry Andric } 689e8d8bef9SDimitry Andric 690e8d8bef9SDimitry Andric // LastValueMap is updated with the values for the current loop 691e8d8bef9SDimitry Andric // which are used the next time this function is called. 692e8d8bef9SDimitry Andric for (auto KV : VMap) 693e8d8bef9SDimitry Andric LVMap[KV.first] = KV.second; 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( 697e8d8bef9SDimitry Andric Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 698e8d8bef9SDimitry Andric Optional<bool> UserAllowPeeling, 699e8d8bef9SDimitry Andric Optional<bool> UserAllowProfileBasedPeeling, bool UnrollingSpecficValues) { 700e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences PP; 701e8d8bef9SDimitry Andric 702e8d8bef9SDimitry Andric // Set the default values. 703e8d8bef9SDimitry Andric PP.PeelCount = 0; 704e8d8bef9SDimitry Andric PP.AllowPeeling = true; 705e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = false; 706e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 707e8d8bef9SDimitry Andric 708e8d8bef9SDimitry Andric // Get the target specifc values. 709e8d8bef9SDimitry Andric TTI.getPeelingPreferences(L, SE, PP); 710e8d8bef9SDimitry Andric 711e8d8bef9SDimitry Andric // User specified values using cl::opt. 712e8d8bef9SDimitry Andric if (UnrollingSpecficValues) { 713e8d8bef9SDimitry Andric if (UnrollPeelCount.getNumOccurrences() > 0) 714e8d8bef9SDimitry Andric PP.PeelCount = UnrollPeelCount; 715e8d8bef9SDimitry Andric if (UnrollAllowPeeling.getNumOccurrences() > 0) 716e8d8bef9SDimitry Andric PP.AllowPeeling = UnrollAllowPeeling; 717e8d8bef9SDimitry Andric if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 718e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 719e8d8bef9SDimitry Andric } 720e8d8bef9SDimitry Andric 721e8d8bef9SDimitry Andric // User specifed values provided by argument. 722*81ad6265SDimitry Andric if (UserAllowPeeling) 723e8d8bef9SDimitry Andric PP.AllowPeeling = *UserAllowPeeling; 724*81ad6265SDimitry Andric if (UserAllowProfileBasedPeeling) 725e8d8bef9SDimitry Andric PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 726e8d8bef9SDimitry Andric 727e8d8bef9SDimitry Andric return PP; 728e8d8bef9SDimitry Andric } 729e8d8bef9SDimitry Andric 730e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L. 731e8d8bef9SDimitry Andric /// 732e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block. 733e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the 734e8d8bef9SDimitry Andric /// exit condition. 735e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less 736e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account 737e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar 738e8d8bef9SDimitry Andric /// optimizations. 739e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 7401fd87a68SDimitry Andric ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, 741e8d8bef9SDimitry Andric bool PreserveLCSSA) { 742e8d8bef9SDimitry Andric assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 743e8d8bef9SDimitry Andric assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 744e8d8bef9SDimitry Andric 745e8d8bef9SDimitry Andric LoopBlocksDFS LoopBlocks(L); 746e8d8bef9SDimitry Andric LoopBlocks.perform(LI); 747e8d8bef9SDimitry Andric 748e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 749e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 750e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 751e8d8bef9SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 752e8d8bef9SDimitry Andric L->getExitEdges(ExitEdges); 753e8d8bef9SDimitry Andric 754349cc55cSDimitry Andric // Remember dominators of blocks we might reach through exits to change them 755349cc55cSDimitry Andric // later. Immediate dominator of such block might change, because we add more 756349cc55cSDimitry Andric // routes which can lead to the exit: we can reach it from the peeled 757349cc55cSDimitry Andric // iterations too. 758349cc55cSDimitry Andric DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 759349cc55cSDimitry Andric for (auto *BB : L->blocks()) { 7601fd87a68SDimitry Andric auto *BBDomNode = DT.getNode(BB); 761349cc55cSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate; 762349cc55cSDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) { 763349cc55cSDimitry Andric auto *ChildBB = ChildDomNode->getBlock(); 764349cc55cSDimitry Andric if (!L->contains(ChildBB)) 765349cc55cSDimitry Andric ChildrenToUpdate.push_back(ChildBB); 766349cc55cSDimitry Andric } 767349cc55cSDimitry Andric // The new idom of the block will be the nearest common dominator 768349cc55cSDimitry Andric // of all copies of the previous idom. This is equivalent to the 769349cc55cSDimitry Andric // nearest common dominator of the previous idom and the first latch, 770349cc55cSDimitry Andric // which dominates all copies of the previous idom. 7711fd87a68SDimitry Andric BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch); 772349cc55cSDimitry Andric for (auto *ChildBB : ChildrenToUpdate) 773349cc55cSDimitry Andric NonLoopBlocksIDom[ChildBB] = NewIDom; 774e8d8bef9SDimitry Andric } 775e8d8bef9SDimitry Andric 776e8d8bef9SDimitry Andric Function *F = Header->getParent(); 777e8d8bef9SDimitry Andric 778e8d8bef9SDimitry Andric // Set up all the necessary basic blocks. It is convenient to split the 779e8d8bef9SDimitry Andric // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 780e8d8bef9SDimitry Andric // body, and a new preheader for the "real" loop. 781e8d8bef9SDimitry Andric 782e8d8bef9SDimitry Andric // Peeling the first iteration transforms. 783e8d8bef9SDimitry Andric // 784e8d8bef9SDimitry Andric // PreHeader: 785e8d8bef9SDimitry Andric // ... 786e8d8bef9SDimitry Andric // Header: 787e8d8bef9SDimitry Andric // LoopBody 788e8d8bef9SDimitry Andric // If (cond) goto Header 789e8d8bef9SDimitry Andric // Exit: 790e8d8bef9SDimitry Andric // 791e8d8bef9SDimitry Andric // into 792e8d8bef9SDimitry Andric // 793e8d8bef9SDimitry Andric // InsertTop: 794e8d8bef9SDimitry Andric // LoopBody 795e8d8bef9SDimitry Andric // If (!cond) goto Exit 796e8d8bef9SDimitry Andric // InsertBot: 797e8d8bef9SDimitry Andric // NewPreHeader: 798e8d8bef9SDimitry Andric // ... 799e8d8bef9SDimitry Andric // Header: 800e8d8bef9SDimitry Andric // LoopBody 801e8d8bef9SDimitry Andric // If (cond) goto Header 802e8d8bef9SDimitry Andric // Exit: 803e8d8bef9SDimitry Andric // 804e8d8bef9SDimitry Andric // Each following iteration will split the current bottom anchor in two, 805e8d8bef9SDimitry Andric // and put the new copy of the loop body between these two blocks. That is, 806e8d8bef9SDimitry Andric // after peeling another iteration from the example above, we'll split 807e8d8bef9SDimitry Andric // InsertBot, and get: 808e8d8bef9SDimitry Andric // 809e8d8bef9SDimitry Andric // InsertTop: 810e8d8bef9SDimitry Andric // LoopBody 811e8d8bef9SDimitry Andric // If (!cond) goto Exit 812e8d8bef9SDimitry Andric // InsertBot: 813e8d8bef9SDimitry Andric // LoopBody 814e8d8bef9SDimitry Andric // If (!cond) goto Exit 815e8d8bef9SDimitry Andric // InsertBot.next: 816e8d8bef9SDimitry Andric // NewPreHeader: 817e8d8bef9SDimitry Andric // ... 818e8d8bef9SDimitry Andric // Header: 819e8d8bef9SDimitry Andric // LoopBody 820e8d8bef9SDimitry Andric // If (cond) goto Header 821e8d8bef9SDimitry Andric // Exit: 822e8d8bef9SDimitry Andric 8231fd87a68SDimitry Andric BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI); 824e8d8bef9SDimitry Andric BasicBlock *InsertBot = 8251fd87a68SDimitry Andric SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI); 826e8d8bef9SDimitry Andric BasicBlock *NewPreHeader = 8271fd87a68SDimitry Andric SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 828e8d8bef9SDimitry Andric 829e8d8bef9SDimitry Andric InsertTop->setName(Header->getName() + ".peel.begin"); 830e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 831e8d8bef9SDimitry Andric NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 832e8d8bef9SDimitry Andric 833e8d8bef9SDimitry Andric ValueToValueMapTy LVMap; 834e8d8bef9SDimitry Andric 835e8d8bef9SDimitry Andric // If we have branch weight information, we'll want to update it for the 836e8d8bef9SDimitry Andric // newly created branches. 837e8d8bef9SDimitry Andric BranchInst *LatchBR = 838e8d8bef9SDimitry Andric cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator()); 839e8d8bef9SDimitry Andric uint64_t ExitWeight = 0, FallThroughWeight = 0; 840e8d8bef9SDimitry Andric initBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 841e8d8bef9SDimitry Andric 842d409305fSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the 843d409305fSDimitry Andric // loop, the associated metadata must be cloned for each iteration. 844d409305fSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 845d409305fSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 846d409305fSDimitry Andric 847e8d8bef9SDimitry Andric // For each peeled-off iteration, make a copy of the loop. 848e8d8bef9SDimitry Andric for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 849e8d8bef9SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks; 850e8d8bef9SDimitry Andric ValueToValueMapTy VMap; 851e8d8bef9SDimitry Andric 852e8d8bef9SDimitry Andric cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 8531fd87a68SDimitry Andric LoopBlocks, VMap, LVMap, &DT, LI, 854*81ad6265SDimitry Andric LoopLocalNoAliasDeclScopes, *SE); 855e8d8bef9SDimitry Andric 856e8d8bef9SDimitry Andric // Remap to use values from the current iteration instead of the 857e8d8bef9SDimitry Andric // previous one. 858e8d8bef9SDimitry Andric remapInstructionsInBlocks(NewBlocks, VMap); 859e8d8bef9SDimitry Andric 860349cc55cSDimitry Andric // Update IDoms of the blocks reachable through exits. 861e8d8bef9SDimitry Andric if (Iter == 0) 862349cc55cSDimitry Andric for (auto BBIDom : NonLoopBlocksIDom) 8631fd87a68SDimitry Andric DT.changeImmediateDominator(BBIDom.first, 864349cc55cSDimitry Andric cast<BasicBlock>(LVMap[BBIDom.second])); 865e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS 8661fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 867e8d8bef9SDimitry Andric #endif 868e8d8bef9SDimitry Andric 869e8d8bef9SDimitry Andric auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]); 870e8d8bef9SDimitry Andric updateBranchWeights(InsertBot, LatchBRCopy, ExitWeight, FallThroughWeight); 871e8d8bef9SDimitry Andric // Remove Loop metadata from the latch branch instruction 872e8d8bef9SDimitry Andric // because it is not the Loop's latch branch anymore. 873e8d8bef9SDimitry Andric LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr); 874e8d8bef9SDimitry Andric 875e8d8bef9SDimitry Andric InsertTop = InsertBot; 8761fd87a68SDimitry Andric InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 877e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 878e8d8bef9SDimitry Andric 879e8d8bef9SDimitry Andric F->getBasicBlockList().splice(InsertTop->getIterator(), 880e8d8bef9SDimitry Andric F->getBasicBlockList(), 881e8d8bef9SDimitry Andric NewBlocks[0]->getIterator(), F->end()); 882e8d8bef9SDimitry Andric } 883e8d8bef9SDimitry Andric 884e8d8bef9SDimitry Andric // Now adjust the phi nodes in the loop header to get their initial values 885e8d8bef9SDimitry Andric // from the last peeled-off iteration instead of the preheader. 886e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 887e8d8bef9SDimitry Andric PHINode *PHI = cast<PHINode>(I); 888e8d8bef9SDimitry Andric Value *NewVal = PHI->getIncomingValueForBlock(Latch); 889e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 890e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 891e8d8bef9SDimitry Andric NewVal = LVMap[LatchInst]; 892e8d8bef9SDimitry Andric 893e8d8bef9SDimitry Andric PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 894e8d8bef9SDimitry Andric } 895e8d8bef9SDimitry Andric 896e8d8bef9SDimitry Andric fixupBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 897e8d8bef9SDimitry Andric 898e8d8bef9SDimitry Andric // Update Metadata for count of peeled off iterations. 899e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 900e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 901e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 902e8d8bef9SDimitry Andric addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 903e8d8bef9SDimitry Andric 904e8d8bef9SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) 905e8d8bef9SDimitry Andric L = ParentLoop; 906e8d8bef9SDimitry Andric 907e8d8bef9SDimitry Andric // We modified the loop, update SE. 908e8d8bef9SDimitry Andric SE->forgetTopmostLoop(L); 909e8d8bef9SDimitry Andric 910*81ad6265SDimitry Andric #ifdef EXPENSIVE_CHECKS 911e8d8bef9SDimitry Andric // Finally DomtTree must be correct. 9121fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 913*81ad6265SDimitry Andric #endif 914e8d8bef9SDimitry Andric 915e8d8bef9SDimitry Andric // FIXME: Incrementally update loop-simplify 9161fd87a68SDimitry Andric simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA); 917e8d8bef9SDimitry Andric 918e8d8bef9SDimitry Andric NumPeeled++; 919e8d8bef9SDimitry Andric 920e8d8bef9SDimitry Andric return true; 921e8d8bef9SDimitry Andric } 922