18fb3d57eSArtur Pilipenko //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
28fb3d57eSArtur Pilipenko //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68fb3d57eSArtur Pilipenko //
78fb3d57eSArtur Pilipenko //===----------------------------------------------------------------------===//
88fb3d57eSArtur Pilipenko //
98fb3d57eSArtur Pilipenko // The LoopPredication pass tries to convert loop variant range checks to loop
108fb3d57eSArtur Pilipenko // invariant by widening checks across loop iterations. For example, it will
118fb3d57eSArtur Pilipenko // convert
128fb3d57eSArtur Pilipenko //
138fb3d57eSArtur Pilipenko // for (i = 0; i < n; i++) {
148fb3d57eSArtur Pilipenko // guard(i < len);
158fb3d57eSArtur Pilipenko // ...
168fb3d57eSArtur Pilipenko // }
178fb3d57eSArtur Pilipenko //
188fb3d57eSArtur Pilipenko // to
198fb3d57eSArtur Pilipenko //
208fb3d57eSArtur Pilipenko // for (i = 0; i < n; i++) {
218fb3d57eSArtur Pilipenko // guard(n - 1 < len);
228fb3d57eSArtur Pilipenko // ...
238fb3d57eSArtur Pilipenko // }
248fb3d57eSArtur Pilipenko //
258fb3d57eSArtur Pilipenko // After this transformation the condition of the guard is loop invariant, so
268fb3d57eSArtur Pilipenko // loop-unswitch can later unswitch the loop by this condition which basically
278fb3d57eSArtur Pilipenko // predicates the loop by the widened condition:
288fb3d57eSArtur Pilipenko //
298fb3d57eSArtur Pilipenko // if (n - 1 < len)
308fb3d57eSArtur Pilipenko // for (i = 0; i < n; i++) {
318fb3d57eSArtur Pilipenko // ...
328fb3d57eSArtur Pilipenko // }
338fb3d57eSArtur Pilipenko // else
348fb3d57eSArtur Pilipenko // deoptimize
358fb3d57eSArtur Pilipenko //
36889dc1e3SArtur Pilipenko // It's tempting to rely on SCEV here, but it has proven to be problematic.
37889dc1e3SArtur Pilipenko // Generally the facts SCEV provides about the increment step of add
38889dc1e3SArtur Pilipenko // recurrences are true if the backedge of the loop is taken, which implicitly
39889dc1e3SArtur Pilipenko // assumes that the guard doesn't fail. Using these facts to optimize the
40889dc1e3SArtur Pilipenko // guard results in a circular logic where the guard is optimized under the
41889dc1e3SArtur Pilipenko // assumption that it never fails.
42889dc1e3SArtur Pilipenko //
43889dc1e3SArtur Pilipenko // For example, in the loop below the induction variable will be marked as nuw
44889dc1e3SArtur Pilipenko // basing on the guard. Basing on nuw the guard predicate will be considered
45889dc1e3SArtur Pilipenko // monotonic. Given a monotonic condition it's tempting to replace the induction
46889dc1e3SArtur Pilipenko // variable in the condition with its value on the last iteration. But this
47889dc1e3SArtur Pilipenko // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
48889dc1e3SArtur Pilipenko //
49889dc1e3SArtur Pilipenko // for (int i = b; i != e; i++)
50889dc1e3SArtur Pilipenko // guard(i u< len)
51889dc1e3SArtur Pilipenko //
52889dc1e3SArtur Pilipenko // One of the ways to reason about this problem is to use an inductive proof
53889dc1e3SArtur Pilipenko // approach. Given the loop:
54889dc1e3SArtur Pilipenko //
558aadc643SArtur Pilipenko // if (B(0)) {
56889dc1e3SArtur Pilipenko // do {
578aadc643SArtur Pilipenko // I = PHI(0, I.INC)
58889dc1e3SArtur Pilipenko // I.INC = I + Step
59889dc1e3SArtur Pilipenko // guard(G(I));
608aadc643SArtur Pilipenko // } while (B(I));
61889dc1e3SArtur Pilipenko // }
62889dc1e3SArtur Pilipenko //
63889dc1e3SArtur Pilipenko // where B(x) and G(x) are predicates that map integers to booleans, we want a
64889dc1e3SArtur Pilipenko // loop invariant expression M such the following program has the same semantics
65889dc1e3SArtur Pilipenko // as the above:
66889dc1e3SArtur Pilipenko //
678aadc643SArtur Pilipenko // if (B(0)) {
68889dc1e3SArtur Pilipenko // do {
698aadc643SArtur Pilipenko // I = PHI(0, I.INC)
70889dc1e3SArtur Pilipenko // I.INC = I + Step
718aadc643SArtur Pilipenko // guard(G(0) && M);
728aadc643SArtur Pilipenko // } while (B(I));
73889dc1e3SArtur Pilipenko // }
74889dc1e3SArtur Pilipenko //
758aadc643SArtur Pilipenko // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
76889dc1e3SArtur Pilipenko //
77889dc1e3SArtur Pilipenko // Informal proof that the transformation above is correct:
78889dc1e3SArtur Pilipenko //
79889dc1e3SArtur Pilipenko // By the definition of guards we can rewrite the guard condition to:
808aadc643SArtur Pilipenko // G(I) && G(0) && M
81889dc1e3SArtur Pilipenko //
82889dc1e3SArtur Pilipenko // Let's prove that for each iteration of the loop:
838aadc643SArtur Pilipenko // G(0) && M => G(I)
84889dc1e3SArtur Pilipenko // And the condition above can be simplified to G(Start) && M.
85889dc1e3SArtur Pilipenko //
86889dc1e3SArtur Pilipenko // Induction base.
878aadc643SArtur Pilipenko // G(0) && M => G(0)
88889dc1e3SArtur Pilipenko //
898aadc643SArtur Pilipenko // Induction step. Assuming G(0) && M => G(I) on the subsequent
90889dc1e3SArtur Pilipenko // iteration:
91889dc1e3SArtur Pilipenko //
928aadc643SArtur Pilipenko // B(I) is true because it's the backedge condition.
93889dc1e3SArtur Pilipenko // G(I) is true because the backedge is guarded by this condition.
94889dc1e3SArtur Pilipenko //
958aadc643SArtur Pilipenko // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
96889dc1e3SArtur Pilipenko //
97889dc1e3SArtur Pilipenko // Note that we can use anything stronger than M, i.e. any condition which
98889dc1e3SArtur Pilipenko // implies M.
99889dc1e3SArtur Pilipenko //
1007b360434SAnna Thomas // When S = 1 (i.e. forward iterating loop), the transformation is supported
1017b360434SAnna Thomas // when:
102b4527e1cSArtur Pilipenko // * The loop has a single latch with the condition of the form:
1038aadc643SArtur Pilipenko // B(X) = latchStart + X <pred> latchLimit,
1048aadc643SArtur Pilipenko // where <pred> is u<, u<=, s<, or s<=.
1058aadc643SArtur Pilipenko // * The guard condition is of the form
1068aadc643SArtur Pilipenko // G(X) = guardStart + X u< guardLimit
107889dc1e3SArtur Pilipenko //
108b4527e1cSArtur Pilipenko // For the ult latch comparison case M is:
1098aadc643SArtur Pilipenko // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
1108aadc643SArtur Pilipenko // guardStart + X + 1 u< guardLimit
111889dc1e3SArtur Pilipenko //
112889dc1e3SArtur Pilipenko // The only way the antecedent can be true and the consequent can be false is
113889dc1e3SArtur Pilipenko // if
1148aadc643SArtur Pilipenko // X == guardLimit - 1 - guardStart
115889dc1e3SArtur Pilipenko // (and guardLimit is non-zero, but we won't use this latter fact).
1168aadc643SArtur Pilipenko // If X == guardLimit - 1 - guardStart then the second half of the antecedent is
1178aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart u< latchLimit
118889dc1e3SArtur Pilipenko // and its negation is
1198aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart u>= latchLimit
120889dc1e3SArtur Pilipenko //
1218aadc643SArtur Pilipenko // In other words, if
1228aadc643SArtur Pilipenko // latchLimit u<= latchStart + guardLimit - 1 - guardStart
1238aadc643SArtur Pilipenko // then:
124889dc1e3SArtur Pilipenko // (the ranges below are written in ConstantRange notation, where [A, B) is the
125889dc1e3SArtur Pilipenko // set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
126889dc1e3SArtur Pilipenko //
1278aadc643SArtur Pilipenko // forall X . guardStart + X u< guardLimit &&
1288aadc643SArtur Pilipenko // latchStart + X u< latchLimit =>
1298aadc643SArtur Pilipenko // guardStart + X + 1 u< guardLimit
1308aadc643SArtur Pilipenko // == forall X . guardStart + X u< guardLimit &&
1318aadc643SArtur Pilipenko // latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
1328aadc643SArtur Pilipenko // guardStart + X + 1 u< guardLimit
1338aadc643SArtur Pilipenko // == forall X . (guardStart + X) in [0, guardLimit) &&
1348aadc643SArtur Pilipenko // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
1358aadc643SArtur Pilipenko // (guardStart + X + 1) in [0, guardLimit)
1368aadc643SArtur Pilipenko // == forall X . X in [-guardStart, guardLimit - guardStart) &&
1378aadc643SArtur Pilipenko // X in [-latchStart, guardLimit - 1 - guardStart) =>
1388aadc643SArtur Pilipenko // X in [-guardStart - 1, guardLimit - guardStart - 1)
139889dc1e3SArtur Pilipenko // == true
140889dc1e3SArtur Pilipenko //
141889dc1e3SArtur Pilipenko // So the widened condition is:
1428aadc643SArtur Pilipenko // guardStart u< guardLimit &&
1438aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart u>= latchLimit
1448aadc643SArtur Pilipenko // Similarly for ule condition the widened condition is:
1458aadc643SArtur Pilipenko // guardStart u< guardLimit &&
1468aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart u> latchLimit
1478aadc643SArtur Pilipenko // For slt condition the widened condition is:
1488aadc643SArtur Pilipenko // guardStart u< guardLimit &&
1498aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart s>= latchLimit
1508aadc643SArtur Pilipenko // For sle condition the widened condition is:
1518aadc643SArtur Pilipenko // guardStart u< guardLimit &&
1528aadc643SArtur Pilipenko // latchStart + guardLimit - 1 - guardStart s> latchLimit
153889dc1e3SArtur Pilipenko //
1547b360434SAnna Thomas // When S = -1 (i.e. reverse iterating loop), the transformation is supported
1557b360434SAnna Thomas // when:
1567b360434SAnna Thomas // * The loop has a single latch with the condition of the form:
157c8016e7aSSerguei Katkov // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
1587b360434SAnna Thomas // * The guard condition is of the form
1597b360434SAnna Thomas // G(X) = X - 1 u< guardLimit
1607b360434SAnna Thomas //
1617b360434SAnna Thomas // For the ugt latch comparison case M is:
1627b360434SAnna Thomas // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
1637b360434SAnna Thomas //
1647b360434SAnna Thomas // The only way the antecedent can be true and the consequent can be false is if
1657b360434SAnna Thomas // X == 1.
1667b360434SAnna Thomas // If X == 1 then the second half of the antecedent is
1677b360434SAnna Thomas // 1 u> latchLimit, and its negation is latchLimit u>= 1.
1687b360434SAnna Thomas //
1697b360434SAnna Thomas // So the widened condition is:
1707b360434SAnna Thomas // guardStart u< guardLimit && latchLimit u>= 1.
1717b360434SAnna Thomas // Similarly for sgt condition the widened condition is:
1727b360434SAnna Thomas // guardStart u< guardLimit && latchLimit s>= 1.
173c8016e7aSSerguei Katkov // For uge condition the widened condition is:
174c8016e7aSSerguei Katkov // guardStart u< guardLimit && latchLimit u> 1.
175c8016e7aSSerguei Katkov // For sge condition the widened condition is:
176c8016e7aSSerguei Katkov // guardStart u< guardLimit && latchLimit s> 1.
1778fb3d57eSArtur Pilipenko //===----------------------------------------------------------------------===//
1788fb3d57eSArtur Pilipenko
1798fb3d57eSArtur Pilipenko #include "llvm/Transforms/Scalar/LoopPredication.h"
180c297e84bSFedor Sergeev #include "llvm/ADT/Statistic.h"
18192a7177eSPhilip Reames #include "llvm/Analysis/AliasAnalysis.h"
1829b1176b0SAnna Thomas #include "llvm/Analysis/BranchProbabilityInfo.h"
18328298e96SMax Kazantsev #include "llvm/Analysis/GuardUtils.h"
1848fb3d57eSArtur Pilipenko #include "llvm/Analysis/LoopInfo.h"
1858fb3d57eSArtur Pilipenko #include "llvm/Analysis/LoopPass.h"
18655bdb140SAnna Thomas #include "llvm/Analysis/MemorySSA.h"
18755bdb140SAnna Thomas #include "llvm/Analysis/MemorySSAUpdater.h"
1888fb3d57eSArtur Pilipenko #include "llvm/Analysis/ScalarEvolution.h"
1898fb3d57eSArtur Pilipenko #include "llvm/Analysis/ScalarEvolutionExpressions.h"
1908fb3d57eSArtur Pilipenko #include "llvm/IR/Function.h"
1918fb3d57eSArtur Pilipenko #include "llvm/IR/IntrinsicInst.h"
1928fb3d57eSArtur Pilipenko #include "llvm/IR/Module.h"
1938fb3d57eSArtur Pilipenko #include "llvm/IR/PatternMatch.h"
19405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
1956bda14b3SChandler Carruth #include "llvm/Pass.h"
1964c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
1978fb3d57eSArtur Pilipenko #include "llvm/Support/Debug.h"
1988fb3d57eSArtur Pilipenko #include "llvm/Transforms/Scalar.h"
19970c68a6bSPhilip Reames #include "llvm/Transforms/Utils/GuardUtils.h"
200d109e2a7SPhilip Reames #include "llvm/Transforms/Utils/Local.h"
2018fb3d57eSArtur Pilipenko #include "llvm/Transforms/Utils/LoopUtils.h"
202bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
2038fb3d57eSArtur Pilipenko
2048fb3d57eSArtur Pilipenko #define DEBUG_TYPE "loop-predication"
2058fb3d57eSArtur Pilipenko
206c297e84bSFedor Sergeev STATISTIC(TotalConsidered, "Number of guards considered");
207c297e84bSFedor Sergeev STATISTIC(TotalWidened, "Number of checks widened");
208c297e84bSFedor Sergeev
2098fb3d57eSArtur Pilipenko using namespace llvm;
2108fb3d57eSArtur Pilipenko
2111d02b13eSAnna Thomas static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
2121d02b13eSAnna Thomas cl::Hidden, cl::init(true));
2131d02b13eSAnna Thomas
2147b360434SAnna Thomas static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
2157b360434SAnna Thomas cl::Hidden, cl::init(true));
2169b1176b0SAnna Thomas
2179b1176b0SAnna Thomas static cl::opt<bool>
2189b1176b0SAnna Thomas SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
2199b1176b0SAnna Thomas cl::Hidden, cl::init(false));
2209b1176b0SAnna Thomas
2219b1176b0SAnna Thomas // This is the scale factor for the latch probability. We use this during
2229b1176b0SAnna Thomas // profitability analysis to find other exiting blocks that have a much higher
2239b1176b0SAnna Thomas // probability of exiting the loop instead of loop exiting via latch.
2249b1176b0SAnna Thomas // This value should be greater than 1 for a sane profitability check.
2259b1176b0SAnna Thomas static cl::opt<float> LatchExitProbabilityScale(
2269b1176b0SAnna Thomas "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
2279b1176b0SAnna Thomas cl::desc("scale factor for the latch probability. Value should be greater "
2289b1176b0SAnna Thomas "than 1. Lower values are ignored"));
2299b1176b0SAnna Thomas
230feb475f4SMax Kazantsev static cl::opt<bool> PredicateWidenableBranchGuards(
231feb475f4SMax Kazantsev "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
232feb475f4SMax Kazantsev cl::desc("Whether or not we should predicate guards "
233feb475f4SMax Kazantsev "expressed as widenable branches to deoptimize blocks"),
234feb475f4SMax Kazantsev cl::init(true));
235feb475f4SMax Kazantsev
2368fb3d57eSArtur Pilipenko namespace {
237a6c27804SArtur Pilipenko /// Represents an induction variable check:
238a6c27804SArtur Pilipenko /// icmp Pred, <induction variable>, <loop invariant limit>
239a6c27804SArtur Pilipenko struct LoopICmp {
240a6c27804SArtur Pilipenko ICmpInst::Predicate Pred;
241a6c27804SArtur Pilipenko const SCEVAddRecExpr *IV;
242a6c27804SArtur Pilipenko const SCEV *Limit;
LoopICmp__anon082da8af0111::LoopICmp243c488dfabSArtur Pilipenko LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
244c488dfabSArtur Pilipenko const SCEV *Limit)
245a6c27804SArtur Pilipenko : Pred(Pred), IV(IV), Limit(Limit) {}
2463a3cb929SKazu Hirata LoopICmp() = default;
dump__anon082da8af0111::LoopICmp24768797214SAnna Thomas void dump() {
24868797214SAnna Thomas dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
24968797214SAnna Thomas << ", Limit = " << *Limit << "\n";
25068797214SAnna Thomas }
251a6c27804SArtur Pilipenko };
252c488dfabSArtur Pilipenko
253099eca83SPhilip Reames class LoopPredication {
25492a7177eSPhilip Reames AliasAnalysis *AA;
255ad5a84c8SPhilip Reames DominatorTree *DT;
256c488dfabSArtur Pilipenko ScalarEvolution *SE;
257ad5a84c8SPhilip Reames LoopInfo *LI;
25855bdb140SAnna Thomas MemorySSAUpdater *MSSAU;
259c488dfabSArtur Pilipenko
260c488dfabSArtur Pilipenko Loop *L;
261c488dfabSArtur Pilipenko const DataLayout *DL;
262c488dfabSArtur Pilipenko BasicBlock *Preheader;
263889dc1e3SArtur Pilipenko LoopICmp LatchCheck;
264c488dfabSArtur Pilipenko
26568797214SAnna Thomas bool isSupportedStep(const SCEV* Step);
26619afdf74SPhilip Reames Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
267889dc1e3SArtur Pilipenko Optional<LoopICmp> parseLoopLatchICmp();
268a6c27804SArtur Pilipenko
269fbe64a2cSPhilip Reames /// Return an insertion point suitable for inserting a safe to speculate
270fbe64a2cSPhilip Reames /// instruction whose only user will be 'User' which has operands 'Ops'. A
271fbe64a2cSPhilip Reames /// trivial result would be the at the User itself, but we try to return a
272fbe64a2cSPhilip Reames /// loop invariant location if possible.
273fbe64a2cSPhilip Reames Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
274e46d77d1SPhilip Reames /// Same as above, *except* that this uses the SCEV definition of invariant
275e46d77d1SPhilip Reames /// which is that an expression *can be made* invariant via SCEVExpander.
276e46d77d1SPhilip Reames /// Thus, this version is only suitable for finding an insert point to be be
277e46d77d1SPhilip Reames /// passed to SCEVExpander!
278*9e6e631bSNikita Popov Instruction *findInsertPt(const SCEVExpander &Expander, Instruction *User,
279*9e6e631bSNikita Popov ArrayRef<const SCEV *> Ops);
280fbe64a2cSPhilip Reames
28192a7177eSPhilip Reames /// Return true if the value is known to produce a single fixed value across
28292a7177eSPhilip Reames /// all iterations on which it executes. Note that this does not imply
283bc93c2d7SMarek Kurdej /// speculation safety. That must be established separately.
28492a7177eSPhilip Reames bool isLoopInvariantValue(const SCEV* S);
28592a7177eSPhilip Reames
286e46d77d1SPhilip Reames Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
2873d4e1082SPhilip Reames ICmpInst::Predicate Pred, const SCEV *LHS,
2883d4e1082SPhilip Reames const SCEV *RHS);
2896780ba65SArtur Pilipenko
2908fb3d57eSArtur Pilipenko Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
291e46d77d1SPhilip Reames Instruction *Guard);
29268797214SAnna Thomas Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
29368797214SAnna Thomas LoopICmp RangeCheck,
29468797214SAnna Thomas SCEVExpander &Expander,
295e46d77d1SPhilip Reames Instruction *Guard);
2967b360434SAnna Thomas Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
2977b360434SAnna Thomas LoopICmp RangeCheck,
2987b360434SAnna Thomas SCEVExpander &Expander,
299e46d77d1SPhilip Reames Instruction *Guard);
300ca450878SMax Kazantsev unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
301e46d77d1SPhilip Reames SCEVExpander &Expander, Instruction *Guard);
3028fb3d57eSArtur Pilipenko bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
303feb475f4SMax Kazantsev bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
3049b1176b0SAnna Thomas // If the loop always exits through another block in the loop, we should not
3059b1176b0SAnna Thomas // predicate based on the latch check. For example, the latch check can be a
3069b1176b0SAnna Thomas // very coarse grained check and there can be more fine grained exit checks
3079403514eSAnna Thomas // within the loop.
3089b1176b0SAnna Thomas bool isLoopProfitableToPredicate();
3099b1176b0SAnna Thomas
310ad5a84c8SPhilip Reames bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
311ad5a84c8SPhilip Reames
3128fb3d57eSArtur Pilipenko public:
LoopPredication(AliasAnalysis * AA,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,MemorySSAUpdater * MSSAU)31355bdb140SAnna Thomas LoopPredication(AliasAnalysis *AA, DominatorTree *DT, ScalarEvolution *SE,
3149403514eSAnna Thomas LoopInfo *LI, MemorySSAUpdater *MSSAU)
3159403514eSAnna Thomas : AA(AA), DT(DT), SE(SE), LI(LI), MSSAU(MSSAU){};
3168fb3d57eSArtur Pilipenko bool runOnLoop(Loop *L);
3178fb3d57eSArtur Pilipenko };
3188fb3d57eSArtur Pilipenko
3198fb3d57eSArtur Pilipenko class LoopPredicationLegacyPass : public LoopPass {
3208fb3d57eSArtur Pilipenko public:
3218fb3d57eSArtur Pilipenko static char ID;
LoopPredicationLegacyPass()3228fb3d57eSArtur Pilipenko LoopPredicationLegacyPass() : LoopPass(ID) {
3238fb3d57eSArtur Pilipenko initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
3248fb3d57eSArtur Pilipenko }
3258fb3d57eSArtur Pilipenko
getAnalysisUsage(AnalysisUsage & AU) const3268fb3d57eSArtur Pilipenko void getAnalysisUsage(AnalysisUsage &AU) const override {
3279b1176b0SAnna Thomas AU.addRequired<BranchProbabilityInfoWrapperPass>();
3288fb3d57eSArtur Pilipenko getLoopAnalysisUsage(AU);
32955bdb140SAnna Thomas AU.addPreserved<MemorySSAWrapperPass>();
3308fb3d57eSArtur Pilipenko }
3318fb3d57eSArtur Pilipenko
runOnLoop(Loop * L,LPPassManager & LPM)3328fb3d57eSArtur Pilipenko bool runOnLoop(Loop *L, LPPassManager &LPM) override {
3338fb3d57eSArtur Pilipenko if (skipLoop(L))
3348fb3d57eSArtur Pilipenko return false;
3358fb3d57eSArtur Pilipenko auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
336ad5a84c8SPhilip Reames auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
337ad5a84c8SPhilip Reames auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
33855bdb140SAnna Thomas auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
33955bdb140SAnna Thomas std::unique_ptr<MemorySSAUpdater> MSSAU;
34055bdb140SAnna Thomas if (MSSAWP)
34155bdb140SAnna Thomas MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA());
34292a7177eSPhilip Reames auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3439403514eSAnna Thomas LoopPredication LP(AA, DT, SE, LI, MSSAU ? MSSAU.get() : nullptr);
3448fb3d57eSArtur Pilipenko return LP.runOnLoop(L);
3458fb3d57eSArtur Pilipenko }
3468fb3d57eSArtur Pilipenko };
3478fb3d57eSArtur Pilipenko
3488fb3d57eSArtur Pilipenko char LoopPredicationLegacyPass::ID = 0;
3491c03cc5aSAlina Sbirlea } // end namespace
3508fb3d57eSArtur Pilipenko
3518fb3d57eSArtur Pilipenko INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
3528fb3d57eSArtur Pilipenko "Loop predication", false, false)
INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)3539b1176b0SAnna Thomas INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
3548fb3d57eSArtur Pilipenko INITIALIZE_PASS_DEPENDENCY(LoopPass)
3558fb3d57eSArtur Pilipenko INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
3568fb3d57eSArtur Pilipenko "Loop predication", false, false)
3578fb3d57eSArtur Pilipenko
3588fb3d57eSArtur Pilipenko Pass *llvm::createLoopPredicationPass() {
3598fb3d57eSArtur Pilipenko return new LoopPredicationLegacyPass();
3608fb3d57eSArtur Pilipenko }
3618fb3d57eSArtur Pilipenko
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)3628fb3d57eSArtur Pilipenko PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
3638fb3d57eSArtur Pilipenko LoopStandardAnalysisResults &AR,
3648fb3d57eSArtur Pilipenko LPMUpdater &U) {
36555bdb140SAnna Thomas std::unique_ptr<MemorySSAUpdater> MSSAU;
36655bdb140SAnna Thomas if (AR.MSSA)
36755bdb140SAnna Thomas MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
3689403514eSAnna Thomas LoopPredication LP(&AR.AA, &AR.DT, &AR.SE, &AR.LI,
36955bdb140SAnna Thomas MSSAU ? MSSAU.get() : nullptr);
3708fb3d57eSArtur Pilipenko if (!LP.runOnLoop(&L))
3718fb3d57eSArtur Pilipenko return PreservedAnalyses::all();
3728fb3d57eSArtur Pilipenko
37355bdb140SAnna Thomas auto PA = getLoopPassPreservedAnalyses();
37455bdb140SAnna Thomas if (AR.MSSA)
37555bdb140SAnna Thomas PA.preserve<MemorySSAAnalysis>();
37655bdb140SAnna Thomas return PA;
3778fb3d57eSArtur Pilipenko }
3788fb3d57eSArtur Pilipenko
379099eca83SPhilip Reames Optional<LoopICmp>
parseLoopICmp(ICmpInst * ICI)38019afdf74SPhilip Reames LoopPredication::parseLoopICmp(ICmpInst *ICI) {
38119afdf74SPhilip Reames auto Pred = ICI->getPredicate();
38219afdf74SPhilip Reames auto *LHS = ICI->getOperand(0);
38319afdf74SPhilip Reames auto *RHS = ICI->getOperand(1);
38419afdf74SPhilip Reames
385a6c27804SArtur Pilipenko const SCEV *LHSS = SE->getSCEV(LHS);
386a6c27804SArtur Pilipenko if (isa<SCEVCouldNotCompute>(LHSS))
387a6c27804SArtur Pilipenko return None;
388a6c27804SArtur Pilipenko const SCEV *RHSS = SE->getSCEV(RHS);
389a6c27804SArtur Pilipenko if (isa<SCEVCouldNotCompute>(RHSS))
390a6c27804SArtur Pilipenko return None;
391a6c27804SArtur Pilipenko
392a6c27804SArtur Pilipenko // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
393a6c27804SArtur Pilipenko if (SE->isLoopInvariant(LHSS, L)) {
394a6c27804SArtur Pilipenko std::swap(LHS, RHS);
395a6c27804SArtur Pilipenko std::swap(LHSS, RHSS);
396a6c27804SArtur Pilipenko Pred = ICmpInst::getSwappedPredicate(Pred);
397a6c27804SArtur Pilipenko }
398a6c27804SArtur Pilipenko
399a6c27804SArtur Pilipenko const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
400a6c27804SArtur Pilipenko if (!AR || AR->getLoop() != L)
401a6c27804SArtur Pilipenko return None;
402a6c27804SArtur Pilipenko
403a6c27804SArtur Pilipenko return LoopICmp(Pred, AR, RHSS);
404a6c27804SArtur Pilipenko }
405a6c27804SArtur Pilipenko
expandCheck(SCEVExpander & Expander,Instruction * Guard,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)4066780ba65SArtur Pilipenko Value *LoopPredication::expandCheck(SCEVExpander &Expander,
407e46d77d1SPhilip Reames Instruction *Guard,
4086780ba65SArtur Pilipenko ICmpInst::Predicate Pred, const SCEV *LHS,
4093d4e1082SPhilip Reames const SCEV *RHS) {
4106780ba65SArtur Pilipenko Type *Ty = LHS->getType();
4116780ba65SArtur Pilipenko assert(Ty == RHS->getType() && "expandCheck operands have different types?");
412ead69ee4SArtur Pilipenko
413e46d77d1SPhilip Reames if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
414e46d77d1SPhilip Reames IRBuilder<> Builder(Guard);
415ead69ee4SArtur Pilipenko if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
416ead69ee4SArtur Pilipenko return Builder.getTrue();
41705e3e554SPhilip Reames if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
41805e3e554SPhilip Reames LHS, RHS))
41905e3e554SPhilip Reames return Builder.getFalse();
420e46d77d1SPhilip Reames }
421ead69ee4SArtur Pilipenko
422*9e6e631bSNikita Popov Value *LHSV =
423*9e6e631bSNikita Popov Expander.expandCodeFor(LHS, Ty, findInsertPt(Expander, Guard, {LHS}));
424*9e6e631bSNikita Popov Value *RHSV =
425*9e6e631bSNikita Popov Expander.expandCodeFor(RHS, Ty, findInsertPt(Expander, Guard, {RHS}));
426e46d77d1SPhilip Reames IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
4276780ba65SArtur Pilipenko return Builder.CreateICmp(Pred, LHSV, RHSV);
4286780ba65SArtur Pilipenko }
4296780ba65SArtur Pilipenko
4300912b06fSPhilip Reames // Returns true if its safe to truncate the IV to RangeCheckType.
4310912b06fSPhilip Reames // When the IV type is wider than the range operand type, we can still do loop
4320912b06fSPhilip Reames // predication, by generating SCEVs for the range and latch that are of the
4330912b06fSPhilip Reames // same type. We achieve this by generating a SCEV truncate expression for the
4340912b06fSPhilip Reames // latch IV. This is done iff truncation of the IV is a safe operation,
4350912b06fSPhilip Reames // without loss of information.
4360912b06fSPhilip Reames // Another way to achieve this is by generating a wider type SCEV for the
4370912b06fSPhilip Reames // range check operand, however, this needs a more involved check that
4380912b06fSPhilip Reames // operands do not overflow. This can lead to loss of information when the
4390912b06fSPhilip Reames // range operand is of the form: add i32 %offset, %iv. We need to prove that
4400912b06fSPhilip Reames // sext(x + y) is same as sext(x) + sext(y).
4410912b06fSPhilip Reames // This function returns true if we can safely represent the IV type in
4420912b06fSPhilip Reames // the RangeCheckType without loss of information.
isSafeToTruncateWideIVType(const DataLayout & DL,ScalarEvolution & SE,const LoopICmp LatchCheck,Type * RangeCheckType)4439ed16737SPhilip Reames static bool isSafeToTruncateWideIVType(const DataLayout &DL,
4449ed16737SPhilip Reames ScalarEvolution &SE,
4450912b06fSPhilip Reames const LoopICmp LatchCheck,
4460912b06fSPhilip Reames Type *RangeCheckType) {
4470912b06fSPhilip Reames if (!EnableIVTruncation)
4480912b06fSPhilip Reames return false;
44924156364SCaroline Concatto assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedSize() >
45024156364SCaroline Concatto DL.getTypeSizeInBits(RangeCheckType).getFixedSize() &&
4510912b06fSPhilip Reames "Expected latch check IV type to be larger than range check operand "
4520912b06fSPhilip Reames "type!");
4530912b06fSPhilip Reames // The start and end values of the IV should be known. This is to guarantee
4540912b06fSPhilip Reames // that truncating the wide type will not lose information.
4550912b06fSPhilip Reames auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
4560912b06fSPhilip Reames auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
4570912b06fSPhilip Reames if (!Limit || !Start)
4580912b06fSPhilip Reames return false;
4590912b06fSPhilip Reames // This check makes sure that the IV does not change sign during loop
4600912b06fSPhilip Reames // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
4610912b06fSPhilip Reames // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
4620912b06fSPhilip Reames // IV wraps around, and the truncation of the IV would lose the range of
4630912b06fSPhilip Reames // iterations between 2^32 and 2^64.
464a5b2e795SMax Kazantsev if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred))
4650912b06fSPhilip Reames return false;
4660912b06fSPhilip Reames // The active bits should be less than the bits in the RangeCheckType. This
4670912b06fSPhilip Reames // guarantees that truncating the latch check to RangeCheckType is a safe
4680912b06fSPhilip Reames // operation.
46924156364SCaroline Concatto auto RangeCheckTypeBitSize =
47024156364SCaroline Concatto DL.getTypeSizeInBits(RangeCheckType).getFixedSize();
4710912b06fSPhilip Reames return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
4720912b06fSPhilip Reames Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
4730912b06fSPhilip Reames }
4740912b06fSPhilip Reames
4750912b06fSPhilip Reames
4769ed16737SPhilip Reames // Return an LoopICmp describing a latch check equivlent to LatchCheck but with
4779ed16737SPhilip Reames // the requested type if safe to do so. May involve the use of a new IV.
generateLoopLatchCheck(const DataLayout & DL,ScalarEvolution & SE,const LoopICmp LatchCheck,Type * RangeCheckType)4789ed16737SPhilip Reames static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
4799ed16737SPhilip Reames ScalarEvolution &SE,
4809ed16737SPhilip Reames const LoopICmp LatchCheck,
4819ed16737SPhilip Reames Type *RangeCheckType) {
4821d02b13eSAnna Thomas
4831d02b13eSAnna Thomas auto *LatchType = LatchCheck.IV->getType();
4841d02b13eSAnna Thomas if (RangeCheckType == LatchType)
4851d02b13eSAnna Thomas return LatchCheck;
4861d02b13eSAnna Thomas // For now, bail out if latch type is narrower than range type.
48724156364SCaroline Concatto if (DL.getTypeSizeInBits(LatchType).getFixedSize() <
48824156364SCaroline Concatto DL.getTypeSizeInBits(RangeCheckType).getFixedSize())
4891d02b13eSAnna Thomas return None;
4909ed16737SPhilip Reames if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
4911d02b13eSAnna Thomas return None;
4921d02b13eSAnna Thomas // We can now safely identify the truncated version of the IV and limit for
4931d02b13eSAnna Thomas // RangeCheckType.
4941d02b13eSAnna Thomas LoopICmp NewLatchCheck;
4951d02b13eSAnna Thomas NewLatchCheck.Pred = LatchCheck.Pred;
4961d02b13eSAnna Thomas NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
4979ed16737SPhilip Reames SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
4981d02b13eSAnna Thomas if (!NewLatchCheck.IV)
4991d02b13eSAnna Thomas return None;
5009ed16737SPhilip Reames NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
501d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
502d34e60caSNicola Zaghen << "can be represented as range check type:"
503d34e60caSNicola Zaghen << *RangeCheckType << "\n");
504d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
505d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
5061d02b13eSAnna Thomas return NewLatchCheck;
5071d02b13eSAnna Thomas }
5081d02b13eSAnna Thomas
isSupportedStep(const SCEV * Step)50968797214SAnna Thomas bool LoopPredication::isSupportedStep(const SCEV* Step) {
5107b360434SAnna Thomas return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
5111d02b13eSAnna Thomas }
5128fb3d57eSArtur Pilipenko
findInsertPt(Instruction * Use,ArrayRef<Value * > Ops)513fbe64a2cSPhilip Reames Instruction *LoopPredication::findInsertPt(Instruction *Use,
514fbe64a2cSPhilip Reames ArrayRef<Value*> Ops) {
515fbe64a2cSPhilip Reames for (Value *Op : Ops)
516fbe64a2cSPhilip Reames if (!L->isLoopInvariant(Op))
517fbe64a2cSPhilip Reames return Use;
518fbe64a2cSPhilip Reames return Preheader->getTerminator();
519fbe64a2cSPhilip Reames }
520fbe64a2cSPhilip Reames
findInsertPt(const SCEVExpander & Expander,Instruction * Use,ArrayRef<const SCEV * > Ops)521*9e6e631bSNikita Popov Instruction *LoopPredication::findInsertPt(const SCEVExpander &Expander,
522*9e6e631bSNikita Popov Instruction *Use,
523e46d77d1SPhilip Reames ArrayRef<const SCEV *> Ops) {
52492a7177eSPhilip Reames // Subtlety: SCEV considers things to be invariant if the value produced is
52592a7177eSPhilip Reames // the same across iterations. This is not the same as being able to
52692a7177eSPhilip Reames // evaluate outside the loop, which is what we actually need here.
527e46d77d1SPhilip Reames for (const SCEV *Op : Ops)
52892a7177eSPhilip Reames if (!SE->isLoopInvariant(Op, L) ||
529*9e6e631bSNikita Popov !Expander.isSafeToExpandAt(Op, Preheader->getTerminator()))
530e46d77d1SPhilip Reames return Use;
531e46d77d1SPhilip Reames return Preheader->getTerminator();
532e46d77d1SPhilip Reames }
533e46d77d1SPhilip Reames
isLoopInvariantValue(const SCEV * S)53492a7177eSPhilip Reames bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
53592a7177eSPhilip Reames // Handling expressions which produce invariant results, but *haven't* yet
53692a7177eSPhilip Reames // been removed from the loop serves two important purposes.
53792a7177eSPhilip Reames // 1) Most importantly, it resolves a pass ordering cycle which would
53892a7177eSPhilip Reames // otherwise need us to iteration licm, loop-predication, and either
53992a7177eSPhilip Reames // loop-unswitch or loop-peeling to make progress on examples with lots of
54092a7177eSPhilip Reames // predicable range checks in a row. (Since, in the general case, we can't
54192a7177eSPhilip Reames // hoist the length checks until the dominating checks have been discharged
54292a7177eSPhilip Reames // as we can't prove doing so is safe.)
54392a7177eSPhilip Reames // 2) As a nice side effect, this exposes the value of peeling or unswitching
54492a7177eSPhilip Reames // much more obviously in the IR. Otherwise, the cost modeling for other
54592a7177eSPhilip Reames // transforms would end up needing to duplicate all of this logic to model a
54692a7177eSPhilip Reames // check which becomes predictable based on a modeled peel or unswitch.
54792a7177eSPhilip Reames //
54892a7177eSPhilip Reames // The cost of doing so in the worst case is an extra fill from the stack in
54992a7177eSPhilip Reames // the loop to materialize the loop invariant test value instead of checking
55092a7177eSPhilip Reames // against the original IV which is presumable in a register inside the loop.
55192a7177eSPhilip Reames // Such cases are presumably rare, and hint at missing oppurtunities for
55292a7177eSPhilip Reames // other passes.
553e46d77d1SPhilip Reames
55492a7177eSPhilip Reames if (SE->isLoopInvariant(S, L))
55592a7177eSPhilip Reames // Note: This the SCEV variant, so the original Value* may be within the
55692a7177eSPhilip Reames // loop even though SCEV has proven it is loop invariant.
55792a7177eSPhilip Reames return true;
55892a7177eSPhilip Reames
55992a7177eSPhilip Reames // Handle a particular important case which SCEV doesn't yet know about which
56092a7177eSPhilip Reames // shows up in range checks on arrays with immutable lengths.
56192a7177eSPhilip Reames // TODO: This should be sunk inside SCEV.
56292a7177eSPhilip Reames if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
56392a7177eSPhilip Reames if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
564adf288c5SPhilip Reames if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
56592a7177eSPhilip Reames if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
56627820f99SPhilip Reames LI->hasMetadata(LLVMContext::MD_invariant_load))
56792a7177eSPhilip Reames return true;
56892a7177eSPhilip Reames return false;
56968797214SAnna Thomas }
57068797214SAnna Thomas
widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)57168797214SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
572099eca83SPhilip Reames LoopICmp LatchCheck, LoopICmp RangeCheck,
573e46d77d1SPhilip Reames SCEVExpander &Expander, Instruction *Guard) {
57468797214SAnna Thomas auto *Ty = RangeCheck.IV->getType();
57568797214SAnna Thomas // Generate the widened condition for the forward loop:
5768aadc643SArtur Pilipenko // guardStart u< guardLimit &&
5778aadc643SArtur Pilipenko // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
578b4527e1cSArtur Pilipenko // where <pred> depends on the latch condition predicate. See the file
579b4527e1cSArtur Pilipenko // header comment for the reasoning.
58068797214SAnna Thomas // guardLimit - guardStart + latchStart - 1
58168797214SAnna Thomas const SCEV *GuardStart = RangeCheck.IV->getStart();
58268797214SAnna Thomas const SCEV *GuardLimit = RangeCheck.Limit;
58368797214SAnna Thomas const SCEV *LatchStart = LatchCheck.IV->getStart();
58468797214SAnna Thomas const SCEV *LatchLimit = LatchCheck.Limit;
58592a7177eSPhilip Reames // Subtlety: We need all the values to be *invariant* across all iterations,
58692a7177eSPhilip Reames // but we only need to check expansion safety for those which *aren't*
58792a7177eSPhilip Reames // already guaranteed to dominate the guard.
58892a7177eSPhilip Reames if (!isLoopInvariantValue(GuardStart) ||
58992a7177eSPhilip Reames !isLoopInvariantValue(GuardLimit) ||
59092a7177eSPhilip Reames !isLoopInvariantValue(LatchStart) ||
59192a7177eSPhilip Reames !isLoopInvariantValue(LatchLimit)) {
59292a7177eSPhilip Reames LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
59392a7177eSPhilip Reames return None;
59492a7177eSPhilip Reames }
595dcf4b733SNikita Popov if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
596dcf4b733SNikita Popov !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
59792a7177eSPhilip Reames LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
59892a7177eSPhilip Reames return None;
59992a7177eSPhilip Reames }
6008aadc643SArtur Pilipenko
6018aadc643SArtur Pilipenko // guardLimit - guardStart + latchStart - 1
6028aadc643SArtur Pilipenko const SCEV *RHS =
6038aadc643SArtur Pilipenko SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
6048aadc643SArtur Pilipenko SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
6053cb4c34aSSerguei Katkov auto LimitCheckPred =
6063cb4c34aSSerguei Katkov ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
607aab28666SArtur Pilipenko
608d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
609d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
610d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
6118aadc643SArtur Pilipenko
6128aadc643SArtur Pilipenko auto *LimitCheck =
613e46d77d1SPhilip Reames expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
614e46d77d1SPhilip Reames auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
6153d4e1082SPhilip Reames GuardStart, GuardLimit);
616e46d77d1SPhilip Reames IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
617889dc1e3SArtur Pilipenko return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
6188fb3d57eSArtur Pilipenko }
6197b360434SAnna Thomas
widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)6207b360434SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
621099eca83SPhilip Reames LoopICmp LatchCheck, LoopICmp RangeCheck,
622e46d77d1SPhilip Reames SCEVExpander &Expander, Instruction *Guard) {
6237b360434SAnna Thomas auto *Ty = RangeCheck.IV->getType();
6247b360434SAnna Thomas const SCEV *GuardStart = RangeCheck.IV->getStart();
6257b360434SAnna Thomas const SCEV *GuardLimit = RangeCheck.Limit;
62692a7177eSPhilip Reames const SCEV *LatchStart = LatchCheck.IV->getStart();
6277b360434SAnna Thomas const SCEV *LatchLimit = LatchCheck.Limit;
62892a7177eSPhilip Reames // Subtlety: We need all the values to be *invariant* across all iterations,
62992a7177eSPhilip Reames // but we only need to check expansion safety for those which *aren't*
63092a7177eSPhilip Reames // already guaranteed to dominate the guard.
63192a7177eSPhilip Reames if (!isLoopInvariantValue(GuardStart) ||
63292a7177eSPhilip Reames !isLoopInvariantValue(GuardLimit) ||
63392a7177eSPhilip Reames !isLoopInvariantValue(LatchStart) ||
63492a7177eSPhilip Reames !isLoopInvariantValue(LatchLimit)) {
63592a7177eSPhilip Reames LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
63692a7177eSPhilip Reames return None;
63792a7177eSPhilip Reames }
638dcf4b733SNikita Popov if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
639dcf4b733SNikita Popov !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
640d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
6417b360434SAnna Thomas return None;
6427b360434SAnna Thomas }
6437b360434SAnna Thomas // The decrement of the latch check IV should be the same as the
6447b360434SAnna Thomas // rangeCheckIV.
6457b360434SAnna Thomas auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
6467b360434SAnna Thomas if (RangeCheck.IV != PostDecLatchCheckIV) {
647d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
6487b360434SAnna Thomas << *PostDecLatchCheckIV
6497b360434SAnna Thomas << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
6507b360434SAnna Thomas return None;
6517b360434SAnna Thomas }
6527b360434SAnna Thomas
6537b360434SAnna Thomas // Generate the widened condition for CountDownLoop:
6547b360434SAnna Thomas // guardStart u< guardLimit &&
6557b360434SAnna Thomas // latchLimit <pred> 1.
6567b360434SAnna Thomas // See the header comment for reasoning of the checks.
6573cb4c34aSSerguei Katkov auto LimitCheckPred =
6583cb4c34aSSerguei Katkov ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
659e46d77d1SPhilip Reames auto *FirstIterationCheck = expandCheck(Expander, Guard,
660e46d77d1SPhilip Reames ICmpInst::ICMP_ULT,
6613d4e1082SPhilip Reames GuardStart, GuardLimit);
662e46d77d1SPhilip Reames auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
6633d4e1082SPhilip Reames SE->getOne(Ty));
664e46d77d1SPhilip Reames IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
6657b360434SAnna Thomas return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
6667b360434SAnna Thomas }
6677b360434SAnna Thomas
normalizePredicate(ScalarEvolution * SE,Loop * L,LoopICmp & RC)668099eca83SPhilip Reames static void normalizePredicate(ScalarEvolution *SE, Loop *L,
669099eca83SPhilip Reames LoopICmp& RC) {
6700e344e9dSPhilip Reames // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
6710e344e9dSPhilip Reames // ULT/UGE form for ease of handling by our caller.
6720e344e9dSPhilip Reames if (ICmpInst::isEquality(RC.Pred) &&
673099eca83SPhilip Reames RC.IV->getStepRecurrence(*SE)->isOne() &&
674099eca83SPhilip Reames SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
6750e344e9dSPhilip Reames RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
6760e344e9dSPhilip Reames ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
677099eca83SPhilip Reames }
678099eca83SPhilip Reames
679099eca83SPhilip Reames
68068797214SAnna Thomas /// If ICI can be widened to a loop invariant condition emits the loop
68168797214SAnna Thomas /// invariant condition in the loop preheader and return it, otherwise
68268797214SAnna Thomas /// returns None.
widenICmpRangeCheck(ICmpInst * ICI,SCEVExpander & Expander,Instruction * Guard)68368797214SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
68468797214SAnna Thomas SCEVExpander &Expander,
685e46d77d1SPhilip Reames Instruction *Guard) {
686d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
687d34e60caSNicola Zaghen LLVM_DEBUG(ICI->dump());
68868797214SAnna Thomas
68968797214SAnna Thomas // parseLoopStructure guarantees that the latch condition is:
69068797214SAnna Thomas // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
69168797214SAnna Thomas // We are looking for the range checks of the form:
69268797214SAnna Thomas // i u< guardLimit
69368797214SAnna Thomas auto RangeCheck = parseLoopICmp(ICI);
69468797214SAnna Thomas if (!RangeCheck) {
695d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
69668797214SAnna Thomas return None;
69768797214SAnna Thomas }
698d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Guard check:\n");
699d34e60caSNicola Zaghen LLVM_DEBUG(RangeCheck->dump());
70068797214SAnna Thomas if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
701d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
702d34e60caSNicola Zaghen << RangeCheck->Pred << ")!\n");
70368797214SAnna Thomas return None;
70468797214SAnna Thomas }
70568797214SAnna Thomas auto *RangeCheckIV = RangeCheck->IV;
70668797214SAnna Thomas if (!RangeCheckIV->isAffine()) {
707d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
70868797214SAnna Thomas return None;
70968797214SAnna Thomas }
71068797214SAnna Thomas auto *Step = RangeCheckIV->getStepRecurrence(*SE);
71168797214SAnna Thomas // We cannot just compare with latch IV step because the latch and range IVs
71268797214SAnna Thomas // may have different types.
71368797214SAnna Thomas if (!isSupportedStep(Step)) {
714d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
71568797214SAnna Thomas return None;
71668797214SAnna Thomas }
71768797214SAnna Thomas auto *Ty = RangeCheckIV->getType();
7189ed16737SPhilip Reames auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
71968797214SAnna Thomas if (!CurrLatchCheckOpt) {
720d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
72168797214SAnna Thomas "corresponding to range type: "
72268797214SAnna Thomas << *Ty << "\n");
72368797214SAnna Thomas return None;
72468797214SAnna Thomas }
72568797214SAnna Thomas
72668797214SAnna Thomas LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
7277b360434SAnna Thomas // At this point, the range and latch step should have the same type, but need
7287b360434SAnna Thomas // not have the same value (we support both 1 and -1 steps).
7297b360434SAnna Thomas assert(Step->getType() ==
7307b360434SAnna Thomas CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
7317b360434SAnna Thomas "Range and latch steps should be of same type!");
7327b360434SAnna Thomas if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
733d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
7347b360434SAnna Thomas return None;
7357b360434SAnna Thomas }
73668797214SAnna Thomas
7377b360434SAnna Thomas if (Step->isOne())
73868797214SAnna Thomas return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
739e46d77d1SPhilip Reames Expander, Guard);
7407b360434SAnna Thomas else {
7417b360434SAnna Thomas assert(Step->isAllOnesValue() && "Step should be -1!");
7427b360434SAnna Thomas return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
743e46d77d1SPhilip Reames Expander, Guard);
7447b360434SAnna Thomas }
74568797214SAnna Thomas }
7468fb3d57eSArtur Pilipenko
collectChecks(SmallVectorImpl<Value * > & Checks,Value * Condition,SCEVExpander & Expander,Instruction * Guard)747ca450878SMax Kazantsev unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
748ca450878SMax Kazantsev Value *Condition,
749ca450878SMax Kazantsev SCEVExpander &Expander,
750e46d77d1SPhilip Reames Instruction *Guard) {
751ca450878SMax Kazantsev unsigned NumWidened = 0;
7528fb3d57eSArtur Pilipenko // The guard condition is expected to be in form of:
7538fb3d57eSArtur Pilipenko // cond1 && cond2 && cond3 ...
7540909ca13SHiroshi Inoue // Iterate over subconditions looking for icmp conditions which can be
7558fb3d57eSArtur Pilipenko // widened across loop iterations. Widening these conditions remember the
7568fb3d57eSArtur Pilipenko // resulting list of subconditions in Checks vector.
757ca450878SMax Kazantsev SmallVector<Value *, 4> Worklist(1, Condition);
7588fb3d57eSArtur Pilipenko SmallPtrSet<Value *, 4> Visited;
759adb3ece2SPhilip Reames Value *WideableCond = nullptr;
7608fb3d57eSArtur Pilipenko do {
7618fb3d57eSArtur Pilipenko Value *Condition = Worklist.pop_back_val();
7628fb3d57eSArtur Pilipenko if (!Visited.insert(Condition).second)
7638fb3d57eSArtur Pilipenko continue;
7648fb3d57eSArtur Pilipenko
7658fb3d57eSArtur Pilipenko Value *LHS, *RHS;
7668fb3d57eSArtur Pilipenko using namespace llvm::PatternMatch;
7678fb3d57eSArtur Pilipenko if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
7688fb3d57eSArtur Pilipenko Worklist.push_back(LHS);
7698fb3d57eSArtur Pilipenko Worklist.push_back(RHS);
7708fb3d57eSArtur Pilipenko continue;
7718fb3d57eSArtur Pilipenko }
7728fb3d57eSArtur Pilipenko
773adb3ece2SPhilip Reames if (match(Condition,
774adb3ece2SPhilip Reames m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
775adb3ece2SPhilip Reames // Pick any, we don't care which
776adb3ece2SPhilip Reames WideableCond = Condition;
777adb3ece2SPhilip Reames continue;
778adb3ece2SPhilip Reames }
779adb3ece2SPhilip Reames
7808fb3d57eSArtur Pilipenko if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
7813d4e1082SPhilip Reames if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
782e46d77d1SPhilip Reames Guard)) {
7837a47ee51SKazu Hirata Checks.push_back(*NewRangeCheck);
7848fb3d57eSArtur Pilipenko NumWidened++;
7858fb3d57eSArtur Pilipenko continue;
7868fb3d57eSArtur Pilipenko }
7878fb3d57eSArtur Pilipenko }
7888fb3d57eSArtur Pilipenko
7898fb3d57eSArtur Pilipenko // Save the condition as is if we can't widen it
7908fb3d57eSArtur Pilipenko Checks.push_back(Condition);
791ca450878SMax Kazantsev } while (!Worklist.empty());
792adb3ece2SPhilip Reames // At the moment, our matching logic for wideable conditions implicitly
793adb3ece2SPhilip Reames // assumes we preserve the form: (br (and Cond, WC())). FIXME
794adb3ece2SPhilip Reames // Note that if there were multiple calls to wideable condition in the
795adb3ece2SPhilip Reames // traversal, we only need to keep one, and which one is arbitrary.
796adb3ece2SPhilip Reames if (WideableCond)
797adb3ece2SPhilip Reames Checks.push_back(WideableCond);
798ca450878SMax Kazantsev return NumWidened;
799ca450878SMax Kazantsev }
8008fb3d57eSArtur Pilipenko
widenGuardConditions(IntrinsicInst * Guard,SCEVExpander & Expander)801ca450878SMax Kazantsev bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
802ca450878SMax Kazantsev SCEVExpander &Expander) {
803ca450878SMax Kazantsev LLVM_DEBUG(dbgs() << "Processing guard:\n");
804ca450878SMax Kazantsev LLVM_DEBUG(Guard->dump());
805ca450878SMax Kazantsev
806ca450878SMax Kazantsev TotalConsidered++;
807ca450878SMax Kazantsev SmallVector<Value *, 4> Checks;
808ca450878SMax Kazantsev unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
809e46d77d1SPhilip Reames Guard);
8108fb3d57eSArtur Pilipenko if (NumWidened == 0)
8118fb3d57eSArtur Pilipenko return false;
8128fb3d57eSArtur Pilipenko
813c297e84bSFedor Sergeev TotalWidened += NumWidened;
814c297e84bSFedor Sergeev
8158fb3d57eSArtur Pilipenko // Emit the new guard condition
816e46d77d1SPhilip Reames IRBuilder<> Builder(findInsertPt(Guard, Checks));
8179e62c864SPhilip Reames Value *AllChecks = Builder.CreateAnd(Checks);
818d109e2a7SPhilip Reames auto *OldCond = Guard->getOperand(0);
8199e62c864SPhilip Reames Guard->setOperand(0, AllChecks);
82055bdb140SAnna Thomas RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
8218fb3d57eSArtur Pilipenko
822d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
8238fb3d57eSArtur Pilipenko return true;
8248fb3d57eSArtur Pilipenko }
8258fb3d57eSArtur Pilipenko
widenWidenableBranchGuardConditions(BranchInst * BI,SCEVExpander & Expander)826feb475f4SMax Kazantsev bool LoopPredication::widenWidenableBranchGuardConditions(
827f608678fSPhilip Reames BranchInst *BI, SCEVExpander &Expander) {
828f608678fSPhilip Reames assert(isGuardAsWidenableBranch(BI) && "Must be!");
829feb475f4SMax Kazantsev LLVM_DEBUG(dbgs() << "Processing guard:\n");
830f608678fSPhilip Reames LLVM_DEBUG(BI->dump());
831feb475f4SMax Kazantsev
832feb475f4SMax Kazantsev TotalConsidered++;
833feb475f4SMax Kazantsev SmallVector<Value *, 4> Checks;
834adb3ece2SPhilip Reames unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
835e46d77d1SPhilip Reames Expander, BI);
836feb475f4SMax Kazantsev if (NumWidened == 0)
837feb475f4SMax Kazantsev return false;
838feb475f4SMax Kazantsev
839feb475f4SMax Kazantsev TotalWidened += NumWidened;
840feb475f4SMax Kazantsev
841feb475f4SMax Kazantsev // Emit the new guard condition
842e46d77d1SPhilip Reames IRBuilder<> Builder(findInsertPt(BI, Checks));
8439e62c864SPhilip Reames Value *AllChecks = Builder.CreateAnd(Checks);
844adb3ece2SPhilip Reames auto *OldCond = BI->getCondition();
8459e62c864SPhilip Reames BI->setCondition(AllChecks);
84655bdb140SAnna Thomas RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
847f608678fSPhilip Reames assert(isGuardAsWidenableBranch(BI) &&
848feb475f4SMax Kazantsev "Stopped being a guard after transform?");
849feb475f4SMax Kazantsev
850feb475f4SMax Kazantsev LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
851feb475f4SMax Kazantsev return true;
852feb475f4SMax Kazantsev }
853feb475f4SMax Kazantsev
parseLoopLatchICmp()854099eca83SPhilip Reames Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
855889dc1e3SArtur Pilipenko using namespace PatternMatch;
856889dc1e3SArtur Pilipenko
857889dc1e3SArtur Pilipenko BasicBlock *LoopLatch = L->getLoopLatch();
858889dc1e3SArtur Pilipenko if (!LoopLatch) {
859d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
860889dc1e3SArtur Pilipenko return None;
861889dc1e3SArtur Pilipenko }
862889dc1e3SArtur Pilipenko
86319afdf74SPhilip Reames auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
864101915cfSPhilip Reames if (!BI || !BI->isConditional()) {
865d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
866889dc1e3SArtur Pilipenko return None;
867889dc1e3SArtur Pilipenko }
86819afdf74SPhilip Reames BasicBlock *TrueDest = BI->getSuccessor(0);
8694e875464SRichard Trieu assert(
8704e875464SRichard Trieu (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
871889dc1e3SArtur Pilipenko "One of the latch's destinations must be the header");
872889dc1e3SArtur Pilipenko
87319afdf74SPhilip Reames auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
874101915cfSPhilip Reames if (!ICI) {
87519afdf74SPhilip Reames LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
87619afdf74SPhilip Reames return None;
87719afdf74SPhilip Reames }
87819afdf74SPhilip Reames auto Result = parseLoopICmp(ICI);
879889dc1e3SArtur Pilipenko if (!Result) {
880d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
881889dc1e3SArtur Pilipenko return None;
882889dc1e3SArtur Pilipenko }
883889dc1e3SArtur Pilipenko
88419afdf74SPhilip Reames if (TrueDest != L->getHeader())
88519afdf74SPhilip Reames Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
88619afdf74SPhilip Reames
887889dc1e3SArtur Pilipenko // Check affine first, so if it's not we don't try to compute the step
888889dc1e3SArtur Pilipenko // recurrence.
889889dc1e3SArtur Pilipenko if (!Result->IV->isAffine()) {
890d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
891889dc1e3SArtur Pilipenko return None;
892889dc1e3SArtur Pilipenko }
893889dc1e3SArtur Pilipenko
894889dc1e3SArtur Pilipenko auto *Step = Result->IV->getStepRecurrence(*SE);
89568797214SAnna Thomas if (!isSupportedStep(Step)) {
896d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
897889dc1e3SArtur Pilipenko return None;
898889dc1e3SArtur Pilipenko }
899889dc1e3SArtur Pilipenko
90068797214SAnna Thomas auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
9017b360434SAnna Thomas if (Step->isOne()) {
90268797214SAnna Thomas return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
90368797214SAnna Thomas Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
9047b360434SAnna Thomas } else {
9057b360434SAnna Thomas assert(Step->isAllOnesValue() && "Step should be -1!");
906c8016e7aSSerguei Katkov return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
907c8016e7aSSerguei Katkov Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
9087b360434SAnna Thomas }
90968797214SAnna Thomas };
91068797214SAnna Thomas
911099eca83SPhilip Reames normalizePredicate(SE, L, *Result);
91268797214SAnna Thomas if (IsUnsupportedPredicate(Step, Result->Pred)) {
913d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
91468797214SAnna Thomas << ")!\n");
91568797214SAnna Thomas return None;
91668797214SAnna Thomas }
91719afdf74SPhilip Reames
918889dc1e3SArtur Pilipenko return Result;
919889dc1e3SArtur Pilipenko }
920889dc1e3SArtur Pilipenko
9211d02b13eSAnna Thomas
isLoopProfitableToPredicate()9229b1176b0SAnna Thomas bool LoopPredication::isLoopProfitableToPredicate() {
9239403514eSAnna Thomas if (SkipProfitabilityChecks)
9249b1176b0SAnna Thomas return true;
9259b1176b0SAnna Thomas
926c6caddb7SSerguei Katkov SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
9279b1176b0SAnna Thomas L->getExitEdges(ExitEdges);
9289b1176b0SAnna Thomas // If there is only one exiting edge in the loop, it is always profitable to
9299b1176b0SAnna Thomas // predicate the loop.
9309b1176b0SAnna Thomas if (ExitEdges.size() == 1)
9319b1176b0SAnna Thomas return true;
9329b1176b0SAnna Thomas
9339b1176b0SAnna Thomas // Calculate the exiting probabilities of all exiting edges from the loop,
9349b1176b0SAnna Thomas // starting with the LatchExitProbability.
9359b1176b0SAnna Thomas // Heuristic for profitability: If any of the exiting blocks' probability of
9369b1176b0SAnna Thomas // exiting the loop is larger than exiting through the latch block, it's not
9379b1176b0SAnna Thomas // profitable to predicate the loop.
9389b1176b0SAnna Thomas auto *LatchBlock = L->getLoopLatch();
9399b1176b0SAnna Thomas assert(LatchBlock && "Should have a single latch at this point!");
9409b1176b0SAnna Thomas auto *LatchTerm = LatchBlock->getTerminator();
9419b1176b0SAnna Thomas assert(LatchTerm->getNumSuccessors() == 2 &&
9429b1176b0SAnna Thomas "expected to be an exiting block with 2 succs!");
9439b1176b0SAnna Thomas unsigned LatchBrExitIdx =
9449b1176b0SAnna Thomas LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
9459403514eSAnna Thomas // We compute branch probabilities without BPI. We do not rely on BPI since
9469403514eSAnna Thomas // Loop predication is usually run in an LPM and BPI is only preserved
9479403514eSAnna Thomas // lossily within loop pass managers, while BPI has an inherent notion of
9489403514eSAnna Thomas // being complete for an entire function.
9499403514eSAnna Thomas
9509403514eSAnna Thomas // If the latch exits into a deoptimize or an unreachable block, do not
9519403514eSAnna Thomas // predicate on that latch check.
9529403514eSAnna Thomas auto *LatchExitBlock = LatchTerm->getSuccessor(LatchBrExitIdx);
9539403514eSAnna Thomas if (isa<UnreachableInst>(LatchTerm) ||
9549403514eSAnna Thomas LatchExitBlock->getTerminatingDeoptimizeCall())
9559403514eSAnna Thomas return false;
9569403514eSAnna Thomas
9579403514eSAnna Thomas auto IsValidProfileData = [](MDNode *ProfileData, const Instruction *Term) {
9589403514eSAnna Thomas if (!ProfileData || !ProfileData->getOperand(0))
9599403514eSAnna Thomas return false;
9609403514eSAnna Thomas if (MDString *MDS = dyn_cast<MDString>(ProfileData->getOperand(0)))
9619403514eSAnna Thomas if (!MDS->getString().equals("branch_weights"))
9629403514eSAnna Thomas return false;
9639403514eSAnna Thomas if (ProfileData->getNumOperands() != 1 + Term->getNumSuccessors())
9649403514eSAnna Thomas return false;
9659403514eSAnna Thomas return true;
9669403514eSAnna Thomas };
9679403514eSAnna Thomas MDNode *LatchProfileData = LatchTerm->getMetadata(LLVMContext::MD_prof);
9689403514eSAnna Thomas // Latch terminator has no valid profile data, so nothing to check
9699403514eSAnna Thomas // profitability on.
9709403514eSAnna Thomas if (!IsValidProfileData(LatchProfileData, LatchTerm))
9719403514eSAnna Thomas return true;
9729403514eSAnna Thomas
9739403514eSAnna Thomas auto ComputeBranchProbability =
9749403514eSAnna Thomas [&](const BasicBlock *ExitingBlock,
9759403514eSAnna Thomas const BasicBlock *ExitBlock) -> BranchProbability {
9769403514eSAnna Thomas auto *Term = ExitingBlock->getTerminator();
9779403514eSAnna Thomas MDNode *ProfileData = Term->getMetadata(LLVMContext::MD_prof);
9789403514eSAnna Thomas unsigned NumSucc = Term->getNumSuccessors();
9799403514eSAnna Thomas if (IsValidProfileData(ProfileData, Term)) {
9809403514eSAnna Thomas uint64_t Numerator = 0, Denominator = 0, ProfVal = 0;
9819403514eSAnna Thomas for (unsigned i = 0; i < NumSucc; i++) {
9829403514eSAnna Thomas ConstantInt *CI =
9839403514eSAnna Thomas mdconst::extract<ConstantInt>(ProfileData->getOperand(i + 1));
9849403514eSAnna Thomas ProfVal = CI->getValue().getZExtValue();
9859403514eSAnna Thomas if (Term->getSuccessor(i) == ExitBlock)
9869403514eSAnna Thomas Numerator += ProfVal;
9879403514eSAnna Thomas Denominator += ProfVal;
9889403514eSAnna Thomas }
9899403514eSAnna Thomas return BranchProbability::getBranchProbability(Numerator, Denominator);
9909403514eSAnna Thomas } else {
9919403514eSAnna Thomas assert(LatchBlock != ExitingBlock &&
9929403514eSAnna Thomas "Latch term should always have profile data!");
9939403514eSAnna Thomas // No profile data, so we choose the weight as 1/num_of_succ(Src)
9949403514eSAnna Thomas return BranchProbability::getBranchProbability(1, NumSucc);
9959403514eSAnna Thomas }
9969403514eSAnna Thomas };
9979403514eSAnna Thomas
9989b1176b0SAnna Thomas BranchProbability LatchExitProbability =
9999403514eSAnna Thomas ComputeBranchProbability(LatchBlock, LatchExitBlock);
10009b1176b0SAnna Thomas
10019b1176b0SAnna Thomas // Protect against degenerate inputs provided by the user. Providing a value
10029b1176b0SAnna Thomas // less than one, can invert the definition of profitable loop predication.
10039b1176b0SAnna Thomas float ScaleFactor = LatchExitProbabilityScale;
10049b1176b0SAnna Thomas if (ScaleFactor < 1) {
1005d34e60caSNicola Zaghen LLVM_DEBUG(
10069b1176b0SAnna Thomas dbgs()
10079b1176b0SAnna Thomas << "Ignored user setting for loop-predication-latch-probability-scale: "
10089b1176b0SAnna Thomas << LatchExitProbabilityScale << "\n");
1009d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
10109b1176b0SAnna Thomas ScaleFactor = 1.0;
10119b1176b0SAnna Thomas }
10129403514eSAnna Thomas const auto LatchProbabilityThreshold = LatchExitProbability * ScaleFactor;
10139b1176b0SAnna Thomas
10149b1176b0SAnna Thomas for (const auto &ExitEdge : ExitEdges) {
10159b1176b0SAnna Thomas BranchProbability ExitingBlockProbability =
10169403514eSAnna Thomas ComputeBranchProbability(ExitEdge.first, ExitEdge.second);
10179b1176b0SAnna Thomas // Some exiting edge has higher probability than the latch exiting edge.
10189b1176b0SAnna Thomas // No longer profitable to predicate.
10199b1176b0SAnna Thomas if (ExitingBlockProbability > LatchProbabilityThreshold)
10209b1176b0SAnna Thomas return false;
10219b1176b0SAnna Thomas }
10229403514eSAnna Thomas
10239403514eSAnna Thomas // We have concluded that the most probable way to exit from the
10249b1176b0SAnna Thomas // loop is through the latch (or there's no profile information and all
10259b1176b0SAnna Thomas // exits are equally likely).
10269b1176b0SAnna Thomas return true;
10279b1176b0SAnna Thomas }
10289b1176b0SAnna Thomas
1029ad5a84c8SPhilip Reames /// If we can (cheaply) find a widenable branch which controls entry into the
1030ad5a84c8SPhilip Reames /// loop, return it.
FindWidenableTerminatorAboveLoop(Loop * L,LoopInfo & LI)1031ad5a84c8SPhilip Reames static BranchInst *FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI) {
1032ad5a84c8SPhilip Reames // Walk back through any unconditional executed blocks and see if we can find
1033ad5a84c8SPhilip Reames // a widenable condition which seems to control execution of this loop. Note
1034ad5a84c8SPhilip Reames // that we predict that maythrow calls are likely untaken and thus that it's
1035ad5a84c8SPhilip Reames // profitable to widen a branch before a maythrow call with a condition
1036ad5a84c8SPhilip Reames // afterwards even though that may cause the slow path to run in a case where
1037ad5a84c8SPhilip Reames // it wouldn't have otherwise.
1038ad5a84c8SPhilip Reames BasicBlock *BB = L->getLoopPreheader();
1039ad5a84c8SPhilip Reames if (!BB)
1040ad5a84c8SPhilip Reames return nullptr;
1041ad5a84c8SPhilip Reames do {
1042ad5a84c8SPhilip Reames if (BasicBlock *Pred = BB->getSinglePredecessor())
1043ad5a84c8SPhilip Reames if (BB == Pred->getSingleSuccessor()) {
1044ad5a84c8SPhilip Reames BB = Pred;
1045ad5a84c8SPhilip Reames continue;
1046ad5a84c8SPhilip Reames }
1047ad5a84c8SPhilip Reames break;
1048ad5a84c8SPhilip Reames } while (true);
1049ad5a84c8SPhilip Reames
1050ad5a84c8SPhilip Reames if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1051ad5a84c8SPhilip Reames auto *Term = Pred->getTerminator();
1052ad5a84c8SPhilip Reames
1053ad5a84c8SPhilip Reames Value *Cond, *WC;
1054ad5a84c8SPhilip Reames BasicBlock *IfTrueBB, *IfFalseBB;
1055ad5a84c8SPhilip Reames if (parseWidenableBranch(Term, Cond, WC, IfTrueBB, IfFalseBB) &&
1056ad5a84c8SPhilip Reames IfTrueBB == BB)
1057ad5a84c8SPhilip Reames return cast<BranchInst>(Term);
1058ad5a84c8SPhilip Reames }
1059ad5a84c8SPhilip Reames return nullptr;
1060ad5a84c8SPhilip Reames }
1061ad5a84c8SPhilip Reames
1062ad5a84c8SPhilip Reames /// Return the minimum of all analyzeable exit counts. This is an upper bound
1063ad5a84c8SPhilip Reames /// on the actual exit count. If there are not at least two analyzeable exits,
1064ad5a84c8SPhilip Reames /// returns SCEVCouldNotCompute.
getMinAnalyzeableBackedgeTakenCount(ScalarEvolution & SE,DominatorTree & DT,Loop * L)1065ad5a84c8SPhilip Reames static const SCEV *getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE,
1066ad5a84c8SPhilip Reames DominatorTree &DT,
1067ad5a84c8SPhilip Reames Loop *L) {
1068ad5a84c8SPhilip Reames SmallVector<BasicBlock *, 16> ExitingBlocks;
1069ad5a84c8SPhilip Reames L->getExitingBlocks(ExitingBlocks);
1070ad5a84c8SPhilip Reames
1071ad5a84c8SPhilip Reames SmallVector<const SCEV *, 4> ExitCounts;
1072ad5a84c8SPhilip Reames for (BasicBlock *ExitingBB : ExitingBlocks) {
1073ad5a84c8SPhilip Reames const SCEV *ExitCount = SE.getExitCount(L, ExitingBB);
1074ad5a84c8SPhilip Reames if (isa<SCEVCouldNotCompute>(ExitCount))
1075ad5a84c8SPhilip Reames continue;
1076ad5a84c8SPhilip Reames assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
1077ad5a84c8SPhilip Reames "We should only have known counts for exiting blocks that "
1078ad5a84c8SPhilip Reames "dominate latch!");
1079ad5a84c8SPhilip Reames ExitCounts.push_back(ExitCount);
1080ad5a84c8SPhilip Reames }
1081ad5a84c8SPhilip Reames if (ExitCounts.size() < 2)
1082ad5a84c8SPhilip Reames return SE.getCouldNotCompute();
1083ad5a84c8SPhilip Reames return SE.getUMinFromMismatchedTypes(ExitCounts);
1084ad5a84c8SPhilip Reames }
1085ad5a84c8SPhilip Reames
1086ad5a84c8SPhilip Reames /// This implements an analogous, but entirely distinct transform from the main
1087ad5a84c8SPhilip Reames /// loop predication transform. This one is phrased in terms of using a
1088ad5a84c8SPhilip Reames /// widenable branch *outside* the loop to allow us to simplify loop exits in a
1089ad5a84c8SPhilip Reames /// following loop. This is close in spirit to the IndVarSimplify transform
1090ad5a84c8SPhilip Reames /// of the same name, but is materially different widening loosens legality
1091ad5a84c8SPhilip Reames /// sharply.
predicateLoopExits(Loop * L,SCEVExpander & Rewriter)1092ad5a84c8SPhilip Reames bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1093ad5a84c8SPhilip Reames // The transformation performed here aims to widen a widenable condition
1094ad5a84c8SPhilip Reames // above the loop such that all analyzeable exit leading to deopt are dead.
1095ad5a84c8SPhilip Reames // It assumes that the latch is the dominant exit for profitability and that
1096ad5a84c8SPhilip Reames // exits branching to deoptimizing blocks are rarely taken. It relies on the
1097ad5a84c8SPhilip Reames // semantics of widenable expressions for legality. (i.e. being able to fall
1098ad5a84c8SPhilip Reames // down the widenable path spuriously allows us to ignore exit order,
1099ad5a84c8SPhilip Reames // unanalyzeable exits, side effects, exceptional exits, and other challenges
1100ad5a84c8SPhilip Reames // which restrict the applicability of the non-WC based version of this
1101ad5a84c8SPhilip Reames // transform in IndVarSimplify.)
1102ad5a84c8SPhilip Reames //
1103ad5a84c8SPhilip Reames // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may
1104ad5a84c8SPhilip Reames // imply flags on the expression being hoisted and inserting new uses (flags
1105ad5a84c8SPhilip Reames // are only correct for current uses). The result is that we may be
1106ad5a84c8SPhilip Reames // inserting a branch on the value which can be either poison or undef. In
1107ad5a84c8SPhilip Reames // this case, the branch can legally go either way; we just need to avoid
1108ad5a84c8SPhilip Reames // introducing UB. This is achieved through the use of the freeze
1109ad5a84c8SPhilip Reames // instruction.
1110ad5a84c8SPhilip Reames
1111ad5a84c8SPhilip Reames SmallVector<BasicBlock *, 16> ExitingBlocks;
1112ad5a84c8SPhilip Reames L->getExitingBlocks(ExitingBlocks);
1113ad5a84c8SPhilip Reames
1114ad5a84c8SPhilip Reames if (ExitingBlocks.empty())
1115ad5a84c8SPhilip Reames return false; // Nothing to do.
1116ad5a84c8SPhilip Reames
1117ad5a84c8SPhilip Reames auto *Latch = L->getLoopLatch();
1118ad5a84c8SPhilip Reames if (!Latch)
1119ad5a84c8SPhilip Reames return false;
1120ad5a84c8SPhilip Reames
1121ad5a84c8SPhilip Reames auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI);
1122ad5a84c8SPhilip Reames if (!WidenableBR)
1123ad5a84c8SPhilip Reames return false;
1124ad5a84c8SPhilip Reames
1125ad5a84c8SPhilip Reames const SCEV *LatchEC = SE->getExitCount(L, Latch);
1126ad5a84c8SPhilip Reames if (isa<SCEVCouldNotCompute>(LatchEC))
1127ad5a84c8SPhilip Reames return false; // profitability - want hot exit in analyzeable set
1128ad5a84c8SPhilip Reames
1129dfb7a909SPhilip Reames // At this point, we have found an analyzeable latch, and a widenable
1130dfb7a909SPhilip Reames // condition above the loop. If we have a widenable exit within the loop
1131dfb7a909SPhilip Reames // (for which we can't compute exit counts), drop the ability to further
1132dfb7a909SPhilip Reames // widen so that we gain ability to analyze it's exit count and perform this
1133dfb7a909SPhilip Reames // transform. TODO: It'd be nice to know for sure the exit became
1134dfb7a909SPhilip Reames // analyzeable after dropping widenability.
11350e362883SDaniil Suchkov bool ChangedLoop = false;
1136dfb7a909SPhilip Reames
1137dfb7a909SPhilip Reames for (auto *ExitingBB : ExitingBlocks) {
1138dfb7a909SPhilip Reames if (LI->getLoopFor(ExitingBB) != L)
1139dfb7a909SPhilip Reames continue;
1140dfb7a909SPhilip Reames
1141dfb7a909SPhilip Reames auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1142dfb7a909SPhilip Reames if (!BI)
1143dfb7a909SPhilip Reames continue;
1144dfb7a909SPhilip Reames
1145dfb7a909SPhilip Reames Use *Cond, *WC;
1146dfb7a909SPhilip Reames BasicBlock *IfTrueBB, *IfFalseBB;
1147dfb7a909SPhilip Reames if (parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB) &&
1148dfb7a909SPhilip Reames L->contains(IfTrueBB)) {
1149dfb7a909SPhilip Reames WC->set(ConstantInt::getTrue(IfTrueBB->getContext()));
11500e362883SDaniil Suchkov ChangedLoop = true;
1151dfb7a909SPhilip Reames }
1152dfb7a909SPhilip Reames }
11530e362883SDaniil Suchkov if (ChangedLoop)
1154dfb7a909SPhilip Reames SE->forgetLoop(L);
1155dfb7a909SPhilip Reames
1156ad5a84c8SPhilip Reames // The use of umin(all analyzeable exits) instead of latch is subtle, but
1157ad5a84c8SPhilip Reames // important for profitability. We may have a loop which hasn't been fully
1158ad5a84c8SPhilip Reames // canonicalized just yet. If the exit we chose to widen is provably never
1159ad5a84c8SPhilip Reames // taken, we want the widened form to *also* be provably never taken. We
1160ad5a84c8SPhilip Reames // can't guarantee this as a current unanalyzeable exit may later become
1161ad5a84c8SPhilip Reames // analyzeable, but we can at least avoid the obvious cases.
1162ad5a84c8SPhilip Reames const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L);
1163ad5a84c8SPhilip Reames if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() ||
1164ad5a84c8SPhilip Reames !SE->isLoopInvariant(MinEC, L) ||
1165dcf4b733SNikita Popov !Rewriter.isSafeToExpandAt(MinEC, WidenableBR))
11660e362883SDaniil Suchkov return ChangedLoop;
1167ad5a84c8SPhilip Reames
1168ad5a84c8SPhilip Reames // Subtlety: We need to avoid inserting additional uses of the WC. We know
1169ad5a84c8SPhilip Reames // that it can only have one transitive use at the moment, and thus moving
1170ad5a84c8SPhilip Reames // that use to just before the branch and inserting code before it and then
1171ad5a84c8SPhilip Reames // modifying the operand is legal.
1172ad5a84c8SPhilip Reames auto *IP = cast<Instruction>(WidenableBR->getCondition());
11730e362883SDaniil Suchkov // Here we unconditionally modify the IR, so after this point we should return
11740e362883SDaniil Suchkov // only `true`!
1175ad5a84c8SPhilip Reames IP->moveBefore(WidenableBR);
1176f661ce20SAnna Thomas if (MSSAU)
1177f661ce20SAnna Thomas if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(IP))
1178f661ce20SAnna Thomas MSSAU->moveToPlace(MUD, WidenableBR->getParent(),
1179f661ce20SAnna Thomas MemorySSA::BeforeTerminator);
1180ad5a84c8SPhilip Reames Rewriter.setInsertPoint(IP);
1181ad5a84c8SPhilip Reames IRBuilder<> B(IP);
1182ad5a84c8SPhilip Reames
11830e362883SDaniil Suchkov bool InvalidateLoop = false;
1184ad5a84c8SPhilip Reames Value *MinECV = nullptr; // lazily generated if needed
1185ad5a84c8SPhilip Reames for (BasicBlock *ExitingBB : ExitingBlocks) {
1186ad5a84c8SPhilip Reames // If our exiting block exits multiple loops, we can only rewrite the
1187ad5a84c8SPhilip Reames // innermost one. Otherwise, we're changing how many times the innermost
1188ad5a84c8SPhilip Reames // loop runs before it exits.
1189ad5a84c8SPhilip Reames if (LI->getLoopFor(ExitingBB) != L)
1190ad5a84c8SPhilip Reames continue;
1191ad5a84c8SPhilip Reames
1192ad5a84c8SPhilip Reames // Can't rewrite non-branch yet.
1193ad5a84c8SPhilip Reames auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1194ad5a84c8SPhilip Reames if (!BI)
1195ad5a84c8SPhilip Reames continue;
1196ad5a84c8SPhilip Reames
1197ad5a84c8SPhilip Reames // If already constant, nothing to do.
1198ad5a84c8SPhilip Reames if (isa<Constant>(BI->getCondition()))
1199ad5a84c8SPhilip Reames continue;
1200ad5a84c8SPhilip Reames
1201ad5a84c8SPhilip Reames const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1202ad5a84c8SPhilip Reames if (isa<SCEVCouldNotCompute>(ExitCount) ||
1203ad5a84c8SPhilip Reames ExitCount->getType()->isPointerTy() ||
1204dcf4b733SNikita Popov !Rewriter.isSafeToExpandAt(ExitCount, WidenableBR))
1205ad5a84c8SPhilip Reames continue;
1206ad5a84c8SPhilip Reames
1207ad5a84c8SPhilip Reames const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1208ad5a84c8SPhilip Reames BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1);
12098a4d12aeSFedor Sergeev if (!ExitBB->getPostdominatingDeoptimizeCall())
1210ad5a84c8SPhilip Reames continue;
1211ad5a84c8SPhilip Reames
12128a4d12aeSFedor Sergeev /// Here we can be fairly sure that executing this exit will most likely
12138a4d12aeSFedor Sergeev /// lead to executing llvm.experimental.deoptimize.
12148a4d12aeSFedor Sergeev /// This is a profitability heuristic, not a legality constraint.
12158a4d12aeSFedor Sergeev
1216ad5a84c8SPhilip Reames // If we found a widenable exit condition, do two things:
1217ad5a84c8SPhilip Reames // 1) fold the widened exit test into the widenable condition
1218ad5a84c8SPhilip Reames // 2) fold the branch to untaken - avoids infinite looping
1219ad5a84c8SPhilip Reames
1220ad5a84c8SPhilip Reames Value *ECV = Rewriter.expandCodeFor(ExitCount);
1221ad5a84c8SPhilip Reames if (!MinECV)
1222ad5a84c8SPhilip Reames MinECV = Rewriter.expandCodeFor(MinEC);
1223ad5a84c8SPhilip Reames Value *RHS = MinECV;
1224ad5a84c8SPhilip Reames if (ECV->getType() != RHS->getType()) {
1225ad5a84c8SPhilip Reames Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1226ad5a84c8SPhilip Reames ECV = B.CreateZExt(ECV, WiderTy);
1227ad5a84c8SPhilip Reames RHS = B.CreateZExt(RHS, WiderTy);
1228ad5a84c8SPhilip Reames }
1229ad5a84c8SPhilip Reames assert(!Latch || DT->dominates(ExitingBB, Latch));
1230ad5a84c8SPhilip Reames Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS);
1231ad5a84c8SPhilip Reames // Freeze poison or undef to an arbitrary bit pattern to ensure we can
1232ad5a84c8SPhilip Reames // branch without introducing UB. See NOTE ON POISON/UNDEF above for
1233ad5a84c8SPhilip Reames // context.
1234ad5a84c8SPhilip Reames NewCond = B.CreateFreeze(NewCond);
1235ad5a84c8SPhilip Reames
123670c68a6bSPhilip Reames widenWidenableBranch(WidenableBR, NewCond);
1237ad5a84c8SPhilip Reames
1238ad5a84c8SPhilip Reames Value *OldCond = BI->getCondition();
1239ad5a84c8SPhilip Reames BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue));
12400e362883SDaniil Suchkov InvalidateLoop = true;
1241ad5a84c8SPhilip Reames }
1242ad5a84c8SPhilip Reames
12430e362883SDaniil Suchkov if (InvalidateLoop)
1244ad5a84c8SPhilip Reames // We just mutated a bunch of loop exits changing there exit counts
1245ad5a84c8SPhilip Reames // widely. We need to force recomputation of the exit counts given these
1246ad5a84c8SPhilip Reames // changes. Note that all of the inserted exits are never taken, and
1247ad5a84c8SPhilip Reames // should be removed next time the CFG is modified.
1248ad5a84c8SPhilip Reames SE->forgetLoop(L);
12490e362883SDaniil Suchkov
12500e362883SDaniil Suchkov // Always return `true` since we have moved the WidenableBR's condition.
12510e362883SDaniil Suchkov return true;
1252ad5a84c8SPhilip Reames }
1253ad5a84c8SPhilip Reames
runOnLoop(Loop * Loop)12548fb3d57eSArtur Pilipenko bool LoopPredication::runOnLoop(Loop *Loop) {
12558fb3d57eSArtur Pilipenko L = Loop;
12568fb3d57eSArtur Pilipenko
1257d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Analyzing ");
1258d34e60caSNicola Zaghen LLVM_DEBUG(L->dump());
12598fb3d57eSArtur Pilipenko
12608fb3d57eSArtur Pilipenko Module *M = L->getHeader()->getModule();
12618fb3d57eSArtur Pilipenko
12628fb3d57eSArtur Pilipenko // There is nothing to do if the module doesn't use guards
12638fb3d57eSArtur Pilipenko auto *GuardDecl =
12648fb3d57eSArtur Pilipenko M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
1265feb475f4SMax Kazantsev bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
1266feb475f4SMax Kazantsev auto *WCDecl = M->getFunction(
1267feb475f4SMax Kazantsev Intrinsic::getName(Intrinsic::experimental_widenable_condition));
1268feb475f4SMax Kazantsev bool HasWidenableConditions =
1269feb475f4SMax Kazantsev PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
1270feb475f4SMax Kazantsev if (!HasIntrinsicGuards && !HasWidenableConditions)
12718fb3d57eSArtur Pilipenko return false;
12728fb3d57eSArtur Pilipenko
12738fb3d57eSArtur Pilipenko DL = &M->getDataLayout();
12748fb3d57eSArtur Pilipenko
12758fb3d57eSArtur Pilipenko Preheader = L->getLoopPreheader();
12768fb3d57eSArtur Pilipenko if (!Preheader)
12778fb3d57eSArtur Pilipenko return false;
12788fb3d57eSArtur Pilipenko
1279889dc1e3SArtur Pilipenko auto LatchCheckOpt = parseLoopLatchICmp();
1280889dc1e3SArtur Pilipenko if (!LatchCheckOpt)
1281889dc1e3SArtur Pilipenko return false;
1282889dc1e3SArtur Pilipenko LatchCheck = *LatchCheckOpt;
1283889dc1e3SArtur Pilipenko
1284d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Latch check:\n");
1285d34e60caSNicola Zaghen LLVM_DEBUG(LatchCheck.dump());
128668797214SAnna Thomas
12879b1176b0SAnna Thomas if (!isLoopProfitableToPredicate()) {
1288d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
12899b1176b0SAnna Thomas return false;
12909b1176b0SAnna Thomas }
12918fb3d57eSArtur Pilipenko // Collect all the guards into a vector and process later, so as not
12928fb3d57eSArtur Pilipenko // to invalidate the instruction iterator.
12938fb3d57eSArtur Pilipenko SmallVector<IntrinsicInst *, 4> Guards;
1294feb475f4SMax Kazantsev SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
1295feb475f4SMax Kazantsev for (const auto BB : L->blocks()) {
12968fb3d57eSArtur Pilipenko for (auto &I : *BB)
129728298e96SMax Kazantsev if (isGuard(&I))
129828298e96SMax Kazantsev Guards.push_back(cast<IntrinsicInst>(&I));
1299feb475f4SMax Kazantsev if (PredicateWidenableBranchGuards &&
1300feb475f4SMax Kazantsev isGuardAsWidenableBranch(BB->getTerminator()))
1301feb475f4SMax Kazantsev GuardsAsWidenableBranches.push_back(
1302feb475f4SMax Kazantsev cast<BranchInst>(BB->getTerminator()));
1303feb475f4SMax Kazantsev }
13048fb3d57eSArtur Pilipenko
13058fb3d57eSArtur Pilipenko SCEVExpander Expander(*SE, *DL, "loop-predication");
13068fb3d57eSArtur Pilipenko bool Changed = false;
13078fb3d57eSArtur Pilipenko for (auto *Guard : Guards)
13088fb3d57eSArtur Pilipenko Changed |= widenGuardConditions(Guard, Expander);
1309feb475f4SMax Kazantsev for (auto *Guard : GuardsAsWidenableBranches)
1310feb475f4SMax Kazantsev Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
1311ad5a84c8SPhilip Reames Changed |= predicateLoopExits(L, Expander);
131255bdb140SAnna Thomas
131355bdb140SAnna Thomas if (MSSAU && VerifyMemorySSA)
131455bdb140SAnna Thomas MSSAU->getMemorySSA()->verifyMemorySSA();
13158fb3d57eSArtur Pilipenko return Changed;
13168fb3d57eSArtur Pilipenko }
1317