LLVM 20.0.0git
LoopPeel.cpp
Go to the documentation of this file.
1//===- LoopPeel.cpp -------------------------------------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// Loop Peeling Utilities.
10//===----------------------------------------------------------------------===//
11
13#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/Loads.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/Instruction.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
34#include "llvm/Support/Debug.h"
41#include <algorithm>
42#include <cassert>
43#include <cstdint>
44#include <optional>
45
46using namespace llvm;
47using namespace llvm::PatternMatch;
48
49#define DEBUG_TYPE "loop-peel"
50
51STATISTIC(NumPeeled, "Number of loops peeled");
52
54 "unroll-peel-count", cl::Hidden,
55 cl::desc("Set the unroll peeling count, for testing purposes"));
56
57static cl::opt<bool>
58 UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden,
59 cl::desc("Allows loops to be peeled when the dynamic "
60 "trip count is known to be low."));
61
62static cl::opt<bool>
63 UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling",
64 cl::init(false), cl::Hidden,
65 cl::desc("Allows loop nests to be peeled."));
66
68 "unroll-peel-max-count", cl::init(7), cl::Hidden,
69 cl::desc("Max average trip count which will cause loop peeling."));
70
72 "unroll-force-peel-count", cl::init(0), cl::Hidden,
73 cl::desc("Force a peel count regardless of profiling information."));
74
76 "disable-advanced-peeling", cl::init(false), cl::Hidden,
78 "Disable advance peeling. Issues for convergent targets (D134803)."));
79
80static const char *PeeledCountMetaData = "llvm.loop.peeled.count";
81
82// Check whether we are capable of peeling this loop.
83bool llvm::canPeel(const Loop *L) {
84 // Make sure the loop is in simplified form
85 if (!L->isLoopSimplifyForm())
86 return false;
88 return true;
89
91 L->getUniqueNonLatchExitBlocks(Exits);
92 // The latch must either be the only exiting block or all non-latch exit
93 // blocks have either a deopt or unreachable terminator or compose a chain of
94 // blocks where the last one is either deopt or unreachable terminated. Both
95 // deopt and unreachable terminators are a strong indication they are not
96 // taken. Note that this is a profitability check, not a legality check. Also
97 // note that LoopPeeling currently can only update the branch weights of latch
98 // blocks and branch weights to blocks with deopt or unreachable do not need
99 // updating.
101}
102
103namespace {
104
105// As a loop is peeled, it may be the case that Phi nodes become
106// loop-invariant (ie, known because there is only one choice).
107// For example, consider the following function:
108// void g(int);
109// void binary() {
110// int x = 0;
111// int y = 0;
112// int a = 0;
113// for(int i = 0; i <100000; ++i) {
114// g(x);
115// x = y;
116// g(a);
117// y = a + 1;
118// a = 5;
119// }
120// }
121// Peeling 3 iterations is beneficial because the values for x, y and a
122// become known. The IR for this loop looks something like the following:
123//
124// %i = phi i32 [ 0, %entry ], [ %inc, %if.end ]
125// %a = phi i32 [ 0, %entry ], [ 5, %if.end ]
126// %y = phi i32 [ 0, %entry ], [ %add, %if.end ]
127// %x = phi i32 [ 0, %entry ], [ %y, %if.end ]
128// ...
129// tail call void @_Z1gi(i32 signext %x)
130// tail call void @_Z1gi(i32 signext %a)
131// %add = add nuw nsw i32 %a, 1
132// %inc = add nuw nsw i32 %i, 1
133// %exitcond = icmp eq i32 %inc, 100000
134// br i1 %exitcond, label %for.cond.cleanup, label %for.body
135//
136// The arguments for the calls to g will become known after 3 iterations
137// of the loop, because the phi nodes values become known after 3 iterations
138// of the loop (ie, they are known on the 4th iteration, so peel 3 iterations).
139// The first iteration has g(0), g(0); the second has g(0), g(5); the
140// third has g(1), g(5) and the fourth (and all subsequent) have g(6), g(5).
141// Now consider the phi nodes:
142// %a is a phi with constants so it is determined after iteration 1.
143// %y is a phi based on a constant and %a so it is determined on
144// the iteration after %a is determined, so iteration 2.
145// %x is a phi based on a constant and %y so it is determined on
146// the iteration after %y, so iteration 3.
147// %i is based on itself (and is an induction variable) so it is
148// never determined.
149// This means that peeling off 3 iterations will result in being able to
150// remove the phi nodes for %a, %y, and %x. The arguments for the
151// corresponding calls to g are determined and the code for computing
152// x, y, and a can be removed.
153//
154// The PhiAnalyzer class calculates how many times a loop should be
155// peeled based on the above analysis of the phi nodes in the loop while
156// respecting the maximum specified.
157class PhiAnalyzer {
158public:
159 PhiAnalyzer(const Loop &L, unsigned MaxIterations);
160
161 // Calculate the sufficient minimum number of iterations of the loop to peel
162 // such that phi instructions become determined (subject to allowable limits)
163 std::optional<unsigned> calculateIterationsToPeel();
164
165protected:
166 using PeelCounter = std::optional<unsigned>;
167 const PeelCounter Unknown = std::nullopt;
168
169 // Add 1 respecting Unknown and return Unknown if result over MaxIterations
170 PeelCounter addOne(PeelCounter PC) const {
171 if (PC == Unknown)
172 return Unknown;
173 return (*PC + 1 <= MaxIterations) ? PeelCounter{*PC + 1} : Unknown;
174 }
175
176 // Calculate the number of iterations after which the given value
177 // becomes an invariant.
178 PeelCounter calculate(const Value &);
179
180 const Loop &L;
181 const unsigned MaxIterations;
182
183 // Map of Values to number of iterations to invariance
184 SmallDenseMap<const Value *, PeelCounter> IterationsToInvariance;
185};
186
187PhiAnalyzer::PhiAnalyzer(const Loop &L, unsigned MaxIterations)
188 : L(L), MaxIterations(MaxIterations) {
189 assert(canPeel(&L) && "loop is not suitable for peeling");
190 assert(MaxIterations > 0 && "no peeling is allowed?");
191}
192
193// This function calculates the number of iterations after which the value
194// becomes an invariant. The pre-calculated values are memorized in a map.
195// N.B. This number will be Unknown or <= MaxIterations.
196// The function is calculated according to the following definition:
197// Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge].
198// F(%x) = G(%y) + 1 (N.B. [MaxIterations | Unknown] + 1 => Unknown)
199// G(%y) = 0 if %y is a loop invariant
200// G(%y) = G(%BackEdgeValue) if %y is a phi in the header block
201// G(%y) = TODO: if %y is an expression based on phis and loop invariants
202// The example looks like:
203// %x = phi(0, %a) <-- becomes invariant starting from 3rd iteration.
204// %y = phi(0, 5)
205// %a = %y + 1
206// G(%y) = Unknown otherwise (including phi not in header block)
207PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(const Value &V) {
208 // If we already know the answer, take it from the map.
209 // Otherwise, place Unknown to map to avoid infinite recursion. Such
210 // cycles can never stop on an invariant.
211 auto [I, Inserted] = IterationsToInvariance.try_emplace(&V, Unknown);
212 if (!Inserted)
213 return I->second;
214
215 if (L.isLoopInvariant(&V))
216 // Loop invariant so known at start.
217 return (IterationsToInvariance[&V] = 0);
218 if (const PHINode *Phi = dyn_cast<PHINode>(&V)) {
219 if (Phi->getParent() != L.getHeader()) {
220 // Phi is not in header block so Unknown.
221 assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved");
222 return Unknown;
223 }
224 // We need to analyze the input from the back edge and add 1.
225 Value *Input = Phi->getIncomingValueForBlock(L.getLoopLatch());
226 PeelCounter Iterations = calculate(*Input);
227 assert(IterationsToInvariance[Input] == Iterations &&
228 "unexpected value saved");
229 return (IterationsToInvariance[Phi] = addOne(Iterations));
230 }
231 if (const Instruction *I = dyn_cast<Instruction>(&V)) {
232 if (isa<CmpInst>(I) || I->isBinaryOp()) {
233 // Binary instructions get the max of the operands.
234 PeelCounter LHS = calculate(*I->getOperand(0));
235 if (LHS == Unknown)
236 return Unknown;
237 PeelCounter RHS = calculate(*I->getOperand(1));
238 if (RHS == Unknown)
239 return Unknown;
240 return (IterationsToInvariance[I] = {std::max(*LHS, *RHS)});
241 }
242 if (I->isCast())
243 // Cast instructions get the value of the operand.
244 return (IterationsToInvariance[I] = calculate(*I->getOperand(0)));
245 }
246 // TODO: handle more expressions
247
248 // Everything else is Unknown.
249 assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved");
250 return Unknown;
251}
252
253std::optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() {
254 unsigned Iterations = 0;
255 for (auto &PHI : L.getHeader()->phis()) {
256 PeelCounter ToInvariance = calculate(PHI);
257 if (ToInvariance != Unknown) {
258 assert(*ToInvariance <= MaxIterations && "bad result in phi analysis");
259 Iterations = std::max(Iterations, *ToInvariance);
260 if (Iterations == MaxIterations)
261 break;
262 }
263 }
264 assert((Iterations <= MaxIterations) && "bad result in phi analysis");
265 return Iterations ? std::optional<unsigned>(Iterations) : std::nullopt;
266}
267
268} // unnamed namespace
269
270// Try to find any invariant memory reads that will become dereferenceable in
271// the remainder loop after peeling. The load must also be used (transitively)
272// by an exit condition. Returns the number of iterations to peel off (at the
273// moment either 0 or 1).
275 DominatorTree &DT,
276 AssumptionCache *AC) {
277 // Skip loops with a single exiting block, because there should be no benefit
278 // for the heuristic below.
279 if (L.getExitingBlock())
280 return 0;
281
282 // All non-latch exit blocks must have an UnreachableInst terminator.
283 // Otherwise the heuristic below may not be profitable.
285 L.getUniqueNonLatchExitBlocks(Exits);
286 if (any_of(Exits, [](const BasicBlock *BB) {
287 return !isa<UnreachableInst>(BB->getTerminator());
288 }))
289 return 0;
290
291 // Now look for invariant loads that dominate the latch and are not known to
292 // be dereferenceable. If there are such loads and no writes, they will become
293 // dereferenceable in the loop if the first iteration is peeled off. Also
294 // collect the set of instructions controlled by such loads. Only peel if an
295 // exit condition uses (transitively) such a load.
296 BasicBlock *Header = L.getHeader();
297 BasicBlock *Latch = L.getLoopLatch();
298 SmallPtrSet<Value *, 8> LoadUsers;
299 const DataLayout &DL = L.getHeader()->getDataLayout();
300 for (BasicBlock *BB : L.blocks()) {
301 for (Instruction &I : *BB) {
302 if (I.mayWriteToMemory())
303 return 0;
304
305 auto Iter = LoadUsers.find(&I);
306 if (Iter != LoadUsers.end()) {
307 for (Value *U : I.users())
308 LoadUsers.insert(U);
309 }
310 // Do not look for reads in the header; they can already be hoisted
311 // without peeling.
312 if (BB == Header)
313 continue;
314 if (auto *LI = dyn_cast<LoadInst>(&I)) {
315 Value *Ptr = LI->getPointerOperand();
316 if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) &&
317 !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, AC, &DT))
318 for (Value *U : I.users())
319 LoadUsers.insert(U);
320 }
321 }
322 }
323 SmallVector<BasicBlock *> ExitingBlocks;
324 L.getExitingBlocks(ExitingBlocks);
325 if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) {
326 return LoadUsers.contains(Exiting->getTerminator());
327 }))
328 return 1;
329 return 0;
330}
331
332// Return the number of iterations to peel off that make conditions in the
333// body true/false. For example, if we peel 2 iterations off the loop below,
334// the condition i < 2 can be evaluated at compile time.
335// for (i = 0; i < n; i++)
336// if (i < 2)
337// ..
338// else
339// ..
340// }
341static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
342 ScalarEvolution &SE) {
343 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form");
344 unsigned DesiredPeelCount = 0;
345
346 // Do not peel the entire loop.
347 const SCEV *BE = SE.getConstantMaxBackedgeTakenCount(&L);
348 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(BE))
349 MaxPeelCount =
350 std::min((unsigned)SC->getAPInt().getLimitedValue() - 1, MaxPeelCount);
351
352 // Increase PeelCount while (IterVal Pred BoundSCEV) condition is satisfied;
353 // return true if inversed condition become known before reaching the
354 // MaxPeelCount limit.
355 auto PeelWhilePredicateIsKnown =
356 [&](unsigned &PeelCount, const SCEV *&IterVal, const SCEV *BoundSCEV,
357 const SCEV *Step, ICmpInst::Predicate Pred) {
358 while (PeelCount < MaxPeelCount &&
359 SE.isKnownPredicate(Pred, IterVal, BoundSCEV)) {
360 IterVal = SE.getAddExpr(IterVal, Step);
361 ++PeelCount;
362 }
363 return SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal,
364 BoundSCEV);
365 };
366
367 const unsigned MaxDepth = 4;
368 std::function<void(Value *, unsigned)> ComputePeelCount =
369 [&](Value *Condition, unsigned Depth) -> void {
370 if (!Condition->getType()->isIntegerTy() || Depth >= MaxDepth)
371 return;
372
373 Value *LeftVal, *RightVal;
374 if (match(Condition, m_And(m_Value(LeftVal), m_Value(RightVal))) ||
375 match(Condition, m_Or(m_Value(LeftVal), m_Value(RightVal)))) {
376 ComputePeelCount(LeftVal, Depth + 1);
377 ComputePeelCount(RightVal, Depth + 1);
378 return;
379 }
380
381 CmpPredicate Pred;
382 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
383 return;
384
385 const SCEV *LeftSCEV = SE.getSCEV(LeftVal);
386 const SCEV *RightSCEV = SE.getSCEV(RightVal);
387
388 // Do not consider predicates that are known to be true or false
389 // independently of the loop iteration.
390 if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV))
391 return;
392
393 // Check if we have a condition with one AddRec and one non AddRec
394 // expression. Normalize LeftSCEV to be the AddRec.
395 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
396 if (isa<SCEVAddRecExpr>(RightSCEV)) {
397 std::swap(LeftSCEV, RightSCEV);
398 Pred = ICmpInst::getSwappedPredicate(Pred);
399 } else
400 return;
401 }
402
403 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV);
404
405 // Avoid huge SCEV computations in the loop below, make sure we only
406 // consider AddRecs of the loop we are trying to peel.
407 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L)
408 return;
409 if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) &&
410 !SE.getMonotonicPredicateType(LeftAR, Pred))
411 return;
412
413 // Check if extending the current DesiredPeelCount lets us evaluate Pred
414 // or !Pred in the loop body statically.
415 unsigned NewPeelCount = DesiredPeelCount;
416
417 const SCEV *IterVal = LeftAR->evaluateAtIteration(
418 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE);
419
420 // If the original condition is not known, get the negated predicate
421 // (which holds on the else branch) and check if it is known. This allows
422 // us to peel of iterations that make the original condition false.
423 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV))
424 Pred = ICmpInst::getInversePredicate(Pred);
425
426 const SCEV *Step = LeftAR->getStepRecurrence(SE);
427 if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, RightSCEV, Step,
428 Pred))
429 return;
430
431 // However, for equality comparisons, that isn't always sufficient to
432 // eliminate the comparsion in loop body, we may need to peel one more
433 // iteration. See if that makes !Pred become unknown again.
434 const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step);
435 if (ICmpInst::isEquality(Pred) &&
436 !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal,
437 RightSCEV) &&
438 !SE.isKnownPredicate(Pred, IterVal, RightSCEV) &&
439 SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) {
440 if (NewPeelCount >= MaxPeelCount)
441 return; // Need to peel one more iteration, but can't. Give up.
442 ++NewPeelCount; // Great!
443 }
444
445 DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount);
446 };
447
448 auto ComputePeelCountMinMax = [&](MinMaxIntrinsic *MinMax) {
449 if (!MinMax->getType()->isIntegerTy())
450 return;
451 Value *LHS = MinMax->getLHS(), *RHS = MinMax->getRHS();
452 const SCEV *BoundSCEV, *IterSCEV;
453 if (L.isLoopInvariant(LHS)) {
454 BoundSCEV = SE.getSCEV(LHS);
455 IterSCEV = SE.getSCEV(RHS);
456 } else if (L.isLoopInvariant(RHS)) {
457 BoundSCEV = SE.getSCEV(RHS);
458 IterSCEV = SE.getSCEV(LHS);
459 } else
460 return;
461 const auto *AddRec = dyn_cast<SCEVAddRecExpr>(IterSCEV);
462 // For simplicity, we support only affine recurrences.
463 if (!AddRec || !AddRec->isAffine() || AddRec->getLoop() != &L)
464 return;
465 const SCEV *Step = AddRec->getStepRecurrence(SE);
466 bool IsSigned = MinMax->isSigned();
467 // To minimize number of peeled iterations, we use strict relational
468 // predicates here.
470 if (SE.isKnownPositive(Step))
471 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
472 else if (SE.isKnownNegative(Step))
473 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
474 else
475 return;
476 // Check that AddRec is not wrapping.
477 if (!(IsSigned ? AddRec->hasNoSignedWrap() : AddRec->hasNoUnsignedWrap()))
478 return;
479 unsigned NewPeelCount = DesiredPeelCount;
480 const SCEV *IterVal = AddRec->evaluateAtIteration(
481 SE.getConstant(AddRec->getType(), NewPeelCount), SE);
482 if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, BoundSCEV, Step,
483 Pred))
484 return;
485 DesiredPeelCount = NewPeelCount;
486 };
487
488 for (BasicBlock *BB : L.blocks()) {
489 for (Instruction &I : *BB) {
490 if (SelectInst *SI = dyn_cast<SelectInst>(&I))
491 ComputePeelCount(SI->getCondition(), 0);
492 if (MinMaxIntrinsic *MinMax = dyn_cast<MinMaxIntrinsic>(&I))
493 ComputePeelCountMinMax(MinMax);
494 }
495
496 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
497 if (!BI || BI->isUnconditional())
498 continue;
499
500 // Ignore loop exit condition.
501 if (L.getLoopLatch() == BB)
502 continue;
503
504 ComputePeelCount(BI->getCondition(), 0);
505 }
506
507 return DesiredPeelCount;
508}
509
510/// This "heuristic" exactly matches implicit behavior which used to exist
511/// inside getLoopEstimatedTripCount. It was added here to keep an
512/// improvement inside that API from causing peeling to become more aggressive.
513/// This should probably be removed.
515 BasicBlock *Latch = L->getLoopLatch();
516 if (!Latch)
517 return true;
518
519 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
520 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
521 return true;
522
523 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
524 LatchBR->getSuccessor(1) == L->getHeader()) &&
525 "At least one edge out of the latch must go to the header");
526
528 L->getUniqueNonLatchExitBlocks(ExitBlocks);
529 return any_of(ExitBlocks, [](const BasicBlock *EB) {
530 return !EB->getTerminatingDeoptimizeCall();
531 });
532}
533
534
535// Return the number of iterations we want to peel off.
536void llvm::computePeelCount(Loop *L, unsigned LoopSize,
538 unsigned TripCount, DominatorTree &DT,
540 unsigned Threshold) {
541 assert(LoopSize > 0 && "Zero loop size is not allowed!");
542 // Save the PP.PeelCount value set by the target in
543 // TTI.getPeelingPreferences or by the flag -unroll-peel-count.
544 unsigned TargetPeelCount = PP.PeelCount;
545 PP.PeelCount = 0;
546 if (!canPeel(L))
547 return;
548
549 // Only try to peel innermost loops by default.
550 // The constraint can be relaxed by the target in TTI.getPeelingPreferences
551 // or by the flag -unroll-allow-loop-nests-peeling.
552 if (!PP.AllowLoopNestsPeeling && !L->isInnermost())
553 return;
554
555 // If the user provided a peel count, use that.
556 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
557 if (UserPeelCount) {
558 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
559 << " iterations.\n");
561 PP.PeelProfiledIterations = true;
562 return;
563 }
564
565 // Skip peeling if it's disabled.
566 if (!PP.AllowPeeling)
567 return;
568
569 // Check that we can peel at least one iteration.
570 if (2 * LoopSize > Threshold)
571 return;
572
573 unsigned AlreadyPeeled = 0;
575 AlreadyPeeled = *Peeled;
576 // Stop if we already peeled off the maximum number of iterations.
577 if (AlreadyPeeled >= UnrollPeelMaxCount)
578 return;
579
580 // Pay respect to limitations implied by loop size and the max peel count.
581 unsigned MaxPeelCount = UnrollPeelMaxCount;
582 MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1);
583
584 // Start the max computation with the PP.PeelCount value set by the target
585 // in TTI.getPeelingPreferences or by the flag -unroll-peel-count.
586 unsigned DesiredPeelCount = TargetPeelCount;
587
588 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N
589 // iterations of the loop. For this we compute the number for iterations after
590 // which every Phi is guaranteed to become an invariant, and try to peel the
591 // maximum number of iterations among these values, thus turning all those
592 // Phis into invariants.
593 if (MaxPeelCount > DesiredPeelCount) {
594 // Check how many iterations are useful for resolving Phis
595 auto NumPeels = PhiAnalyzer(*L, MaxPeelCount).calculateIterationsToPeel();
596 if (NumPeels)
597 DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels);
598 }
599
600 DesiredPeelCount = std::max(DesiredPeelCount,
601 countToEliminateCompares(*L, MaxPeelCount, SE));
602
603 if (DesiredPeelCount == 0)
604 DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT, AC);
605
606 if (DesiredPeelCount > 0) {
607 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
608 // Consider max peel count limitation.
609 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?");
610 if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) {
611 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount
612 << " iteration(s) to turn"
613 << " some Phis into invariants.\n");
614 PP.PeelCount = DesiredPeelCount;
615 PP.PeelProfiledIterations = false;
616 return;
617 }
618 }
619
620 // Bail if we know the statically calculated trip count.
621 // In this case we rather prefer partial unrolling.
622 if (TripCount)
623 return;
624
625 // Do not apply profile base peeling if it is disabled.
627 return;
628 // If we don't know the trip count, but have reason to believe the average
629 // trip count is low, peeling should be beneficial, since we will usually
630 // hit the peeled section.
631 // We only do this in the presence of profile information, since otherwise
632 // our estimates of the trip count are not reliable enough.
633 if (L->getHeader()->getParent()->hasProfileData()) {
635 return;
636 std::optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L);
637 if (!EstimatedTripCount)
638 return;
639
640 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is "
641 << *EstimatedTripCount << "\n");
642
643 if (*EstimatedTripCount) {
644 if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) {
645 unsigned PeelCount = *EstimatedTripCount;
646 LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n");
647 PP.PeelCount = PeelCount;
648 return;
649 }
650 LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n");
651 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
652 LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n");
653 LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n");
654 LLVM_DEBUG(dbgs() << "Max peel count by cost: "
655 << (Threshold / LoopSize - 1) << "\n");
656 }
657 }
658}
659
661 // Weights for current iteration.
663 // Weights to subtract after each iteration.
665};
666
667/// Update the branch weights of an exiting block of a peeled-off loop
668/// iteration.
669/// Let F is a weight of the edge to continue (fallthrough) into the loop.
670/// Let E is a weight of the edge to an exit.
671/// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to
672/// go to exit.
673/// Then, Estimated ExitCount = F / E.
674/// For I-th (counting from 0) peeled off iteration we set the weights for
675/// the peeled exit as (EC - I, 1). It gives us reasonable distribution,
676/// The probability to go to exit 1/(EC-I) increases. At the same time
677/// the estimated exit count in the remainder loop reduces by I.
678/// To avoid dealing with division rounding we can just multiple both part
679/// of weights to E and use weight as (F - I * E, E).
680static void updateBranchWeights(Instruction *Term, WeightInfo &Info) {
681 setBranchWeights(*Term, Info.Weights, /*IsExpected=*/false);
682 for (auto [Idx, SubWeight] : enumerate(Info.SubWeights))
683 if (SubWeight != 0)
684 // Don't set the probability of taking the edge from latch to loop header
685 // to less than 1:1 ratio (meaning Weight should not be lower than
686 // SubWeight), as this could significantly reduce the loop's hotness,
687 // which would be incorrect in the case of underestimating the trip count.
688 Info.Weights[Idx] =
689 Info.Weights[Idx] > SubWeight
690 ? std::max(Info.Weights[Idx] - SubWeight, SubWeight)
691 : SubWeight;
692}
693
694/// Initialize the weights for all exiting blocks.
696 Loop *L) {
697 SmallVector<BasicBlock *> ExitingBlocks;
698 L->getExitingBlocks(ExitingBlocks);
699 for (BasicBlock *ExitingBlock : ExitingBlocks) {
700 Instruction *Term = ExitingBlock->getTerminator();
701 SmallVector<uint32_t> Weights;
702 if (!extractBranchWeights(*Term, Weights))
703 continue;
704
705 // See the comment on updateBranchWeights() for an explanation of what we
706 // do here.
707 uint32_t FallThroughWeights = 0;
708 uint32_t ExitWeights = 0;
709 for (auto [Succ, Weight] : zip(successors(Term), Weights)) {
710 if (L->contains(Succ))
711 FallThroughWeights += Weight;
712 else
713 ExitWeights += Weight;
714 }
715
716 // Don't try to update weights for degenerate case.
717 if (FallThroughWeights == 0)
718 continue;
719
720 SmallVector<uint32_t> SubWeights;
721 for (auto [Succ, Weight] : zip(successors(Term), Weights)) {
722 if (!L->contains(Succ)) {
723 // Exit weights stay the same.
724 SubWeights.push_back(0);
725 continue;
726 }
727
728 // Subtract exit weights on each iteration, distributed across all
729 // fallthrough edges.
730 double W = (double)Weight / (double)FallThroughWeights;
731 SubWeights.push_back((uint32_t)(ExitWeights * W));
732 }
733
734 WeightInfos.insert({Term, {std::move(Weights), std::move(SubWeights)}});
735 }
736}
737
738/// Clones the body of the loop L, putting it between \p InsertTop and \p
739/// InsertBot.
740/// \param IterNumber The serial number of the iteration currently being
741/// peeled off.
742/// \param ExitEdges The exit edges of the original loop.
743/// \param[out] NewBlocks A list of the blocks in the newly created clone
744/// \param[out] VMap The value map between the loop and the new clone.
745/// \param LoopBlocks A helper for DFS-traversal of the loop.
746/// \param LVMap A value-map that maps instructions from the original loop to
747/// instructions in the last peeled-off iteration.
748static void cloneLoopBlocks(
749 Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot,
750 SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges,
751 SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
753 LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes,
754 ScalarEvolution &SE) {
755 BasicBlock *Header = L->getHeader();
756 BasicBlock *Latch = L->getLoopLatch();
757 BasicBlock *PreHeader = L->getLoopPreheader();
758
759 Function *F = Header->getParent();
760 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
761 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
762 Loop *ParentLoop = L->getParentLoop();
763
764 // For each block in the original loop, create a new copy,
765 // and update the value map with the newly created values.
766 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
767 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
768 NewBlocks.push_back(NewBB);
769
770 // If an original block is an immediate child of the loop L, its copy
771 // is a child of a ParentLoop after peeling. If a block is a child of
772 // a nested loop, it is handled in the cloneLoop() call below.
773 if (ParentLoop && LI->getLoopFor(*BB) == L)
774 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
775
776 VMap[*BB] = NewBB;
777
778 // If dominator tree is available, insert nodes to represent cloned blocks.
779 if (DT) {
780 if (Header == *BB)
781 DT->addNewBlock(NewBB, InsertTop);
782 else {
783 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
784 // VMap must contain entry for IDom, as the iteration order is RPO.
785 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
786 }
787 }
788 }
789
790 {
791 // Identify what other metadata depends on the cloned version. After
792 // cloning, replace the metadata with the corrected version for both
793 // memory instructions and noalias intrinsics.
794 std::string Ext = (Twine("Peel") + Twine(IterNumber)).str();
795 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
796 Header->getContext(), Ext);
797 }
798
799 // Recursively create the new Loop objects for nested loops, if any,
800 // to preserve LoopInfo.
801 for (Loop *ChildLoop : *L) {
802 cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr);
803 }
804
805 // Hook-up the control flow for the newly inserted blocks.
806 // The new header is hooked up directly to the "top", which is either
807 // the original loop preheader (for the first iteration) or the previous
808 // iteration's exiting block (for every other iteration)
809 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
810
811 // Similarly, for the latch:
812 // The original exiting edge is still hooked up to the loop exit.
813 // The backedge now goes to the "bottom", which is either the loop's real
814 // header (for the last peeled iteration) or the copied header of the next
815 // iteration (for every other iteration)
816 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
817 auto *LatchTerm = cast<Instruction>(NewLatch->getTerminator());
818 for (unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx)
819 if (LatchTerm->getSuccessor(idx) == Header) {
820 LatchTerm->setSuccessor(idx, InsertBot);
821 break;
822 }
823 if (DT)
824 DT->changeImmediateDominator(InsertBot, NewLatch);
825
826 // The new copy of the loop body starts with a bunch of PHI nodes
827 // that pick an incoming value from either the preheader, or the previous
828 // loop iteration. Since this copy is no longer part of the loop, we
829 // resolve this statically:
830 // For the first iteration, we use the value from the preheader directly.
831 // For any other iteration, we replace the phi with the value generated by
832 // the immediately preceding clone of the loop body (which represents
833 // the previous iteration).
834 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
835 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
836 if (IterNumber == 0) {
837 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
838 } else {
839 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
840 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
841 if (LatchInst && L->contains(LatchInst))
842 VMap[&*I] = LVMap[LatchInst];
843 else
844 VMap[&*I] = LatchVal;
845 }
846 NewPHI->eraseFromParent();
847 }
848
849 // Fix up the outgoing values - we need to add a value for the iteration
850 // we've just created. Note that this must happen *after* the incoming
851 // values are adjusted, since the value going out of the latch may also be
852 // a value coming into the header.
853 for (auto Edge : ExitEdges)
854 for (PHINode &PHI : Edge.second->phis()) {
855 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first);
856 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
857 if (LatchInst && L->contains(LatchInst))
858 LatchVal = VMap[LatchVal];
859 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first]));
861 }
862
863 // LastValueMap is updated with the values for the current loop
864 // which are used the next time this function is called.
865 for (auto KV : VMap)
866 LVMap[KV.first] = KV.second;
867}
868
872 std::optional<bool> UserAllowPeeling,
873 std::optional<bool> UserAllowProfileBasedPeeling,
874 bool UnrollingSpecficValues) {
876
877 // Set the default values.
878 PP.PeelCount = 0;
879 PP.AllowPeeling = true;
880 PP.AllowLoopNestsPeeling = false;
881 PP.PeelProfiledIterations = true;
882
883 // Get the target specifc values.
884 TTI.getPeelingPreferences(L, SE, PP);
885
886 // User specified values using cl::opt.
887 if (UnrollingSpecficValues) {
888 if (UnrollPeelCount.getNumOccurrences() > 0)
890 if (UnrollAllowPeeling.getNumOccurrences() > 0)
892 if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0)
894 }
895
896 // User specifed values provided by argument.
897 if (UserAllowPeeling)
898 PP.AllowPeeling = *UserAllowPeeling;
899 if (UserAllowProfileBasedPeeling)
900 PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling;
901
902 return PP;
903}
904
905/// Peel off the first \p PeelCount iterations of loop \p L.
906///
907/// Note that this does not peel them off as a single straight-line block.
908/// Rather, each iteration is peeled off separately, and needs to check the
909/// exit condition.
910/// For loops that dynamically execute \p PeelCount iterations or less
911/// this provides a benefit, since the peeled off iterations, which account
912/// for the bulk of dynamic execution, can be further simplified by scalar
913/// optimizations.
914bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
916 bool PreserveLCSSA, ValueToValueMapTy &LVMap) {
917 assert(PeelCount > 0 && "Attempt to peel out zero iterations?");
918 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?");
919
920 LoopBlocksDFS LoopBlocks(L);
921 LoopBlocks.perform(LI);
922
923 BasicBlock *Header = L->getHeader();
924 BasicBlock *PreHeader = L->getLoopPreheader();
925 BasicBlock *Latch = L->getLoopLatch();
927 L->getExitEdges(ExitEdges);
928
929 // Remember dominators of blocks we might reach through exits to change them
930 // later. Immediate dominator of such block might change, because we add more
931 // routes which can lead to the exit: we can reach it from the peeled
932 // iterations too.
933 DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom;
934 for (auto *BB : L->blocks()) {
935 auto *BBDomNode = DT.getNode(BB);
936 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
937 for (auto *ChildDomNode : BBDomNode->children()) {
938 auto *ChildBB = ChildDomNode->getBlock();
939 if (!L->contains(ChildBB))
940 ChildrenToUpdate.push_back(ChildBB);
941 }
942 // The new idom of the block will be the nearest common dominator
943 // of all copies of the previous idom. This is equivalent to the
944 // nearest common dominator of the previous idom and the first latch,
945 // which dominates all copies of the previous idom.
946 BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch);
947 for (auto *ChildBB : ChildrenToUpdate)
948 NonLoopBlocksIDom[ChildBB] = NewIDom;
949 }
950
951 Function *F = Header->getParent();
952
953 // Set up all the necessary basic blocks. It is convenient to split the
954 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
955 // body, and a new preheader for the "real" loop.
956
957 // Peeling the first iteration transforms.
958 //
959 // PreHeader:
960 // ...
961 // Header:
962 // LoopBody
963 // If (cond) goto Header
964 // Exit:
965 //
966 // into
967 //
968 // InsertTop:
969 // LoopBody
970 // If (!cond) goto Exit
971 // InsertBot:
972 // NewPreHeader:
973 // ...
974 // Header:
975 // LoopBody
976 // If (cond) goto Header
977 // Exit:
978 //
979 // Each following iteration will split the current bottom anchor in two,
980 // and put the new copy of the loop body between these two blocks. That is,
981 // after peeling another iteration from the example above, we'll split
982 // InsertBot, and get:
983 //
984 // InsertTop:
985 // LoopBody
986 // If (!cond) goto Exit
987 // InsertBot:
988 // LoopBody
989 // If (!cond) goto Exit
990 // InsertBot.next:
991 // NewPreHeader:
992 // ...
993 // Header:
994 // LoopBody
995 // If (cond) goto Header
996 // Exit:
997
998 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI);
999 BasicBlock *InsertBot =
1000 SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI);
1001 BasicBlock *NewPreHeader =
1002 SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI);
1003
1004 InsertTop->setName(Header->getName() + ".peel.begin");
1005 InsertBot->setName(Header->getName() + ".peel.next");
1006 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
1007
1008 Instruction *LatchTerm =
1009 cast<Instruction>(cast<BasicBlock>(Latch)->getTerminator());
1010
1011 // If we have branch weight information, we'll want to update it for the
1012 // newly created branches.
1014 initBranchWeights(Weights, L);
1015
1016 // Identify what noalias metadata is inside the loop: if it is inside the
1017 // loop, the associated metadata must be cloned for each iteration.
1018 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
1019 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
1020
1021 // For each peeled-off iteration, make a copy of the loop.
1022 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
1024 ValueToValueMapTy VMap;
1025
1026 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks,
1027 LoopBlocks, VMap, LVMap, &DT, LI,
1028 LoopLocalNoAliasDeclScopes, *SE);
1029
1030 // Remap to use values from the current iteration instead of the
1031 // previous one.
1032 remapInstructionsInBlocks(NewBlocks, VMap);
1033
1034 // Update IDoms of the blocks reachable through exits.
1035 if (Iter == 0)
1036 for (auto BBIDom : NonLoopBlocksIDom)
1037 DT.changeImmediateDominator(BBIDom.first,
1038 cast<BasicBlock>(LVMap[BBIDom.second]));
1039#ifdef EXPENSIVE_CHECKS
1040 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1041#endif
1042
1043 for (auto &[Term, Info] : Weights) {
1044 auto *TermCopy = cast<Instruction>(VMap[Term]);
1045 updateBranchWeights(TermCopy, Info);
1046 }
1047
1048 // Remove Loop metadata from the latch branch instruction
1049 // because it is not the Loop's latch branch anymore.
1050 auto *LatchTermCopy = cast<Instruction>(VMap[LatchTerm]);
1051 LatchTermCopy->setMetadata(LLVMContext::MD_loop, nullptr);
1052
1053 InsertTop = InsertBot;
1054 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI);
1055 InsertBot->setName(Header->getName() + ".peel.next");
1056
1057 F->splice(InsertTop->getIterator(), F, NewBlocks[0]->getIterator(),
1058 F->end());
1059 }
1060
1061 // Now adjust the phi nodes in the loop header to get their initial values
1062 // from the last peeled-off iteration instead of the preheader.
1063 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
1064 PHINode *PHI = cast<PHINode>(I);
1065 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
1066 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
1067 if (LatchInst && L->contains(LatchInst))
1068 NewVal = LVMap[LatchInst];
1069
1070 PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
1071 }
1072
1073 for (const auto &[Term, Info] : Weights) {
1074 setBranchWeights(*Term, Info.Weights, /*IsExpected=*/false);
1075 }
1076
1077 // Update Metadata for count of peeled off iterations.
1078 unsigned AlreadyPeeled = 0;
1080 AlreadyPeeled = *Peeled;
1081 addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount);
1082
1083 if (Loop *ParentLoop = L->getParentLoop())
1084 L = ParentLoop;
1085
1086 // We modified the loop, update SE.
1087 SE->forgetTopmostLoop(L);
1089
1090#ifdef EXPENSIVE_CHECKS
1091 // Finally DomtTree must be correct.
1092 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1093#endif
1094
1095 // FIXME: Incrementally update loop-simplify
1096 simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA);
1097
1098 NumPeeled++;
1099
1100 return true;
1101}
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseMap class.
static const unsigned MaxDepth
static void updateBranchWeights(Instruction *Term, WeightInfo &Info)
Update the branch weights of an exiting block of a peeled-off loop iteration.
Definition: LoopPeel.cpp:680
static cl::opt< bool > DisableAdvancedPeeling("disable-advanced-peeling", cl::init(false), cl::Hidden, cl::desc("Disable advance peeling. Issues for convergent targets (D134803)."))
static cl::opt< unsigned > UnrollPeelMaxCount("unroll-peel-max-count", cl::init(7), cl::Hidden, cl::desc("Max average trip count which will cause loop peeling."))
static cl::opt< bool > UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, cl::desc("Allows loops to be peeled when the dynamic " "trip count is known to be low."))
static cl::opt< unsigned > UnrollForcePeelCount("unroll-force-peel-count", cl::init(0), cl::Hidden, cl::desc("Force a peel count regardless of profiling information."))
static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, ScalarEvolution &SE)
Definition: LoopPeel.cpp:341
static bool violatesLegacyMultiExitLoopCheck(Loop *L)
This "heuristic" exactly matches implicit behavior which used to exist inside getLoopEstimatedTripCou...
Definition: LoopPeel.cpp:514
static const char * PeeledCountMetaData
Definition: LoopPeel.cpp:80
static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, SmallVectorImpl< std::pair< BasicBlock *, BasicBlock * > > &ExitEdges, SmallVectorImpl< BasicBlock * > &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, LoopInfo *LI, ArrayRef< MDNode * > LoopLocalNoAliasDeclScopes, ScalarEvolution &SE)
Clones the body of the loop L, putting it between InsertTop and InsertBot.
Definition: LoopPeel.cpp:748
static cl::opt< bool > UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", cl::init(false), cl::Hidden, cl::desc("Allows loop nests to be peeled."))
static cl::opt< unsigned > UnrollPeelCount("unroll-peel-count", cl::Hidden, cl::desc("Set the unroll peeling count, for testing purposes"))
static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, DominatorTree &DT, AssumptionCache *AC)
Definition: LoopPeel.cpp:274
static void initBranchWeights(DenseMap< Instruction *, WeightInfo > &WeightInfos, Loop *L)
Initialize the weights for all exiting blocks.
Definition: LoopPeel.cpp:695
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for profiling metadata utility functions.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:331
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
Conditional or Unconditional Branch instruction.
unsigned getNumSuccessors() const
BasicBlock * getSuccessor(unsigned i) const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Definition: CmpPredicate.h:22
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
Definition: Dominators.cpp:344
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
bool isEquality() const
Return true if this predicate is either EQ or NE.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Store the result of a depth first search within basic blocks contained by a single loop.
Definition: LoopIterator.h:97
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
Definition: LoopIterator.h:101
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1254
RPOIterator endRPO() const
Definition: LoopIterator.h:140
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
This class represents min/max intrinsics.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
This class represents a constant integer value.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
std::optional< bool > evaluatePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
void forgetTopmostLoop(const Loop *L)
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
This class represents the LLVM 'select' instruction.
iterator find(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:455
iterator end() const
Definition: SmallPtrSet.h:477
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:458
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP) const
Get target-customized preferences for the generic loop peeling transformation.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
self_iterator getIterator()
Definition: ilist_node.h:132
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:854
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:850
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1739
bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::PeelingPreferences &PP, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, AssumptionCache *AC=nullptr, unsigned Threshold=UINT_MAX)
Definition: LoopPeel.cpp:536
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition: STLExtras.h:2448
auto successors(const MachineBasicBlock *BB)
bool canPeel(const Loop *L)
Definition: LoopPeel.cpp:83
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Definition: LoopUtils.cpp:214
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
Definition: LoopPeel.cpp:870
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
Definition: LoopInfo.cpp:1101
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
Definition: Loads.cpp:235
bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
bool peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
Definition: LoopPeel.cpp:914
Loop * cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
Definition: LoopUtils.cpp:1831
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
SmallVector< uint32_t > Weights
Definition: LoopPeel.cpp:662
const SmallVector< uint32_t > SubWeights
Definition: LoopPeel.cpp:664
bool AllowPeeling
Allow peeling off loop iterations.
bool AllowLoopNestsPeeling
Allow peeling off loop iterations for loop nests.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...