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" 17*349cc55cSDimitry 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/Metadata.h" 32e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 33e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 34e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 35e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 36e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 37e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 39e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h" 40e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 41e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h" 42e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 43e8d8bef9SDimitry Andric #include <algorithm> 44e8d8bef9SDimitry Andric #include <cassert> 45e8d8bef9SDimitry Andric #include <cstdint> 46e8d8bef9SDimitry Andric #include <limits> 47e8d8bef9SDimitry Andric 48e8d8bef9SDimitry Andric using namespace llvm; 49e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 50e8d8bef9SDimitry Andric 51e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-peel" 52e8d8bef9SDimitry Andric 53e8d8bef9SDimitry Andric STATISTIC(NumPeeled, "Number of loops peeled"); 54e8d8bef9SDimitry Andric 55e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelCount( 56e8d8bef9SDimitry Andric "unroll-peel-count", cl::Hidden, 57e8d8bef9SDimitry Andric cl::desc("Set the unroll peeling count, for testing purposes")); 58e8d8bef9SDimitry Andric 59e8d8bef9SDimitry Andric static cl::opt<bool> 60e8d8bef9SDimitry Andric UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 61e8d8bef9SDimitry Andric cl::desc("Allows loops to be peeled when the dynamic " 62e8d8bef9SDimitry Andric "trip count is known to be low.")); 63e8d8bef9SDimitry Andric 64e8d8bef9SDimitry Andric static cl::opt<bool> 65e8d8bef9SDimitry Andric UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 66e8d8bef9SDimitry Andric cl::init(false), cl::Hidden, 67e8d8bef9SDimitry Andric cl::desc("Allows loop nests to be peeled.")); 68e8d8bef9SDimitry Andric 69e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelMaxCount( 70e8d8bef9SDimitry Andric "unroll-peel-max-count", cl::init(7), cl::Hidden, 71e8d8bef9SDimitry Andric cl::desc("Max average trip count which will cause loop peeling.")); 72e8d8bef9SDimitry Andric 73e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollForcePeelCount( 74e8d8bef9SDimitry Andric "unroll-force-peel-count", cl::init(0), cl::Hidden, 75e8d8bef9SDimitry Andric cl::desc("Force a peel count regardless of profiling information.")); 76e8d8bef9SDimitry Andric 77e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 78e8d8bef9SDimitry Andric 79e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop. 80e8d8bef9SDimitry Andric bool llvm::canPeel(Loop *L) { 81e8d8bef9SDimitry Andric // Make sure the loop is in simplified form 82e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) 83e8d8bef9SDimitry Andric return false; 84e8d8bef9SDimitry Andric 85e8d8bef9SDimitry Andric // Don't try to peel loops where the latch is not the exiting block. 86e8d8bef9SDimitry Andric // This can be an indication of two different things: 87e8d8bef9SDimitry Andric // 1) The loop is not rotated. 88e8d8bef9SDimitry Andric // 2) The loop contains irreducible control flow that involves the latch. 89e8d8bef9SDimitry Andric const BasicBlock *Latch = L->getLoopLatch(); 90*349cc55cSDimitry Andric if (!L->isLoopExiting(Latch)) 91e8d8bef9SDimitry Andric return false; 92e8d8bef9SDimitry Andric 93e8d8bef9SDimitry Andric // Peeling is only supported if the latch is a branch. 94e8d8bef9SDimitry Andric if (!isa<BranchInst>(Latch->getTerminator())) 95e8d8bef9SDimitry Andric return false; 96e8d8bef9SDimitry Andric 97*349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 98*349cc55cSDimitry Andric L->getUniqueNonLatchExitBlocks(Exits); 99*349cc55cSDimitry Andric // The latch must either be the only exiting block or all non-latch exit 100*349cc55cSDimitry Andric // blocks have either a deopt or unreachable terminator or compose a chain of 101*349cc55cSDimitry Andric // blocks where the last one is either deopt or unreachable terminated. Both 102*349cc55cSDimitry Andric // deopt and unreachable terminators are a strong indication they are not 103*349cc55cSDimitry Andric // taken. Note that this is a profitability check, not a legality check. Also 104*349cc55cSDimitry Andric // note that LoopPeeling currently can only update the branch weights of latch 105*349cc55cSDimitry Andric // blocks and branch weights to blocks with deopt or unreachable do not need 106*349cc55cSDimitry Andric // updating. 107*349cc55cSDimitry Andric return all_of(Exits, [](const BasicBlock *BB) { 108*349cc55cSDimitry Andric return IsBlockFollowedByDeoptOrUnreachable(BB); 109*349cc55cSDimitry Andric }); 110e8d8bef9SDimitry Andric } 111e8d8bef9SDimitry Andric 112e8d8bef9SDimitry Andric // This function calculates the number of iterations after which the given Phi 113e8d8bef9SDimitry Andric // becomes an invariant. The pre-calculated values are memorized in the map. The 114e8d8bef9SDimitry Andric // function (shortcut is I) is calculated according to the following definition: 115e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 116e8d8bef9SDimitry Andric // If %y is a loop invariant, then I(%x) = 1. 117e8d8bef9SDimitry Andric // If %y is a Phi from the loop header, I(%x) = I(%y) + 1. 118e8d8bef9SDimitry Andric // Otherwise, I(%x) is infinite. 119e8d8bef9SDimitry Andric // TODO: Actually if %y is an expression that depends only on Phi %z and some 120e8d8bef9SDimitry Andric // loop invariants, we can estimate I(%x) = I(%z) + 1. The example 121e8d8bef9SDimitry Andric // looks like: 122e8d8bef9SDimitry Andric // %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration. 123e8d8bef9SDimitry Andric // %y = phi(0, 5), 124e8d8bef9SDimitry Andric // %a = %y + 1. 125*349cc55cSDimitry Andric static Optional<unsigned> calculateIterationsToInvariance( 126e8d8bef9SDimitry Andric PHINode *Phi, Loop *L, BasicBlock *BackEdge, 127*349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned> > &IterationsToInvariance) { 128e8d8bef9SDimitry Andric assert(Phi->getParent() == L->getHeader() && 129e8d8bef9SDimitry Andric "Non-loop Phi should not be checked for turning into invariant."); 130e8d8bef9SDimitry Andric assert(BackEdge == L->getLoopLatch() && "Wrong latch?"); 131e8d8bef9SDimitry Andric // If we already know the answer, take it from the map. 132e8d8bef9SDimitry Andric auto I = IterationsToInvariance.find(Phi); 133e8d8bef9SDimitry Andric if (I != IterationsToInvariance.end()) 134e8d8bef9SDimitry Andric return I->second; 135e8d8bef9SDimitry Andric 136e8d8bef9SDimitry Andric // Otherwise we need to analyze the input from the back edge. 137e8d8bef9SDimitry Andric Value *Input = Phi->getIncomingValueForBlock(BackEdge); 138e8d8bef9SDimitry Andric // Place infinity to map to avoid infinite recursion for cycled Phis. Such 139e8d8bef9SDimitry Andric // cycles can never stop on an invariant. 140*349cc55cSDimitry Andric IterationsToInvariance[Phi] = None; 141*349cc55cSDimitry Andric Optional<unsigned> ToInvariance = None; 142e8d8bef9SDimitry Andric 143e8d8bef9SDimitry Andric if (L->isLoopInvariant(Input)) 144e8d8bef9SDimitry Andric ToInvariance = 1u; 145e8d8bef9SDimitry Andric else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) { 146e8d8bef9SDimitry Andric // Only consider Phis in header block. 147e8d8bef9SDimitry Andric if (IncPhi->getParent() != L->getHeader()) 148*349cc55cSDimitry Andric return None; 149e8d8bef9SDimitry Andric // If the input becomes an invariant after X iterations, then our Phi 150e8d8bef9SDimitry Andric // becomes an invariant after X + 1 iterations. 151*349cc55cSDimitry Andric auto InputToInvariance = calculateIterationsToInvariance( 152e8d8bef9SDimitry Andric IncPhi, L, BackEdge, IterationsToInvariance); 153*349cc55cSDimitry Andric if (InputToInvariance) 154*349cc55cSDimitry Andric ToInvariance = *InputToInvariance + 1u; 155e8d8bef9SDimitry Andric } 156e8d8bef9SDimitry Andric 157e8d8bef9SDimitry Andric // If we found that this Phi lies in an invariant chain, update the map. 158*349cc55cSDimitry Andric if (ToInvariance) 159e8d8bef9SDimitry Andric IterationsToInvariance[Phi] = ToInvariance; 160e8d8bef9SDimitry Andric return ToInvariance; 161e8d8bef9SDimitry Andric } 162e8d8bef9SDimitry Andric 163*349cc55cSDimitry Andric // Try to find any invariant memory reads that will become dereferenceable in 164*349cc55cSDimitry Andric // the remainder loop after peeling. The load must also be used (transitively) 165*349cc55cSDimitry Andric // by an exit condition. Returns the number of iterations to peel off (at the 166*349cc55cSDimitry Andric // moment either 0 or 1). 167*349cc55cSDimitry Andric static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 168*349cc55cSDimitry Andric DominatorTree &DT) { 169*349cc55cSDimitry Andric // Skip loops with a single exiting block, because there should be no benefit 170*349cc55cSDimitry Andric // for the heuristic below. 171*349cc55cSDimitry Andric if (L.getExitingBlock()) 172*349cc55cSDimitry Andric return 0; 173*349cc55cSDimitry Andric 174*349cc55cSDimitry Andric // All non-latch exit blocks must have an UnreachableInst terminator. 175*349cc55cSDimitry Andric // Otherwise the heuristic below may not be profitable. 176*349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 177*349cc55cSDimitry Andric L.getUniqueNonLatchExitBlocks(Exits); 178*349cc55cSDimitry Andric if (any_of(Exits, [](const BasicBlock *BB) { 179*349cc55cSDimitry Andric return !isa<UnreachableInst>(BB->getTerminator()); 180*349cc55cSDimitry Andric })) 181*349cc55cSDimitry Andric return 0; 182*349cc55cSDimitry Andric 183*349cc55cSDimitry Andric // Now look for invariant loads that dominate the latch and are not known to 184*349cc55cSDimitry Andric // be dereferenceable. If there are such loads and no writes, they will become 185*349cc55cSDimitry Andric // dereferenceable in the loop if the first iteration is peeled off. Also 186*349cc55cSDimitry Andric // collect the set of instructions controlled by such loads. Only peel if an 187*349cc55cSDimitry Andric // exit condition uses (transitively) such a load. 188*349cc55cSDimitry Andric BasicBlock *Header = L.getHeader(); 189*349cc55cSDimitry Andric BasicBlock *Latch = L.getLoopLatch(); 190*349cc55cSDimitry Andric SmallPtrSet<Value *, 8> LoadUsers; 191*349cc55cSDimitry Andric const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 192*349cc55cSDimitry Andric for (BasicBlock *BB : L.blocks()) { 193*349cc55cSDimitry Andric for (Instruction &I : *BB) { 194*349cc55cSDimitry Andric if (I.mayWriteToMemory()) 195*349cc55cSDimitry Andric return 0; 196*349cc55cSDimitry Andric 197*349cc55cSDimitry Andric auto Iter = LoadUsers.find(&I); 198*349cc55cSDimitry Andric if (Iter != LoadUsers.end()) { 199*349cc55cSDimitry Andric for (Value *U : I.users()) 200*349cc55cSDimitry Andric LoadUsers.insert(U); 201*349cc55cSDimitry Andric } 202*349cc55cSDimitry Andric // Do not look for reads in the header; they can already be hoisted 203*349cc55cSDimitry Andric // without peeling. 204*349cc55cSDimitry Andric if (BB == Header) 205*349cc55cSDimitry Andric continue; 206*349cc55cSDimitry Andric if (auto *LI = dyn_cast<LoadInst>(&I)) { 207*349cc55cSDimitry Andric Value *Ptr = LI->getPointerOperand(); 208*349cc55cSDimitry Andric if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 209*349cc55cSDimitry Andric !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, &DT)) 210*349cc55cSDimitry Andric for (Value *U : I.users()) 211*349cc55cSDimitry Andric LoadUsers.insert(U); 212*349cc55cSDimitry Andric } 213*349cc55cSDimitry Andric } 214*349cc55cSDimitry Andric } 215*349cc55cSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 216*349cc55cSDimitry Andric L.getExitingBlocks(ExitingBlocks); 217*349cc55cSDimitry Andric if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 218*349cc55cSDimitry Andric return LoadUsers.contains(Exiting->getTerminator()); 219*349cc55cSDimitry Andric })) 220*349cc55cSDimitry Andric return 1; 221*349cc55cSDimitry Andric return 0; 222*349cc55cSDimitry Andric } 223*349cc55cSDimitry Andric 224e8d8bef9SDimitry Andric // Return the number of iterations to peel off that make conditions in the 225e8d8bef9SDimitry Andric // body true/false. For example, if we peel 2 iterations off the loop below, 226e8d8bef9SDimitry Andric // the condition i < 2 can be evaluated at compile time. 227e8d8bef9SDimitry Andric // for (i = 0; i < n; i++) 228e8d8bef9SDimitry Andric // if (i < 2) 229e8d8bef9SDimitry Andric // .. 230e8d8bef9SDimitry Andric // else 231e8d8bef9SDimitry Andric // .. 232e8d8bef9SDimitry Andric // } 233e8d8bef9SDimitry Andric static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 234e8d8bef9SDimitry Andric ScalarEvolution &SE) { 235e8d8bef9SDimitry Andric assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 236e8d8bef9SDimitry Andric unsigned DesiredPeelCount = 0; 237e8d8bef9SDimitry Andric 238e8d8bef9SDimitry Andric for (auto *BB : L.blocks()) { 239e8d8bef9SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 240e8d8bef9SDimitry Andric if (!BI || BI->isUnconditional()) 241e8d8bef9SDimitry Andric continue; 242e8d8bef9SDimitry Andric 243e8d8bef9SDimitry Andric // Ignore loop exit condition. 244e8d8bef9SDimitry Andric if (L.getLoopLatch() == BB) 245e8d8bef9SDimitry Andric continue; 246e8d8bef9SDimitry Andric 247e8d8bef9SDimitry Andric Value *Condition = BI->getCondition(); 248e8d8bef9SDimitry Andric Value *LeftVal, *RightVal; 249e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 250e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 251e8d8bef9SDimitry Andric continue; 252e8d8bef9SDimitry Andric 253e8d8bef9SDimitry Andric const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 254e8d8bef9SDimitry Andric const SCEV *RightSCEV = SE.getSCEV(RightVal); 255e8d8bef9SDimitry Andric 256e8d8bef9SDimitry Andric // Do not consider predicates that are known to be true or false 257e8d8bef9SDimitry Andric // independently of the loop iteration. 258fe6060f1SDimitry Andric if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 259e8d8bef9SDimitry Andric continue; 260e8d8bef9SDimitry Andric 261e8d8bef9SDimitry Andric // Check if we have a condition with one AddRec and one non AddRec 262e8d8bef9SDimitry Andric // expression. Normalize LeftSCEV to be the AddRec. 263e8d8bef9SDimitry Andric if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 264e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(RightSCEV)) { 265e8d8bef9SDimitry Andric std::swap(LeftSCEV, RightSCEV); 266e8d8bef9SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 267e8d8bef9SDimitry Andric } else 268e8d8bef9SDimitry Andric continue; 269e8d8bef9SDimitry Andric } 270e8d8bef9SDimitry Andric 271e8d8bef9SDimitry Andric const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 272e8d8bef9SDimitry Andric 273e8d8bef9SDimitry Andric // Avoid huge SCEV computations in the loop below, make sure we only 274e8d8bef9SDimitry Andric // consider AddRecs of the loop we are trying to peel. 275e8d8bef9SDimitry Andric if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 276e8d8bef9SDimitry Andric continue; 277e8d8bef9SDimitry Andric if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 278e8d8bef9SDimitry Andric !SE.getMonotonicPredicateType(LeftAR, Pred)) 279e8d8bef9SDimitry Andric continue; 280e8d8bef9SDimitry Andric 281e8d8bef9SDimitry Andric // Check if extending the current DesiredPeelCount lets us evaluate Pred 282e8d8bef9SDimitry Andric // or !Pred in the loop body statically. 283e8d8bef9SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 284e8d8bef9SDimitry Andric 285e8d8bef9SDimitry Andric const SCEV *IterVal = LeftAR->evaluateAtIteration( 286e8d8bef9SDimitry Andric SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 287e8d8bef9SDimitry Andric 288e8d8bef9SDimitry Andric // If the original condition is not known, get the negated predicate 289e8d8bef9SDimitry Andric // (which holds on the else branch) and check if it is known. This allows 290e8d8bef9SDimitry Andric // us to peel of iterations that make the original condition false. 291e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 292e8d8bef9SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred); 293e8d8bef9SDimitry Andric 294e8d8bef9SDimitry Andric const SCEV *Step = LeftAR->getStepRecurrence(SE); 295e8d8bef9SDimitry Andric const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 296e8d8bef9SDimitry Andric auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 297e8d8bef9SDimitry Andric &NewPeelCount]() { 298e8d8bef9SDimitry Andric IterVal = NextIterVal; 299e8d8bef9SDimitry Andric NextIterVal = SE.getAddExpr(IterVal, Step); 300e8d8bef9SDimitry Andric NewPeelCount++; 301e8d8bef9SDimitry Andric }; 302e8d8bef9SDimitry Andric 303e8d8bef9SDimitry Andric auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 304e8d8bef9SDimitry Andric return NewPeelCount < MaxPeelCount; 305e8d8bef9SDimitry Andric }; 306e8d8bef9SDimitry Andric 307e8d8bef9SDimitry Andric while (CanPeelOneMoreIteration() && 308e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 309e8d8bef9SDimitry Andric PeelOneMoreIteration(); 310e8d8bef9SDimitry Andric 311e8d8bef9SDimitry Andric // With *that* peel count, does the predicate !Pred become known in the 312e8d8bef9SDimitry Andric // first iteration of the loop body after peeling? 313e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 314e8d8bef9SDimitry Andric RightSCEV)) 315e8d8bef9SDimitry Andric continue; // If not, give up. 316e8d8bef9SDimitry Andric 317e8d8bef9SDimitry Andric // However, for equality comparisons, that isn't always sufficient to 318e8d8bef9SDimitry Andric // eliminate the comparsion in loop body, we may need to peel one more 319e8d8bef9SDimitry Andric // iteration. See if that makes !Pred become unknown again. 320e8d8bef9SDimitry Andric if (ICmpInst::isEquality(Pred) && 321e8d8bef9SDimitry Andric !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 322e8d8bef9SDimitry Andric RightSCEV) && 323e8d8bef9SDimitry Andric !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 324e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 325e8d8bef9SDimitry Andric if (!CanPeelOneMoreIteration()) 326e8d8bef9SDimitry Andric continue; // Need to peel one more iteration, but can't. Give up. 327e8d8bef9SDimitry Andric PeelOneMoreIteration(); // Great! 328e8d8bef9SDimitry Andric } 329e8d8bef9SDimitry Andric 330e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 331e8d8bef9SDimitry Andric } 332e8d8bef9SDimitry Andric 333e8d8bef9SDimitry Andric return DesiredPeelCount; 334e8d8bef9SDimitry Andric } 335e8d8bef9SDimitry Andric 336e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off. 337e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize, 338e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences &PP, 339*349cc55cSDimitry Andric unsigned &TripCount, DominatorTree &DT, 340*349cc55cSDimitry Andric ScalarEvolution &SE, unsigned Threshold) { 341e8d8bef9SDimitry Andric assert(LoopSize > 0 && "Zero loop size is not allowed!"); 342e8d8bef9SDimitry Andric // Save the PP.PeelCount value set by the target in 343e8d8bef9SDimitry Andric // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 344e8d8bef9SDimitry Andric unsigned TargetPeelCount = PP.PeelCount; 345e8d8bef9SDimitry Andric PP.PeelCount = 0; 346e8d8bef9SDimitry Andric if (!canPeel(L)) 347e8d8bef9SDimitry Andric return; 348e8d8bef9SDimitry Andric 349e8d8bef9SDimitry Andric // Only try to peel innermost loops by default. 350e8d8bef9SDimitry Andric // The constraint can be relaxed by the target in TTI.getUnrollingPreferences 351e8d8bef9SDimitry Andric // or by the flag -unroll-allow-loop-nests-peeling. 352e8d8bef9SDimitry Andric if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 353e8d8bef9SDimitry Andric return; 354e8d8bef9SDimitry Andric 355e8d8bef9SDimitry Andric // If the user provided a peel count, use that. 356e8d8bef9SDimitry Andric bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 357e8d8bef9SDimitry Andric if (UserPeelCount) { 358e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 359e8d8bef9SDimitry Andric << " iterations.\n"); 360e8d8bef9SDimitry Andric PP.PeelCount = UnrollForcePeelCount; 361e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 362e8d8bef9SDimitry Andric return; 363e8d8bef9SDimitry Andric } 364e8d8bef9SDimitry Andric 365e8d8bef9SDimitry Andric // Skip peeling if it's disabled. 366e8d8bef9SDimitry Andric if (!PP.AllowPeeling) 367e8d8bef9SDimitry Andric return; 368e8d8bef9SDimitry Andric 369e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 370e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 371e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 372e8d8bef9SDimitry Andric // Stop if we already peeled off the maximum number of iterations. 373e8d8bef9SDimitry Andric if (AlreadyPeeled >= UnrollPeelMaxCount) 374e8d8bef9SDimitry Andric return; 375e8d8bef9SDimitry Andric 376e8d8bef9SDimitry Andric // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 377e8d8bef9SDimitry Andric // iterations of the loop. For this we compute the number for iterations after 378e8d8bef9SDimitry Andric // which every Phi is guaranteed to become an invariant, and try to peel the 379e8d8bef9SDimitry Andric // maximum number of iterations among these values, thus turning all those 380e8d8bef9SDimitry Andric // Phis into invariants. 381e8d8bef9SDimitry Andric // First, check that we can peel at least one iteration. 382e8d8bef9SDimitry Andric if (2 * LoopSize <= Threshold && UnrollPeelMaxCount > 0) { 383e8d8bef9SDimitry Andric // Store the pre-calculated values here. 384*349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned> > IterationsToInvariance; 385e8d8bef9SDimitry Andric // Now go through all Phis to calculate their the number of iterations they 386e8d8bef9SDimitry Andric // need to become invariants. 387e8d8bef9SDimitry Andric // Start the max computation with the UP.PeelCount value set by the target 388e8d8bef9SDimitry Andric // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count. 389e8d8bef9SDimitry Andric unsigned DesiredPeelCount = TargetPeelCount; 390e8d8bef9SDimitry Andric BasicBlock *BackEdge = L->getLoopLatch(); 391e8d8bef9SDimitry Andric assert(BackEdge && "Loop is not in simplified form?"); 392e8d8bef9SDimitry Andric for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) { 393e8d8bef9SDimitry Andric PHINode *Phi = cast<PHINode>(&*BI); 394*349cc55cSDimitry Andric auto ToInvariance = calculateIterationsToInvariance( 395e8d8bef9SDimitry Andric Phi, L, BackEdge, IterationsToInvariance); 396*349cc55cSDimitry Andric if (ToInvariance) 397*349cc55cSDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, *ToInvariance); 398e8d8bef9SDimitry Andric } 399e8d8bef9SDimitry Andric 400e8d8bef9SDimitry Andric // Pay respect to limitations implied by loop size and the max peel count. 401e8d8bef9SDimitry Andric unsigned MaxPeelCount = UnrollPeelMaxCount; 402e8d8bef9SDimitry Andric MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 403e8d8bef9SDimitry Andric 404e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, 405e8d8bef9SDimitry Andric countToEliminateCompares(*L, MaxPeelCount, SE)); 406e8d8bef9SDimitry Andric 407*349cc55cSDimitry Andric if (DesiredPeelCount == 0) 408*349cc55cSDimitry Andric DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT); 409*349cc55cSDimitry Andric 410e8d8bef9SDimitry Andric if (DesiredPeelCount > 0) { 411e8d8bef9SDimitry Andric DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 412e8d8bef9SDimitry Andric // Consider max peel count limitation. 413e8d8bef9SDimitry Andric assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 414e8d8bef9SDimitry Andric if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 415e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 416e8d8bef9SDimitry Andric << " iteration(s) to turn" 417e8d8bef9SDimitry Andric << " some Phis into invariants.\n"); 418e8d8bef9SDimitry Andric PP.PeelCount = DesiredPeelCount; 419e8d8bef9SDimitry Andric PP.PeelProfiledIterations = false; 420e8d8bef9SDimitry Andric return; 421e8d8bef9SDimitry Andric } 422e8d8bef9SDimitry Andric } 423e8d8bef9SDimitry Andric } 424e8d8bef9SDimitry Andric 425e8d8bef9SDimitry Andric // Bail if we know the statically calculated trip count. 426e8d8bef9SDimitry Andric // In this case we rather prefer partial unrolling. 427e8d8bef9SDimitry Andric if (TripCount) 428e8d8bef9SDimitry Andric return; 429e8d8bef9SDimitry Andric 430e8d8bef9SDimitry Andric // Do not apply profile base peeling if it is disabled. 431e8d8bef9SDimitry Andric if (!PP.PeelProfiledIterations) 432e8d8bef9SDimitry Andric return; 433e8d8bef9SDimitry Andric // If we don't know the trip count, but have reason to believe the average 434e8d8bef9SDimitry Andric // trip count is low, peeling should be beneficial, since we will usually 435e8d8bef9SDimitry Andric // hit the peeled section. 436e8d8bef9SDimitry Andric // We only do this in the presence of profile information, since otherwise 437e8d8bef9SDimitry Andric // our estimates of the trip count are not reliable enough. 438e8d8bef9SDimitry Andric if (L->getHeader()->getParent()->hasProfileData()) { 439e8d8bef9SDimitry Andric Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L); 440e8d8bef9SDimitry Andric if (!PeelCount) 441e8d8bef9SDimitry Andric return; 442e8d8bef9SDimitry Andric 443e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount 444e8d8bef9SDimitry Andric << "\n"); 445e8d8bef9SDimitry Andric 446e8d8bef9SDimitry Andric if (*PeelCount) { 447e8d8bef9SDimitry Andric if ((*PeelCount + AlreadyPeeled <= UnrollPeelMaxCount) && 448e8d8bef9SDimitry Andric (LoopSize * (*PeelCount + 1) <= Threshold)) { 449e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount 450e8d8bef9SDimitry Andric << " iterations.\n"); 451e8d8bef9SDimitry Andric PP.PeelCount = *PeelCount; 452e8d8bef9SDimitry Andric return; 453e8d8bef9SDimitry Andric } 454e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n"); 455e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 456e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 457e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) 458e8d8bef9SDimitry Andric << "\n"); 459e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 460e8d8bef9SDimitry Andric } 461e8d8bef9SDimitry Andric } 462e8d8bef9SDimitry Andric } 463e8d8bef9SDimitry Andric 464e8d8bef9SDimitry Andric /// Update the branch weights of the latch of a peeled-off loop 465e8d8bef9SDimitry Andric /// iteration. 466e8d8bef9SDimitry Andric /// This sets the branch weights for the latch of the recently peeled off loop 467e8d8bef9SDimitry Andric /// iteration correctly. 468e8d8bef9SDimitry Andric /// Let F is a weight of the edge from latch to header. 469e8d8bef9SDimitry Andric /// Let E is a weight of the edge from latch to exit. 470e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 471e8d8bef9SDimitry Andric /// go to exit. 472e8d8bef9SDimitry Andric /// Then, Estimated TripCount = F / E. 473e8d8bef9SDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the the weights for 474e8d8bef9SDimitry Andric /// the peeled latch as (TC - I, 1). It gives us reasonable distribution, 475e8d8bef9SDimitry Andric /// The probability to go to exit 1/(TC-I) increases. At the same time 476e8d8bef9SDimitry Andric /// the estimated trip count of remaining loop reduces by I. 477e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part 478e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E). 479e8d8bef9SDimitry Andric /// 480e8d8bef9SDimitry Andric /// \param Header The copy of the header block that belongs to next iteration. 481e8d8bef9SDimitry Andric /// \param LatchBR The copy of the latch branch that belongs to this iteration. 482e8d8bef9SDimitry Andric /// \param[in,out] FallThroughWeight The weight of the edge from latch to 483e8d8bef9SDimitry Andric /// header before peeling (in) and after peeled off one iteration (out). 484e8d8bef9SDimitry Andric static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 485e8d8bef9SDimitry Andric uint64_t ExitWeight, 486e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 487e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 488e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 489e8d8bef9SDimitry Andric if (!FallThroughWeight) 490e8d8bef9SDimitry Andric return; 491e8d8bef9SDimitry Andric 492e8d8bef9SDimitry Andric unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1); 493e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 494e8d8bef9SDimitry Andric MDNode *WeightNode = 495e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 496e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 497e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 498e8d8bef9SDimitry Andric FallThroughWeight = 499e8d8bef9SDimitry Andric FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1; 500e8d8bef9SDimitry Andric } 501e8d8bef9SDimitry Andric 502e8d8bef9SDimitry Andric /// Initialize the weights. 503e8d8bef9SDimitry Andric /// 504e8d8bef9SDimitry Andric /// \param Header The header block. 505e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 506e8d8bef9SDimitry Andric /// \param[out] ExitWeight The weight of the edge from Latch to Exit. 507e8d8bef9SDimitry Andric /// \param[out] FallThroughWeight The weight of the edge from Latch to Header. 508e8d8bef9SDimitry Andric static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 509e8d8bef9SDimitry Andric uint64_t &ExitWeight, 510e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 511e8d8bef9SDimitry Andric uint64_t TrueWeight, FalseWeight; 512e8d8bef9SDimitry Andric if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) 513e8d8bef9SDimitry Andric return; 514e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 515e8d8bef9SDimitry Andric ExitWeight = HeaderIdx ? TrueWeight : FalseWeight; 516e8d8bef9SDimitry Andric FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight; 517e8d8bef9SDimitry Andric } 518e8d8bef9SDimitry Andric 519e8d8bef9SDimitry Andric /// Update the weights of original Latch block after peeling off all iterations. 520e8d8bef9SDimitry Andric /// 521e8d8bef9SDimitry Andric /// \param Header The header block. 522e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 523e8d8bef9SDimitry Andric /// \param ExitWeight The weight of the edge from Latch to Exit. 524e8d8bef9SDimitry Andric /// \param FallThroughWeight The weight of the edge from Latch to Header. 525e8d8bef9SDimitry Andric static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 526e8d8bef9SDimitry Andric uint64_t ExitWeight, 527e8d8bef9SDimitry Andric uint64_t FallThroughWeight) { 528e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 529e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 530e8d8bef9SDimitry Andric if (!FallThroughWeight) 531e8d8bef9SDimitry Andric return; 532e8d8bef9SDimitry Andric 533e8d8bef9SDimitry Andric // Sets the branch weights on the loop exit. 534e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 535e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 536e8d8bef9SDimitry Andric MDNode *WeightNode = 537e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 538e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 539e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 540e8d8bef9SDimitry Andric } 541e8d8bef9SDimitry Andric 542e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p 543e8d8bef9SDimitry Andric /// InsertBot. 544e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being 545e8d8bef9SDimitry Andric /// peeled off. 546e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop. 547e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone 548e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone. 549e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop. 550e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to 551e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration. 552e8d8bef9SDimitry Andric static void cloneLoopBlocks( 553e8d8bef9SDimitry Andric Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 554e8d8bef9SDimitry Andric SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 555e8d8bef9SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 556e8d8bef9SDimitry Andric ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 557d409305fSDimitry Andric LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes) { 558e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 559e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 560e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 561e8d8bef9SDimitry Andric 562e8d8bef9SDimitry Andric Function *F = Header->getParent(); 563e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 564e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 565e8d8bef9SDimitry Andric Loop *ParentLoop = L->getParentLoop(); 566e8d8bef9SDimitry Andric 567e8d8bef9SDimitry Andric // For each block in the original loop, create a new copy, 568e8d8bef9SDimitry Andric // and update the value map with the newly created values. 569e8d8bef9SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 570e8d8bef9SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 571e8d8bef9SDimitry Andric NewBlocks.push_back(NewBB); 572e8d8bef9SDimitry Andric 573e8d8bef9SDimitry Andric // If an original block is an immediate child of the loop L, its copy 574e8d8bef9SDimitry Andric // is a child of a ParentLoop after peeling. If a block is a child of 575e8d8bef9SDimitry Andric // a nested loop, it is handled in the cloneLoop() call below. 576e8d8bef9SDimitry Andric if (ParentLoop && LI->getLoopFor(*BB) == L) 577e8d8bef9SDimitry Andric ParentLoop->addBasicBlockToLoop(NewBB, *LI); 578e8d8bef9SDimitry Andric 579e8d8bef9SDimitry Andric VMap[*BB] = NewBB; 580e8d8bef9SDimitry Andric 581e8d8bef9SDimitry Andric // If dominator tree is available, insert nodes to represent cloned blocks. 582e8d8bef9SDimitry Andric if (DT) { 583e8d8bef9SDimitry Andric if (Header == *BB) 584e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, InsertTop); 585e8d8bef9SDimitry Andric else { 586e8d8bef9SDimitry Andric DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 587e8d8bef9SDimitry Andric // VMap must contain entry for IDom, as the iteration order is RPO. 588e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 589e8d8bef9SDimitry Andric } 590e8d8bef9SDimitry Andric } 591e8d8bef9SDimitry Andric } 592e8d8bef9SDimitry Andric 593d409305fSDimitry Andric { 594d409305fSDimitry Andric // Identify what other metadata depends on the cloned version. After 595d409305fSDimitry Andric // cloning, replace the metadata with the corrected version for both 596d409305fSDimitry Andric // memory instructions and noalias intrinsics. 597d409305fSDimitry Andric std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 598d409305fSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 599d409305fSDimitry Andric Header->getContext(), Ext); 600d409305fSDimitry Andric } 601d409305fSDimitry Andric 602e8d8bef9SDimitry Andric // Recursively create the new Loop objects for nested loops, if any, 603e8d8bef9SDimitry Andric // to preserve LoopInfo. 604e8d8bef9SDimitry Andric for (Loop *ChildLoop : *L) { 605e8d8bef9SDimitry Andric cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 606e8d8bef9SDimitry Andric } 607e8d8bef9SDimitry Andric 608e8d8bef9SDimitry Andric // Hook-up the control flow for the newly inserted blocks. 609e8d8bef9SDimitry Andric // The new header is hooked up directly to the "top", which is either 610e8d8bef9SDimitry Andric // the original loop preheader (for the first iteration) or the previous 611e8d8bef9SDimitry Andric // iteration's exiting block (for every other iteration) 612e8d8bef9SDimitry Andric InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 613e8d8bef9SDimitry Andric 614e8d8bef9SDimitry Andric // Similarly, for the latch: 615e8d8bef9SDimitry Andric // The original exiting edge is still hooked up to the loop exit. 616e8d8bef9SDimitry Andric // The backedge now goes to the "bottom", which is either the loop's real 617e8d8bef9SDimitry Andric // header (for the last peeled iteration) or the copied header of the next 618e8d8bef9SDimitry Andric // iteration (for every other iteration) 619e8d8bef9SDimitry Andric BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 620e8d8bef9SDimitry Andric BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator()); 621e8d8bef9SDimitry Andric for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx) 622e8d8bef9SDimitry Andric if (LatchBR->getSuccessor(idx) == Header) { 623e8d8bef9SDimitry Andric LatchBR->setSuccessor(idx, InsertBot); 624e8d8bef9SDimitry Andric break; 625e8d8bef9SDimitry Andric } 626e8d8bef9SDimitry Andric if (DT) 627e8d8bef9SDimitry Andric DT->changeImmediateDominator(InsertBot, NewLatch); 628e8d8bef9SDimitry Andric 629e8d8bef9SDimitry Andric // The new copy of the loop body starts with a bunch of PHI nodes 630e8d8bef9SDimitry Andric // that pick an incoming value from either the preheader, or the previous 631e8d8bef9SDimitry Andric // loop iteration. Since this copy is no longer part of the loop, we 632e8d8bef9SDimitry Andric // resolve this statically: 633e8d8bef9SDimitry Andric // For the first iteration, we use the value from the preheader directly. 634e8d8bef9SDimitry Andric // For any other iteration, we replace the phi with the value generated by 635e8d8bef9SDimitry Andric // the immediately preceding clone of the loop body (which represents 636e8d8bef9SDimitry Andric // the previous iteration). 637e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 638e8d8bef9SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 639e8d8bef9SDimitry Andric if (IterNumber == 0) { 640e8d8bef9SDimitry Andric VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 641e8d8bef9SDimitry Andric } else { 642e8d8bef9SDimitry Andric Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 643e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 644e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 645e8d8bef9SDimitry Andric VMap[&*I] = LVMap[LatchInst]; 646e8d8bef9SDimitry Andric else 647e8d8bef9SDimitry Andric VMap[&*I] = LatchVal; 648e8d8bef9SDimitry Andric } 649e8d8bef9SDimitry Andric cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 650e8d8bef9SDimitry Andric } 651e8d8bef9SDimitry Andric 652e8d8bef9SDimitry Andric // Fix up the outgoing values - we need to add a value for the iteration 653e8d8bef9SDimitry Andric // we've just created. Note that this must happen *after* the incoming 654e8d8bef9SDimitry Andric // values are adjusted, since the value going out of the latch may also be 655e8d8bef9SDimitry Andric // a value coming into the header. 656e8d8bef9SDimitry Andric for (auto Edge : ExitEdges) 657e8d8bef9SDimitry Andric for (PHINode &PHI : Edge.second->phis()) { 658e8d8bef9SDimitry Andric Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 659e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 660e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 661e8d8bef9SDimitry Andric LatchVal = VMap[LatchVal]; 662e8d8bef9SDimitry Andric PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 663e8d8bef9SDimitry Andric } 664e8d8bef9SDimitry Andric 665e8d8bef9SDimitry Andric // LastValueMap is updated with the values for the current loop 666e8d8bef9SDimitry Andric // which are used the next time this function is called. 667e8d8bef9SDimitry Andric for (auto KV : VMap) 668e8d8bef9SDimitry Andric LVMap[KV.first] = KV.second; 669e8d8bef9SDimitry Andric } 670e8d8bef9SDimitry Andric 671e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( 672e8d8bef9SDimitry Andric Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 673e8d8bef9SDimitry Andric Optional<bool> UserAllowPeeling, 674e8d8bef9SDimitry Andric Optional<bool> UserAllowProfileBasedPeeling, bool UnrollingSpecficValues) { 675e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences PP; 676e8d8bef9SDimitry Andric 677e8d8bef9SDimitry Andric // Set the default values. 678e8d8bef9SDimitry Andric PP.PeelCount = 0; 679e8d8bef9SDimitry Andric PP.AllowPeeling = true; 680e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = false; 681e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 682e8d8bef9SDimitry Andric 683e8d8bef9SDimitry Andric // Get the target specifc values. 684e8d8bef9SDimitry Andric TTI.getPeelingPreferences(L, SE, PP); 685e8d8bef9SDimitry Andric 686e8d8bef9SDimitry Andric // User specified values using cl::opt. 687e8d8bef9SDimitry Andric if (UnrollingSpecficValues) { 688e8d8bef9SDimitry Andric if (UnrollPeelCount.getNumOccurrences() > 0) 689e8d8bef9SDimitry Andric PP.PeelCount = UnrollPeelCount; 690e8d8bef9SDimitry Andric if (UnrollAllowPeeling.getNumOccurrences() > 0) 691e8d8bef9SDimitry Andric PP.AllowPeeling = UnrollAllowPeeling; 692e8d8bef9SDimitry Andric if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 693e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696e8d8bef9SDimitry Andric // User specifed values provided by argument. 697e8d8bef9SDimitry Andric if (UserAllowPeeling.hasValue()) 698e8d8bef9SDimitry Andric PP.AllowPeeling = *UserAllowPeeling; 699e8d8bef9SDimitry Andric if (UserAllowProfileBasedPeeling.hasValue()) 700e8d8bef9SDimitry Andric PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 701e8d8bef9SDimitry Andric 702e8d8bef9SDimitry Andric return PP; 703e8d8bef9SDimitry Andric } 704e8d8bef9SDimitry Andric 705e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L. 706e8d8bef9SDimitry Andric /// 707e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block. 708e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the 709e8d8bef9SDimitry Andric /// exit condition. 710e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less 711e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account 712e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar 713e8d8bef9SDimitry Andric /// optimizations. 714e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 715e8d8bef9SDimitry Andric ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, 716e8d8bef9SDimitry Andric bool PreserveLCSSA) { 717e8d8bef9SDimitry Andric assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 718e8d8bef9SDimitry Andric assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 719e8d8bef9SDimitry Andric 720e8d8bef9SDimitry Andric LoopBlocksDFS LoopBlocks(L); 721e8d8bef9SDimitry Andric LoopBlocks.perform(LI); 722e8d8bef9SDimitry Andric 723e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 724e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 725e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 726e8d8bef9SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 727e8d8bef9SDimitry Andric L->getExitEdges(ExitEdges); 728e8d8bef9SDimitry Andric 729*349cc55cSDimitry Andric // Remember dominators of blocks we might reach through exits to change them 730*349cc55cSDimitry Andric // later. Immediate dominator of such block might change, because we add more 731*349cc55cSDimitry Andric // routes which can lead to the exit: we can reach it from the peeled 732*349cc55cSDimitry Andric // iterations too. 733*349cc55cSDimitry Andric DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 734e8d8bef9SDimitry Andric if (DT) { 735*349cc55cSDimitry Andric for (auto *BB : L->blocks()) { 736*349cc55cSDimitry Andric auto *BBDomNode = DT->getNode(BB); 737*349cc55cSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate; 738*349cc55cSDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) { 739*349cc55cSDimitry Andric auto *ChildBB = ChildDomNode->getBlock(); 740*349cc55cSDimitry Andric if (!L->contains(ChildBB)) 741*349cc55cSDimitry Andric ChildrenToUpdate.push_back(ChildBB); 742*349cc55cSDimitry Andric } 743*349cc55cSDimitry Andric // The new idom of the block will be the nearest common dominator 744*349cc55cSDimitry Andric // of all copies of the previous idom. This is equivalent to the 745*349cc55cSDimitry Andric // nearest common dominator of the previous idom and the first latch, 746*349cc55cSDimitry Andric // which dominates all copies of the previous idom. 747*349cc55cSDimitry Andric BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, Latch); 748*349cc55cSDimitry Andric for (auto *ChildBB : ChildrenToUpdate) 749*349cc55cSDimitry Andric NonLoopBlocksIDom[ChildBB] = NewIDom; 750e8d8bef9SDimitry Andric } 751e8d8bef9SDimitry Andric } 752e8d8bef9SDimitry Andric 753e8d8bef9SDimitry Andric Function *F = Header->getParent(); 754e8d8bef9SDimitry Andric 755e8d8bef9SDimitry Andric // Set up all the necessary basic blocks. It is convenient to split the 756e8d8bef9SDimitry Andric // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 757e8d8bef9SDimitry Andric // body, and a new preheader for the "real" loop. 758e8d8bef9SDimitry Andric 759e8d8bef9SDimitry Andric // Peeling the first iteration transforms. 760e8d8bef9SDimitry Andric // 761e8d8bef9SDimitry Andric // PreHeader: 762e8d8bef9SDimitry Andric // ... 763e8d8bef9SDimitry Andric // Header: 764e8d8bef9SDimitry Andric // LoopBody 765e8d8bef9SDimitry Andric // If (cond) goto Header 766e8d8bef9SDimitry Andric // Exit: 767e8d8bef9SDimitry Andric // 768e8d8bef9SDimitry Andric // into 769e8d8bef9SDimitry Andric // 770e8d8bef9SDimitry Andric // InsertTop: 771e8d8bef9SDimitry Andric // LoopBody 772e8d8bef9SDimitry Andric // If (!cond) goto Exit 773e8d8bef9SDimitry Andric // InsertBot: 774e8d8bef9SDimitry Andric // NewPreHeader: 775e8d8bef9SDimitry Andric // ... 776e8d8bef9SDimitry Andric // Header: 777e8d8bef9SDimitry Andric // LoopBody 778e8d8bef9SDimitry Andric // If (cond) goto Header 779e8d8bef9SDimitry Andric // Exit: 780e8d8bef9SDimitry Andric // 781e8d8bef9SDimitry Andric // Each following iteration will split the current bottom anchor in two, 782e8d8bef9SDimitry Andric // and put the new copy of the loop body between these two blocks. That is, 783e8d8bef9SDimitry Andric // after peeling another iteration from the example above, we'll split 784e8d8bef9SDimitry Andric // InsertBot, and get: 785e8d8bef9SDimitry Andric // 786e8d8bef9SDimitry Andric // InsertTop: 787e8d8bef9SDimitry Andric // LoopBody 788e8d8bef9SDimitry Andric // If (!cond) goto Exit 789e8d8bef9SDimitry Andric // InsertBot: 790e8d8bef9SDimitry Andric // LoopBody 791e8d8bef9SDimitry Andric // If (!cond) goto Exit 792e8d8bef9SDimitry Andric // InsertBot.next: 793e8d8bef9SDimitry Andric // NewPreHeader: 794e8d8bef9SDimitry Andric // ... 795e8d8bef9SDimitry Andric // Header: 796e8d8bef9SDimitry Andric // LoopBody 797e8d8bef9SDimitry Andric // If (cond) goto Header 798e8d8bef9SDimitry Andric // Exit: 799e8d8bef9SDimitry Andric 800e8d8bef9SDimitry Andric BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI); 801e8d8bef9SDimitry Andric BasicBlock *InsertBot = 802e8d8bef9SDimitry Andric SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI); 803e8d8bef9SDimitry Andric BasicBlock *NewPreHeader = 804e8d8bef9SDimitry Andric SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 805e8d8bef9SDimitry Andric 806e8d8bef9SDimitry Andric InsertTop->setName(Header->getName() + ".peel.begin"); 807e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 808e8d8bef9SDimitry Andric NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 809e8d8bef9SDimitry Andric 810e8d8bef9SDimitry Andric ValueToValueMapTy LVMap; 811e8d8bef9SDimitry Andric 812e8d8bef9SDimitry Andric // If we have branch weight information, we'll want to update it for the 813e8d8bef9SDimitry Andric // newly created branches. 814e8d8bef9SDimitry Andric BranchInst *LatchBR = 815e8d8bef9SDimitry Andric cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator()); 816e8d8bef9SDimitry Andric uint64_t ExitWeight = 0, FallThroughWeight = 0; 817e8d8bef9SDimitry Andric initBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 818e8d8bef9SDimitry Andric 819d409305fSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the 820d409305fSDimitry Andric // loop, the associated metadata must be cloned for each iteration. 821d409305fSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 822d409305fSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 823d409305fSDimitry Andric 824e8d8bef9SDimitry Andric // For each peeled-off iteration, make a copy of the loop. 825e8d8bef9SDimitry Andric for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 826e8d8bef9SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks; 827e8d8bef9SDimitry Andric ValueToValueMapTy VMap; 828e8d8bef9SDimitry Andric 829e8d8bef9SDimitry Andric cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 830d409305fSDimitry Andric LoopBlocks, VMap, LVMap, DT, LI, 831d409305fSDimitry Andric LoopLocalNoAliasDeclScopes); 832e8d8bef9SDimitry Andric 833e8d8bef9SDimitry Andric // Remap to use values from the current iteration instead of the 834e8d8bef9SDimitry Andric // previous one. 835e8d8bef9SDimitry Andric remapInstructionsInBlocks(NewBlocks, VMap); 836e8d8bef9SDimitry Andric 837e8d8bef9SDimitry Andric if (DT) { 838*349cc55cSDimitry Andric // Update IDoms of the blocks reachable through exits. 839e8d8bef9SDimitry Andric if (Iter == 0) 840*349cc55cSDimitry Andric for (auto BBIDom : NonLoopBlocksIDom) 841*349cc55cSDimitry Andric DT->changeImmediateDominator(BBIDom.first, 842*349cc55cSDimitry Andric cast<BasicBlock>(LVMap[BBIDom.second])); 843e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS 844e8d8bef9SDimitry Andric assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 845e8d8bef9SDimitry Andric #endif 846e8d8bef9SDimitry Andric } 847e8d8bef9SDimitry Andric 848e8d8bef9SDimitry Andric auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]); 849e8d8bef9SDimitry Andric updateBranchWeights(InsertBot, LatchBRCopy, ExitWeight, FallThroughWeight); 850e8d8bef9SDimitry Andric // Remove Loop metadata from the latch branch instruction 851e8d8bef9SDimitry Andric // because it is not the Loop's latch branch anymore. 852e8d8bef9SDimitry Andric LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr); 853e8d8bef9SDimitry Andric 854e8d8bef9SDimitry Andric InsertTop = InsertBot; 855e8d8bef9SDimitry Andric InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 856e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 857e8d8bef9SDimitry Andric 858e8d8bef9SDimitry Andric F->getBasicBlockList().splice(InsertTop->getIterator(), 859e8d8bef9SDimitry Andric F->getBasicBlockList(), 860e8d8bef9SDimitry Andric NewBlocks[0]->getIterator(), F->end()); 861e8d8bef9SDimitry Andric } 862e8d8bef9SDimitry Andric 863e8d8bef9SDimitry Andric // Now adjust the phi nodes in the loop header to get their initial values 864e8d8bef9SDimitry Andric // from the last peeled-off iteration instead of the preheader. 865e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 866e8d8bef9SDimitry Andric PHINode *PHI = cast<PHINode>(I); 867e8d8bef9SDimitry Andric Value *NewVal = PHI->getIncomingValueForBlock(Latch); 868e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 869e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 870e8d8bef9SDimitry Andric NewVal = LVMap[LatchInst]; 871e8d8bef9SDimitry Andric 872e8d8bef9SDimitry Andric PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 873e8d8bef9SDimitry Andric } 874e8d8bef9SDimitry Andric 875e8d8bef9SDimitry Andric fixupBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 876e8d8bef9SDimitry Andric 877e8d8bef9SDimitry Andric // Update Metadata for count of peeled off iterations. 878e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 879e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 880e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 881e8d8bef9SDimitry Andric addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 882e8d8bef9SDimitry Andric 883e8d8bef9SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) 884e8d8bef9SDimitry Andric L = ParentLoop; 885e8d8bef9SDimitry Andric 886e8d8bef9SDimitry Andric // We modified the loop, update SE. 887e8d8bef9SDimitry Andric SE->forgetTopmostLoop(L); 888e8d8bef9SDimitry Andric 889e8d8bef9SDimitry Andric // Finally DomtTree must be correct. 890e8d8bef9SDimitry Andric assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 891e8d8bef9SDimitry Andric 892e8d8bef9SDimitry Andric // FIXME: Incrementally update loop-simplify 893e8d8bef9SDimitry Andric simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA); 894e8d8bef9SDimitry Andric 895e8d8bef9SDimitry Andric NumPeeled++; 896e8d8bef9SDimitry Andric 897e8d8bef9SDimitry Andric return true; 898e8d8bef9SDimitry Andric } 899