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