blob: deb38df4420f6544ebaeef30bbcb656c9c822a70 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- UnrollLoopPeel.cpp - Loop peeling utilities ------------------------===//
Michael Kupersteinb151a642016-11-30 21:13:57 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael Kupersteinb151a642016-11-30 21:13:57 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements some loop unrolling utilities for peeling loops
10// with dynamically inferred (from PGO) trip counts. See LoopUnroll.cpp for
11// unrolling loops with compile-time constant trip counts.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/SmallVector.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000018#include "llvm/ADT/Statistic.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000019#include "llvm/Analysis/LoopInfo.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000020#include "llvm/Analysis/LoopIterator.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000021#include "llvm/Analysis/ScalarEvolution.h"
Florian Hahnfc97b612018-03-15 21:34:43 +000022#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000023#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Dominators.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/LLVMContext.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000031#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
Florian Hahnfc97b612018-03-15 21:34:43 +000033#include "llvm/IR/PatternMatch.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000034#include "llvm/Support/Casting.h"
35#include "llvm/Support/CommandLine.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000036#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Cloning.h"
Eli Friedman0a217452017-01-18 23:26:37 +000040#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000041#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/UnrollLoop.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000043#include "llvm/Transforms/Utils/ValueMapper.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000044#include <algorithm>
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000045#include <cassert>
46#include <cstdint>
47#include <limits>
Michael Kupersteinb151a642016-11-30 21:13:57 +000048
49using namespace llvm;
Florian Hahnfc97b612018-03-15 21:34:43 +000050using namespace llvm::PatternMatch;
Michael Kupersteinb151a642016-11-30 21:13:57 +000051
52#define DEBUG_TYPE "loop-unroll"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000053
Michael Kupersteinb151a642016-11-30 21:13:57 +000054STATISTIC(NumPeeled, "Number of loops peeled");
55
56static cl::opt<unsigned> UnrollPeelMaxCount(
57 "unroll-peel-max-count", cl::init(7), cl::Hidden,
58 cl::desc("Max average trip count which will cause loop peeling."));
59
60static cl::opt<unsigned> UnrollForcePeelCount(
61 "unroll-force-peel-count", cl::init(0), cl::Hidden,
62 cl::desc("Force a peel count regardless of profiling information."));
63
Serguei Katkov3ed93b42019-07-15 08:26:45 +000064static cl::opt<bool> UnrollPeelMultiDeoptExit(
65 "unroll-peel-multi-deopt-exit", cl::init(false), cl::Hidden,
66 cl::desc("Allow peeling of loops with multiple deopt exits."));
67
Max Kazantsev751579c2017-04-17 09:52:02 +000068// Designates that a Phi is estimated to become invariant after an "infinite"
69// number of loop iterations (i.e. only may become an invariant if the loop is
70// fully unrolled).
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000071static const unsigned InfiniteIterationsToInvariance =
72 std::numeric_limits<unsigned>::max();
Max Kazantsev751579c2017-04-17 09:52:02 +000073
Michael Kupersteinb151a642016-11-30 21:13:57 +000074// Check whether we are capable of peeling this loop.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +000075bool llvm::canPeel(Loop *L) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000076 // Make sure the loop is in simplified form
77 if (!L->isLoopSimplifyForm())
78 return false;
79
Serguei Katkov3ed93b42019-07-15 08:26:45 +000080 if (UnrollPeelMultiDeoptExit) {
81 SmallVector<BasicBlock *, 4> Exits;
82 L->getUniqueNonLatchExitBlocks(Exits);
83
84 if (!Exits.empty()) {
85 // Latch's terminator is a conditional branch, Latch is exiting and
86 // all non Latch exits ends up with deoptimize.
87 const BasicBlock *Latch = L->getLoopLatch();
88 const BranchInst *T = dyn_cast<BranchInst>(Latch->getTerminator());
89 return T && T->isConditional() && L->isLoopExiting(Latch) &&
90 all_of(Exits, [](const BasicBlock *BB) {
91 return BB->getTerminatingDeoptimizeCall();
92 });
93 }
94 }
95
Michael Kupersteinb151a642016-11-30 21:13:57 +000096 // Only peel loops that contain a single exit
97 if (!L->getExitingBlock() || !L->getUniqueExitBlock())
98 return false;
99
Michael Kuperstein2da2bfa2017-03-16 21:07:48 +0000100 // Don't try to peel loops where the latch is not the exiting block.
101 // This can be an indication of two different things:
102 // 1) The loop is not rotated.
103 // 2) The loop contains irreducible control flow that involves the latch.
104 if (L->getLoopLatch() != L->getExitingBlock())
105 return false;
106
Michael Kupersteinb151a642016-11-30 21:13:57 +0000107 return true;
108}
109
Max Kazantsev751579c2017-04-17 09:52:02 +0000110// This function calculates the number of iterations after which the given Phi
111// becomes an invariant. The pre-calculated values are memorized in the map. The
112// function (shortcut is I) is calculated according to the following definition:
113// Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge].
114// If %y is a loop invariant, then I(%x) = 1.
115// If %y is a Phi from the loop header, I(%x) = I(%y) + 1.
116// Otherwise, I(%x) is infinite.
117// TODO: Actually if %y is an expression that depends only on Phi %z and some
118// loop invariants, we can estimate I(%x) = I(%z) + 1. The example
119// looks like:
120// %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration.
121// %y = phi(0, 5),
122// %a = %y + 1.
123static unsigned calculateIterationsToInvariance(
124 PHINode *Phi, Loop *L, BasicBlock *BackEdge,
125 SmallDenseMap<PHINode *, unsigned> &IterationsToInvariance) {
126 assert(Phi->getParent() == L->getHeader() &&
127 "Non-loop Phi should not be checked for turning into invariant.");
128 assert(BackEdge == L->getLoopLatch() && "Wrong latch?");
129 // If we already know the answer, take it from the map.
130 auto I = IterationsToInvariance.find(Phi);
131 if (I != IterationsToInvariance.end())
132 return I->second;
133
134 // Otherwise we need to analyze the input from the back edge.
135 Value *Input = Phi->getIncomingValueForBlock(BackEdge);
136 // Place infinity to map to avoid infinite recursion for cycled Phis. Such
137 // cycles can never stop on an invariant.
138 IterationsToInvariance[Phi] = InfiniteIterationsToInvariance;
139 unsigned ToInvariance = InfiniteIterationsToInvariance;
140
141 if (L->isLoopInvariant(Input))
142 ToInvariance = 1u;
143 else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) {
144 // Only consider Phis in header block.
145 if (IncPhi->getParent() != L->getHeader())
146 return InfiniteIterationsToInvariance;
147 // If the input becomes an invariant after X iterations, then our Phi
148 // becomes an invariant after X + 1 iterations.
149 unsigned InputToInvariance = calculateIterationsToInvariance(
150 IncPhi, L, BackEdge, IterationsToInvariance);
151 if (InputToInvariance != InfiniteIterationsToInvariance)
152 ToInvariance = InputToInvariance + 1u;
153 }
154
155 // If we found that this Phi lies in an invariant chain, update the map.
156 if (ToInvariance != InfiniteIterationsToInvariance)
157 IterationsToInvariance[Phi] = ToInvariance;
158 return ToInvariance;
159}
160
Florian Hahnfc97b612018-03-15 21:34:43 +0000161// Return the number of iterations to peel off that make conditions in the
162// body true/false. For example, if we peel 2 iterations off the loop below,
163// the condition i < 2 can be evaluated at compile time.
164// for (i = 0; i < n; i++)
165// if (i < 2)
166// ..
167// else
168// ..
169// }
170static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
171 ScalarEvolution &SE) {
172 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form");
173 unsigned DesiredPeelCount = 0;
174
175 for (auto *BB : L.blocks()) {
176 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
177 if (!BI || BI->isUnconditional())
178 continue;
179
180 // Ignore loop exit condition.
181 if (L.getLoopLatch() == BB)
182 continue;
183
184 Value *Condition = BI->getCondition();
185 Value *LeftVal, *RightVal;
186 CmpInst::Predicate Pred;
187 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
188 continue;
189
190 const SCEV *LeftSCEV = SE.getSCEV(LeftVal);
191 const SCEV *RightSCEV = SE.getSCEV(RightVal);
192
193 // Do not consider predicates that are known to be true or false
194 // independently of the loop iteration.
195 if (SE.isKnownPredicate(Pred, LeftSCEV, RightSCEV) ||
196 SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), LeftSCEV,
197 RightSCEV))
198 continue;
199
200 // Check if we have a condition with one AddRec and one non AddRec
201 // expression. Normalize LeftSCEV to be the AddRec.
202 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
203 if (isa<SCEVAddRecExpr>(RightSCEV)) {
204 std::swap(LeftSCEV, RightSCEV);
205 Pred = ICmpInst::getSwappedPredicate(Pred);
206 } else
207 continue;
208 }
209
210 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV);
211
Florian Hahnac277582018-04-18 12:29:24 +0000212 // Avoid huge SCEV computations in the loop below, make sure we only
213 // consider AddRecs of the loop we are trying to peel and avoid
214 // non-monotonic predicates, as we will not be able to simplify the loop
215 // body.
216 // FIXME: For the non-monotonic predicates ICMP_EQ and ICMP_NE we can
217 // simplify the loop, if we peel 1 additional iteration, if there
218 // is no wrapping.
219 bool Increasing;
220 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L ||
221 !SE.isMonotonicPredicate(LeftAR, Pred, Increasing))
Florian Hahnfc97b612018-03-15 21:34:43 +0000222 continue;
Florian Hahnac277582018-04-18 12:29:24 +0000223 (void)Increasing;
Florian Hahnfc97b612018-03-15 21:34:43 +0000224
Florian Hahnac277582018-04-18 12:29:24 +0000225 // Check if extending the current DesiredPeelCount lets us evaluate Pred
226 // or !Pred in the loop body statically.
227 unsigned NewPeelCount = DesiredPeelCount;
228
Florian Hahnfc97b612018-03-15 21:34:43 +0000229 const SCEV *IterVal = LeftAR->evaluateAtIteration(
Florian Hahnac277582018-04-18 12:29:24 +0000230 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE);
Florian Hahnfc97b612018-03-15 21:34:43 +0000231
232 // If the original condition is not known, get the negated predicate
233 // (which holds on the else branch) and check if it is known. This allows
234 // us to peel of iterations that make the original condition false.
235 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV))
236 Pred = ICmpInst::getInversePredicate(Pred);
237
238 const SCEV *Step = LeftAR->getStepRecurrence(SE);
Florian Hahnac277582018-04-18 12:29:24 +0000239 while (NewPeelCount < MaxPeelCount &&
Florian Hahnfc97b612018-03-15 21:34:43 +0000240 SE.isKnownPredicate(Pred, IterVal, RightSCEV)) {
241 IterVal = SE.getAddExpr(IterVal, Step);
Florian Hahnac277582018-04-18 12:29:24 +0000242 NewPeelCount++;
Florian Hahnfc97b612018-03-15 21:34:43 +0000243 }
Florian Hahnac277582018-04-18 12:29:24 +0000244
245 // Only peel the loop if the monotonic predicate !Pred becomes known in the
246 // first iteration of the loop body after peeling.
247 if (NewPeelCount > DesiredPeelCount &&
248 SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal,
249 RightSCEV))
250 DesiredPeelCount = NewPeelCount;
Florian Hahnfc97b612018-03-15 21:34:43 +0000251 }
252
253 return DesiredPeelCount;
254}
255
Michael Kupersteinb151a642016-11-30 21:13:57 +0000256// Return the number of iterations we want to peel off.
257void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +0000258 TargetTransformInfo::UnrollingPreferences &UP,
Florian Hahnfc97b612018-03-15 21:34:43 +0000259 unsigned &TripCount, ScalarEvolution &SE) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000260 assert(LoopSize > 0 && "Zero loop size is not allowed!");
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000261 // Save the UP.PeelCount value set by the target in
262 // TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
263 unsigned TargetPeelCount = UP.PeelCount;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000264 UP.PeelCount = 0;
265 if (!canPeel(L))
266 return;
267
268 // Only try to peel innermost loops.
269 if (!L->empty())
270 return;
271
Chad Rosier45735b82018-04-06 13:57:21 +0000272 // If the user provided a peel count, use that.
273 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
274 if (UserPeelCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000275 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
276 << " iterations.\n");
Chad Rosier45735b82018-04-06 13:57:21 +0000277 UP.PeelCount = UnrollForcePeelCount;
278 return;
279 }
280
281 // Skip peeling if it's disabled.
282 if (!UP.AllowPeeling)
283 return;
284
Max Kazantsev751579c2017-04-17 09:52:02 +0000285 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N
286 // iterations of the loop. For this we compute the number for iterations after
287 // which every Phi is guaranteed to become an invariant, and try to peel the
288 // maximum number of iterations among these values, thus turning all those
289 // Phis into invariants.
Max Kazantsev8ed6b662017-04-17 05:38:28 +0000290 // First, check that we can peel at least one iteration.
291 if (2 * LoopSize <= UP.Threshold && UnrollPeelMaxCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000292 // Store the pre-calculated values here.
293 SmallDenseMap<PHINode *, unsigned> IterationsToInvariance;
294 // Now go through all Phis to calculate their the number of iterations they
295 // need to become invariants.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000296 // Start the max computation with the UP.PeelCount value set by the target
297 // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
298 unsigned DesiredPeelCount = TargetPeelCount;
Sanjoy Das30c35382017-03-07 06:03:15 +0000299 BasicBlock *BackEdge = L->getLoopLatch();
300 assert(BackEdge && "Loop is not in simplified form?");
Max Kazantsev751579c2017-04-17 09:52:02 +0000301 for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) {
302 PHINode *Phi = cast<PHINode>(&*BI);
303 unsigned ToInvariance = calculateIterationsToInvariance(
304 Phi, L, BackEdge, IterationsToInvariance);
305 if (ToInvariance != InfiniteIterationsToInvariance)
306 DesiredPeelCount = std::max(DesiredPeelCount, ToInvariance);
Sanjoy Das664c9252017-03-03 18:19:15 +0000307 }
Florian Hahnfc97b612018-03-15 21:34:43 +0000308
309 // Pay respect to limitations implied by loop size and the max peel count.
310 unsigned MaxPeelCount = UnrollPeelMaxCount;
311 MaxPeelCount = std::min(MaxPeelCount, UP.Threshold / LoopSize - 1);
312
313 DesiredPeelCount = std::max(DesiredPeelCount,
314 countToEliminateCompares(*L, MaxPeelCount, SE));
315
Max Kazantsev751579c2017-04-17 09:52:02 +0000316 if (DesiredPeelCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000317 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
318 // Consider max peel count limitation.
319 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000320 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount
321 << " iteration(s) to turn"
322 << " some Phis into invariants.\n");
Max Kazantsev751579c2017-04-17 09:52:02 +0000323 UP.PeelCount = DesiredPeelCount;
Sanjoy Das664c9252017-03-03 18:19:15 +0000324 return;
325 }
326 }
327
Sanjoy Daseed71b92017-03-03 18:19:10 +0000328 // Bail if we know the statically calculated trip count.
329 // In this case we rather prefer partial unrolling.
330 if (TripCount)
331 return;
332
Michael Kupersteinb151a642016-11-30 21:13:57 +0000333 // If we don't know the trip count, but have reason to believe the average
334 // trip count is low, peeling should be beneficial, since we will usually
335 // hit the peeled section.
336 // We only do this in the presence of profile information, since otherwise
337 // our estimates of the trip count are not reliable enough.
Chad Rosier45735b82018-04-06 13:57:21 +0000338 if (L->getHeader()->getParent()->hasProfileData()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000339 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
340 if (!PeelCount)
341 return;
342
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000343 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
344 << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000345
346 if (*PeelCount) {
347 if ((*PeelCount <= UnrollPeelMaxCount) &&
348 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000349 LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount
350 << " iterations.\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000351 UP.PeelCount = *PeelCount;
352 return;
353 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000354 LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
355 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
356 LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1)
357 << "\n");
358 LLVM_DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000359 }
360 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000361}
362
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000363/// Update the branch weights of the latch of a peeled-off loop
Michael Kupersteinb151a642016-11-30 21:13:57 +0000364/// iteration.
365/// This sets the branch weights for the latch of the recently peeled off loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000366/// iteration correctly.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000367/// Our goal is to make sure that:
368/// a) The total weight of all the copies of the loop body is preserved.
369/// b) The total weight of the loop exit is preserved.
370/// c) The body weight is reasonably distributed between the peeled iterations.
371///
372/// \param Header The copy of the header block that belongs to next iteration.
373/// \param LatchBR The copy of the latch branch that belongs to this iteration.
374/// \param IterNumber The serial number of the iteration that was just
375/// peeled off.
376/// \param AvgIters The average number of iterations we expect the loop to have.
377/// \param[in,out] PeeledHeaderWeight The total number of dynamic loop
378/// iterations that are unaccounted for. As an input, it represents the number
379/// of times we expect to enter the header of the iteration currently being
380/// peeled off. The output is the number of times we expect to enter the
381/// header of the next iteration.
382static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
383 unsigned IterNumber, unsigned AvgIters,
384 uint64_t &PeeledHeaderWeight) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000385 // FIXME: Pick a more realistic distribution.
386 // Currently the proportion of weight we assign to the fall-through
387 // side of the branch drops linearly with the iteration number, and we use
388 // a 0.9 fudge factor to make the drop-off less sharp...
389 if (PeeledHeaderWeight) {
390 uint64_t FallThruWeight =
391 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
392 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
393 PeeledHeaderWeight -= ExitWeight;
394
395 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
396 MDBuilder MDB(LatchBR->getContext());
397 MDNode *WeightNode =
398 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
399 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
400 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
401 }
402}
403
Serguei Katkovc22e7722019-07-03 05:59:23 +0000404/// Initialize the weights.
405///
406/// \param Header The header block.
407/// \param LatchBR The latch branch.
408/// \param AvgIters The average number of iterations we expect the loop to have.
Serguei Katkov6d8813a2019-07-04 05:10:14 +0000409/// \param[out] ExitWeight The # of times the edge from Latch to Exit is taken.
410/// \param[out] CurHeaderWeight The # of times the header is executed.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000411static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
412 unsigned AvgIters, uint64_t &ExitWeight,
413 uint64_t &CurHeaderWeight) {
414 uint64_t TrueWeight, FalseWeight;
415 if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight))
416 return;
417 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
418 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
419 // The # of times the loop body executes is the sum of the exit block
Serguei Katkov6d8813a2019-07-04 05:10:14 +0000420 // is taken and the # of times the backedges are taken.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000421 CurHeaderWeight = TrueWeight + FalseWeight;
422}
423
424/// Update the weights of original Latch block after peeling off all iterations.
425///
426/// \param Header The header block.
427/// \param LatchBR The latch branch.
428/// \param ExitWeight The weight of the edge from Latch to Exit block.
429/// \param CurHeaderWeight The # of time the header is executed.
430static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
431 uint64_t ExitWeight, uint64_t CurHeaderWeight) {
432 // Adjust the branch weights on the loop exit.
433 if (ExitWeight) {
434 // The backedge count is the difference of current header weight and
435 // current loop exit weight. If the current header weight is smaller than
436 // the current loop exit weight, we mark the loop backedge weight as 1.
437 uint64_t BackEdgeWeight = 0;
438 if (ExitWeight < CurHeaderWeight)
439 BackEdgeWeight = CurHeaderWeight - ExitWeight;
440 else
441 BackEdgeWeight = 1;
442 MDBuilder MDB(LatchBR->getContext());
443 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
444 MDNode *WeightNode =
445 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
446 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
447 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
448 }
449}
450
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000451/// Clones the body of the loop L, putting it between \p InsertTop and \p
Michael Kupersteinb151a642016-11-30 21:13:57 +0000452/// InsertBot.
453/// \param IterNumber The serial number of the iteration currently being
454/// peeled off.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000455/// \param ExitEdges The exit edges of the original loop.
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000456/// \param[out] NewBlocks A list of the blocks in the newly created clone
Michael Kupersteinb151a642016-11-30 21:13:57 +0000457/// \param[out] VMap The value map between the loop and the new clone.
458/// \param LoopBlocks A helper for DFS-traversal of the loop.
459/// \param LVMap A value-map that maps instructions from the original loop to
460/// instructions in the last peeled-off iteration.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000461static void cloneLoopBlocks(
462 Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot,
463 SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *> > &ExitEdges,
464 SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
465 ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT,
466 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000467 BasicBlock *Header = L->getHeader();
468 BasicBlock *Latch = L->getLoopLatch();
469 BasicBlock *PreHeader = L->getLoopPreheader();
470
471 Function *F = Header->getParent();
472 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
473 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
474 Loop *ParentLoop = L->getParentLoop();
475
476 // For each block in the original loop, create a new copy,
477 // and update the value map with the newly created values.
478 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
479 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
480 NewBlocks.push_back(NewBB);
481
482 if (ParentLoop)
483 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
484
485 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000486
487 // If dominator tree is available, insert nodes to represent cloned blocks.
488 if (DT) {
489 if (Header == *BB)
490 DT->addNewBlock(NewBB, InsertTop);
491 else {
492 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
493 // VMap must contain entry for IDom, as the iteration order is RPO.
494 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
495 }
496 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000497 }
498
499 // Hook-up the control flow for the newly inserted blocks.
500 // The new header is hooked up directly to the "top", which is either
501 // the original loop preheader (for the first iteration) or the previous
502 // iteration's exiting block (for every other iteration)
503 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
504
505 // Similarly, for the latch:
506 // The original exiting edge is still hooked up to the loop exit.
507 // The backedge now goes to the "bottom", which is either the loop's real
508 // header (for the last peeled iteration) or the copied header of the next
509 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000510 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
511 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000512 for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx)
513 if (LatchBR->getSuccessor(idx) == Header) {
514 LatchBR->setSuccessor(idx, InsertBot);
515 break;
516 }
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000517 if (DT)
518 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000519
520 // The new copy of the loop body starts with a bunch of PHI nodes
521 // that pick an incoming value from either the preheader, or the previous
522 // loop iteration. Since this copy is no longer part of the loop, we
523 // resolve this statically:
524 // For the first iteration, we use the value from the preheader directly.
525 // For any other iteration, we replace the phi with the value generated by
526 // the immediately preceding clone of the loop body (which represents
527 // the previous iteration).
528 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
529 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
530 if (IterNumber == 0) {
531 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
532 } else {
533 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
534 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
535 if (LatchInst && L->contains(LatchInst))
536 VMap[&*I] = LVMap[LatchInst];
537 else
538 VMap[&*I] = LatchVal;
539 }
540 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
541 }
542
543 // Fix up the outgoing values - we need to add a value for the iteration
544 // we've just created. Note that this must happen *after* the incoming
545 // values are adjusted, since the value going out of the latch may also be
546 // a value coming into the header.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000547 for (auto Edge : ExitEdges)
548 for (PHINode &PHI : Edge.second->phis()) {
549 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first);
550 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
551 if (LatchInst && L->contains(LatchInst))
552 LatchVal = VMap[LatchVal];
553 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first]));
554 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000555
556 // LastValueMap is updated with the values for the current loop
557 // which are used the next time this function is called.
558 for (const auto &KV : VMap)
559 LVMap[KV.first] = KV.second;
560}
561
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000562/// Peel off the first \p PeelCount iterations of loop \p L.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000563///
564/// Note that this does not peel them off as a single straight-line block.
565/// Rather, each iteration is peeled off separately, and needs to check the
566/// exit condition.
567/// For loops that dynamically execute \p PeelCount iterations or less
568/// this provides a benefit, since the peeled off iterations, which account
569/// for the bulk of dynamic execution, can be further simplified by scalar
570/// optimizations.
571bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
572 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000573 AssumptionCache *AC, bool PreserveLCSSA) {
Max Kazantsevb1ad66f2018-03-27 09:40:51 +0000574 assert(PeelCount > 0 && "Attempt to peel out zero iterations?");
575 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000576
577 LoopBlocksDFS LoopBlocks(L);
578 LoopBlocks.perform(LI);
579
580 BasicBlock *Header = L->getHeader();
581 BasicBlock *PreHeader = L->getLoopPreheader();
582 BasicBlock *Latch = L->getLoopLatch();
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000583 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges;
584 L->getExitEdges(ExitEdges);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000585
Serguei Katkovd021ad92019-07-15 09:13:11 +0000586 DenseMap<BasicBlock *, BasicBlock *> ExitIDom;
587 if (DT) {
588 assert(L->hasDedicatedExits() && "No dedicated exits?");
589 for (auto Edge : ExitEdges) {
590 if (ExitIDom.count(Edge.second))
591 continue;
592 BasicBlock *BB = DT->getNode(Edge.second)->getIDom()->getBlock();
593 assert(L->contains(BB) && "IDom is not in a loop");
594 ExitIDom[Edge.second] = BB;
595 }
596 }
597
Michael Kupersteinb151a642016-11-30 21:13:57 +0000598 Function *F = Header->getParent();
599
600 // Set up all the necessary basic blocks. It is convenient to split the
601 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
602 // body, and a new preheader for the "real" loop.
603
604 // Peeling the first iteration transforms.
605 //
606 // PreHeader:
607 // ...
608 // Header:
609 // LoopBody
610 // If (cond) goto Header
611 // Exit:
612 //
613 // into
614 //
615 // InsertTop:
616 // LoopBody
617 // If (!cond) goto Exit
618 // InsertBot:
619 // NewPreHeader:
620 // ...
621 // Header:
622 // LoopBody
623 // If (cond) goto Header
624 // Exit:
625 //
626 // Each following iteration will split the current bottom anchor in two,
627 // and put the new copy of the loop body between these two blocks. That is,
Fangrui Songf78650a2018-07-30 19:41:25 +0000628 // after peeling another iteration from the example above, we'll split
Michael Kupersteinb151a642016-11-30 21:13:57 +0000629 // InsertBot, and get:
630 //
631 // InsertTop:
632 // LoopBody
633 // If (!cond) goto Exit
634 // InsertBot:
635 // LoopBody
636 // If (!cond) goto Exit
637 // InsertBot.next:
638 // NewPreHeader:
639 // ...
640 // Header:
641 // LoopBody
642 // If (cond) goto Header
643 // Exit:
644
645 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
646 BasicBlock *InsertBot =
647 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
648 BasicBlock *NewPreHeader =
649 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
650
651 InsertTop->setName(Header->getName() + ".peel.begin");
652 InsertBot->setName(Header->getName() + ".peel.next");
653 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
654
655 ValueToValueMapTy LVMap;
656
657 // If we have branch weight information, we'll want to update it for the
658 // newly created branches.
659 BranchInst *LatchBR =
660 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
Xin Tong29402312017-01-02 20:27:23 +0000661 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
Serguei Katkovc22e7722019-07-03 05:59:23 +0000662 initBranchWeights(Header, LatchBR, PeelCount, ExitWeight, CurHeaderWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000663
664 // For each peeled-off iteration, make a copy of the loop.
665 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
666 SmallVector<BasicBlock *, 8> NewBlocks;
667 ValueToValueMapTy VMap;
668
Xin Tong29402312017-01-02 20:27:23 +0000669 // Subtract the exit weight from the current header weight -- the exit
670 // weight is exactly the weight of the previous iteration's header.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000671 // FIXME: due to the way the distribution is constructed, we need a
672 // guard here to make sure we don't end up with non-positive weights.
Xin Tong29402312017-01-02 20:27:23 +0000673 if (ExitWeight < CurHeaderWeight)
674 CurHeaderWeight -= ExitWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000675 else
Xin Tong29402312017-01-02 20:27:23 +0000676 CurHeaderWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000677
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000678 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks,
679 LoopBlocks, VMap, LVMap, DT, LI);
Serge Pavlovb71bb802017-03-26 16:46:53 +0000680
681 // Remap to use values from the current iteration instead of the
682 // previous one.
683 remapInstructionsInBlocks(NewBlocks, VMap);
684
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000685 if (DT) {
686 // Latches of the cloned loops dominate over the loop exit, so idom of the
687 // latter is the first cloned loop body, as original PreHeader dominates
688 // the original loop body.
689 if (Iter == 0)
Serguei Katkovd021ad92019-07-15 09:13:11 +0000690 for (auto Exit : ExitIDom)
691 DT->changeImmediateDominator(Exit.first,
692 cast<BasicBlock>(LVMap[Exit.second]));
Eli Friedman3af2f532018-12-21 01:28:49 +0000693#ifdef EXPENSIVE_CHECKS
David Green7c35de12018-02-28 11:00:08 +0000694 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
Eli Friedman3af2f532018-12-21 01:28:49 +0000695#endif
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000696 }
697
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000698 auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]);
699 updateBranchWeights(InsertBot, LatchBRCopy, Iter,
Michael Kupersteinb151a642016-11-30 21:13:57 +0000700 PeelCount, ExitWeight);
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000701 // Remove Loop metadata from the latch branch instruction
702 // because it is not the Loop's latch branch anymore.
703 LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000704
705 InsertTop = InsertBot;
706 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
707 InsertBot->setName(Header->getName() + ".peel.next");
708
709 F->getBasicBlockList().splice(InsertTop->getIterator(),
710 F->getBasicBlockList(),
711 NewBlocks[0]->getIterator(), F->end());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000712 }
713
714 // Now adjust the phi nodes in the loop header to get their initial values
715 // from the last peeled-off iteration instead of the preheader.
716 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
717 PHINode *PHI = cast<PHINode>(I);
718 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
719 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
720 if (LatchInst && L->contains(LatchInst))
721 NewVal = LVMap[LatchInst];
722
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000723 PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000724 }
725
Serguei Katkovc22e7722019-07-03 05:59:23 +0000726 fixupBranchWeights(Header, LatchBR, ExitWeight, CurHeaderWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000727
Florian Hahn6ab83b72019-02-14 13:59:39 +0000728 if (Loop *ParentLoop = L->getParentLoop())
729 L = ParentLoop;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000730
Florian Hahn6ab83b72019-02-14 13:59:39 +0000731 // We modified the loop, update SE.
732 SE->forgetTopmostLoop(L);
733
Serguei Katkovd021ad92019-07-15 09:13:11 +0000734 // Finally DomtTree must be correct.
735 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
736
Florian Hahn6ab83b72019-02-14 13:59:39 +0000737 // FIXME: Incrementally update loop-simplify
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000738 simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA);
Eli Friedman0a217452017-01-18 23:26:37 +0000739
Michael Kupersteinb151a642016-11-30 21:13:57 +0000740 NumPeeled++;
741
742 return true;
743}