2017-10-25 05:24:53 +08:00
|
|
|
//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
|
2015-01-16 09:03:22 +08:00
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2015-01-16 09:03:22 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
2017-10-25 05:24:53 +08:00
|
|
|
//
|
2015-01-16 09:03:22 +08:00
|
|
|
// The InductiveRangeCheckElimination pass splits a loop's iteration space into
|
|
|
|
// three disjoint ranges. It does that in a way such that the loop running in
|
|
|
|
// the middle loop provably does not need range checks. As an example, it will
|
|
|
|
// convert
|
|
|
|
//
|
|
|
|
// len = < known positive >
|
|
|
|
// for (i = 0; i < n; i++) {
|
|
|
|
// if (0 <= i && i < len) {
|
|
|
|
// do_something();
|
|
|
|
// } else {
|
|
|
|
// throw_out_of_bounds();
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// to
|
|
|
|
//
|
|
|
|
// len = < known positive >
|
|
|
|
// limit = smin(n, len)
|
|
|
|
// // no first segment
|
|
|
|
// for (i = 0; i < limit; i++) {
|
|
|
|
// if (0 <= i && i < len) { // this check is fully redundant
|
|
|
|
// do_something();
|
|
|
|
// } else {
|
|
|
|
// throw_out_of_bounds();
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// for (i = limit; i < n; i++) {
|
|
|
|
// if (0 <= i && i < len) {
|
|
|
|
// do_something();
|
|
|
|
// } else {
|
|
|
|
// throw_out_of_bounds();
|
|
|
|
// }
|
|
|
|
// }
|
2017-10-25 05:24:53 +08:00
|
|
|
//
|
2015-01-16 09:03:22 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/ADT/APInt.h"
|
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
|
|
|
#include "llvm/ADT/None.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/ADT/Optional.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/ADT/SmallPtrSet.h"
|
|
|
|
#include "llvm/ADT/SmallVector.h"
|
|
|
|
#include "llvm/ADT/StringRef.h"
|
|
|
|
#include "llvm/ADT/Twine.h"
|
2015-01-28 05:38:12 +08:00
|
|
|
#include "llvm/Analysis/BranchProbabilityInfo.h"
|
2018-03-15 19:01:19 +08:00
|
|
|
#include "llvm/Analysis/LoopAnalysisManager.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
|
|
|
#include "llvm/Analysis/LoopPass.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolution.h"
|
2020-01-05 02:44:38 +08:00
|
|
|
#include "llvm/Analysis/ScalarEvolutionExpander.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/IR/BasicBlock.h"
|
|
|
|
#include "llvm/IR/CFG.h"
|
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
#include "llvm/IR/DerivedTypes.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/IR/Dominators.h"
|
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/IRBuilder.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/IR/InstrTypes.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/IR/Instructions.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/IR/Metadata.h"
|
|
|
|
#include "llvm/IR/Module.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/IR/PatternMatch.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/IR/Type.h"
|
|
|
|
#include "llvm/IR/Use.h"
|
|
|
|
#include "llvm/IR/User.h"
|
|
|
|
#include "llvm/IR/Value.h"
|
Sink all InitializePasses.h includes
This file lists every pass in LLVM, and is included by Pass.h, which is
very popular. Every time we add, remove, or rename a pass in LLVM, it
caused lots of recompilation.
I found this fact by looking at this table, which is sorted by the
number of times a file was changed over the last 100,000 git commits
multiplied by the number of object files that depend on it in the
current checkout:
recompiles touches affected_files header
342380 95 3604 llvm/include/llvm/ADT/STLExtras.h
314730 234 1345 llvm/include/llvm/InitializePasses.h
307036 118 2602 llvm/include/llvm/ADT/APInt.h
213049 59 3611 llvm/include/llvm/Support/MathExtras.h
170422 47 3626 llvm/include/llvm/Support/Compiler.h
162225 45 3605 llvm/include/llvm/ADT/Optional.h
158319 63 2513 llvm/include/llvm/ADT/Triple.h
140322 39 3598 llvm/include/llvm/ADT/StringRef.h
137647 59 2333 llvm/include/llvm/Support/Error.h
131619 73 1803 llvm/include/llvm/Support/FileSystem.h
Before this change, touching InitializePasses.h would cause 1345 files
to recompile. After this change, touching it only causes 550 compiles in
an incremental rebuild.
Reviewers: bkramer, asbirlea, bollu, jdoerfert
Differential Revision: https://reviews.llvm.org/D70211
2019-11-14 05:15:01 +08:00
|
|
|
#include "llvm/InitializePasses.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Pass.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/Support/BranchProbability.h"
|
|
|
|
#include "llvm/Support/Casting.h"
|
|
|
|
#include "llvm/Support/CommandLine.h"
|
|
|
|
#include "llvm/Support/Compiler.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2015-01-16 09:03:22 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
|
|
|
#include "llvm/Transforms/Utils/Cloning.h"
|
2016-08-06 08:01:56 +08:00
|
|
|
#include "llvm/Transforms/Utils/LoopSimplify.h"
|
2017-06-06 19:49:48 +08:00
|
|
|
#include "llvm/Transforms/Utils/LoopUtils.h"
|
2017-10-25 05:24:53 +08:00
|
|
|
#include "llvm/Transforms/Utils/ValueMapper.h"
|
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <iterator>
|
|
|
|
#include <limits>
|
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
using namespace llvm;
|
2017-10-25 05:24:53 +08:00
|
|
|
using namespace llvm::PatternMatch;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-07 01:51:54 +08:00
|
|
|
static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
|
|
|
|
cl::init(64));
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-07 01:51:54 +08:00
|
|
|
static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
|
|
|
|
cl::init(false));
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-03-17 09:40:22 +08:00
|
|
|
static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
|
|
|
|
cl::init(false));
|
|
|
|
|
2015-02-26 16:56:04 +08:00
|
|
|
static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
|
|
|
|
cl::Hidden, cl::init(10));
|
|
|
|
|
2016-07-22 08:40:56 +08:00
|
|
|
static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
|
|
|
|
cl::Hidden, cl::init(false));
|
|
|
|
|
2017-10-04 14:53:22 +08:00
|
|
|
static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
|
2017-10-25 14:47:39 +08:00
|
|
|
cl::Hidden, cl::init(true));
|
2017-10-04 14:53:22 +08:00
|
|
|
|
2019-01-23 15:20:56 +08:00
|
|
|
static cl::opt<bool> AllowNarrowLatchCondition(
|
2019-01-30 19:25:12 +08:00
|
|
|
"irce-allow-narrow-latch", cl::Hidden, cl::init(true),
|
2019-01-23 15:20:56 +08:00
|
|
|
cl::desc("If set to true, IRCE may eliminate wide range checks in loops "
|
|
|
|
"with narrow latch condition."));
|
|
|
|
|
2016-08-14 09:04:36 +08:00
|
|
|
static const char *ClonedLoopTag = "irce.loop.clone";
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
#define DEBUG_TYPE "irce"
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
|
|
|
/// An inductive range check is conditional branch in a loop with
|
|
|
|
///
|
|
|
|
/// 1. a very cold successor (i.e. the branch jumps to that successor very
|
|
|
|
/// rarely)
|
|
|
|
///
|
|
|
|
/// and
|
|
|
|
///
|
2015-03-17 08:42:13 +08:00
|
|
|
/// 2. a condition that is provably true for some contiguous range of values
|
|
|
|
/// taken by the containing loop's induction variable.
|
2015-01-16 09:03:22 +08:00
|
|
|
///
|
|
|
|
class InductiveRangeCheck {
|
2015-03-17 08:42:13 +08:00
|
|
|
|
2017-10-31 14:19:05 +08:00
|
|
|
const SCEV *Begin = nullptr;
|
|
|
|
const SCEV *Step = nullptr;
|
|
|
|
const SCEV *End = nullptr;
|
2016-05-26 09:50:18 +08:00
|
|
|
Use *CheckUse = nullptr;
|
2017-10-25 14:47:39 +08:00
|
|
|
bool IsSigned = true;
|
2015-03-17 08:42:13 +08:00
|
|
|
|
2019-01-15 18:48:45 +08:00
|
|
|
static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
|
|
|
|
Value *&Index, Value *&Length,
|
|
|
|
bool &IsSigned);
|
2015-03-17 08:42:13 +08:00
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
static void
|
|
|
|
extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
|
|
|
|
SmallVectorImpl<InductiveRangeCheck> &Checks,
|
|
|
|
SmallPtrSetImpl<Value *> &Visited);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
public:
|
2017-10-31 14:19:05 +08:00
|
|
|
const SCEV *getBegin() const { return Begin; }
|
|
|
|
const SCEV *getStep() const { return Step; }
|
|
|
|
const SCEV *getEnd() const { return End; }
|
2017-10-25 14:47:39 +08:00
|
|
|
bool isSigned() const { return IsSigned; }
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
void print(raw_ostream &OS) const {
|
|
|
|
OS << "InductiveRangeCheck:\n";
|
2017-10-31 14:19:05 +08:00
|
|
|
OS << " Begin: ";
|
|
|
|
Begin->print(OS);
|
|
|
|
OS << " Step: ";
|
|
|
|
Step->print(OS);
|
|
|
|
OS << " End: ";
|
2018-01-12 18:00:26 +08:00
|
|
|
End->print(OS);
|
2016-05-24 06:16:45 +08:00
|
|
|
OS << "\n CheckUse: ";
|
|
|
|
getCheckUse()->getUser()->print(OS);
|
|
|
|
OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-08-18 23:55:49 +08:00
|
|
|
LLVM_DUMP_METHOD
|
2015-01-16 09:03:22 +08:00
|
|
|
void dump() {
|
|
|
|
print(dbgs());
|
|
|
|
}
|
|
|
|
|
2016-05-24 06:16:45 +08:00
|
|
|
Use *getCheckUse() const { return CheckUse; }
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-01-22 17:32:02 +08:00
|
|
|
/// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
|
2018-01-15 13:44:43 +08:00
|
|
|
/// R.getEnd() le R.getBegin(), then R denotes the empty range.
|
2015-01-22 17:32:02 +08:00
|
|
|
|
|
|
|
class Range {
|
2015-02-22 06:07:32 +08:00
|
|
|
const SCEV *Begin;
|
|
|
|
const SCEV *End;
|
2015-01-22 17:32:02 +08:00
|
|
|
|
|
|
|
public:
|
2015-02-22 06:07:32 +08:00
|
|
|
Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
|
2015-01-22 17:32:02 +08:00
|
|
|
assert(Begin->getType() == End->getType() && "ill-typed range!");
|
|
|
|
}
|
|
|
|
|
|
|
|
Type *getType() const { return Begin->getType(); }
|
2015-02-22 06:07:32 +08:00
|
|
|
const SCEV *getBegin() const { return Begin; }
|
|
|
|
const SCEV *getEnd() const { return End; }
|
2017-10-25 14:10:02 +08:00
|
|
|
bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
|
|
|
|
if (Begin == End)
|
|
|
|
return true;
|
|
|
|
if (IsSigned)
|
|
|
|
return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
|
|
|
|
else
|
|
|
|
return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
|
|
|
|
}
|
2015-01-22 17:32:02 +08:00
|
|
|
};
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
/// This is the value the condition of the branch needs to evaluate to for the
|
|
|
|
/// branch to take the hot successor (see (1) above).
|
|
|
|
bool getPassingDirection() { return true; }
|
|
|
|
|
2015-02-22 06:20:22 +08:00
|
|
|
/// Computes a range for the induction variable (IndVar) in which the range
|
|
|
|
/// check is redundant and can be constant-folded away. The induction
|
|
|
|
/// variable is not required to be the canonical {0,+,1} induction variable.
|
2015-01-16 09:03:22 +08:00
|
|
|
Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
const SCEVAddRecExpr *IndVar,
|
|
|
|
bool IsLatchSigned) const;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
/// Parse out a set of inductive range checks from \p BI and append them to \p
|
|
|
|
/// Checks.
|
|
|
|
///
|
|
|
|
/// NB! There may be conditions feeding into \p BI that aren't inductive range
|
|
|
|
/// checks, and hence don't end up in \p Checks.
|
|
|
|
static void
|
|
|
|
extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
|
2018-03-15 19:01:19 +08:00
|
|
|
BranchProbabilityInfo *BPI,
|
2016-05-26 08:09:02 +08:00
|
|
|
SmallVectorImpl<InductiveRangeCheck> &Checks);
|
2015-01-16 09:03:22 +08:00
|
|
|
};
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
class InductiveRangeCheckElimination {
|
|
|
|
ScalarEvolution &SE;
|
|
|
|
BranchProbabilityInfo *BPI;
|
|
|
|
DominatorTree &DT;
|
|
|
|
LoopInfo &LI;
|
|
|
|
|
|
|
|
public:
|
|
|
|
InductiveRangeCheckElimination(ScalarEvolution &SE,
|
|
|
|
BranchProbabilityInfo *BPI, DominatorTree &DT,
|
|
|
|
LoopInfo &LI)
|
|
|
|
: SE(SE), BPI(BPI), DT(DT), LI(LI) {}
|
|
|
|
|
|
|
|
bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
|
|
|
|
};
|
|
|
|
|
|
|
|
class IRCELegacyPass : public LoopPass {
|
2015-01-16 09:03:22 +08:00
|
|
|
public:
|
|
|
|
static char ID;
|
2017-10-25 05:24:53 +08:00
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
IRCELegacyPass() : LoopPass(ID) {
|
|
|
|
initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry());
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
2015-07-16 06:48:29 +08:00
|
|
|
AU.addRequired<BranchProbabilityInfoWrapperPass>();
|
[LPM] Factor all of the loop analysis usage updates into a common helper
routine.
We were getting this wrong in small ways and generally being very
inconsistent about it across loop passes. Instead, let's have a common
place where we do this. One minor downside is that this will require
some analyses like SCEV in more places than they are strictly needed.
However, this seems benign as these analyses are complete no-ops, and
without this consistency we can in many cases end up with the legacy
pass manager scheduling deciding to split up a loop pass pipeline in
order to run the function analysis half-way through. It is very, very
annoying to fix these without just being very pedantic across the board.
The only loop passes I've not updated here are ones that use
AU.setPreservesAll() such as IVUsers (an analysis) and the pass printer.
They seemed less relevant.
With this patch, almost all of the problems in PR24804 around loop pass
pipelines are fixed. The one remaining issue is that we run simplify-cfg
and instcombine in the middle of the loop pass pipeline. We've recently
added some loop variants of these passes that would seem substantially
cleaner to use, but this at least gets us much closer to the previous
state. Notably, the seven loop pass managers is down to three.
I've not updated the loop passes using LoopAccessAnalysis because that
analysis hasn't been fully wired into LoopSimplify/LCSSA, and it isn't
clear that those transforms want to support those forms anyways. They
all run late anyways, so this is harmless. Similarly, LSR is left alone
because it already carefully manages its forms and doesn't need to get
fused into a single loop pass manager with a bunch of other loop passes.
LoopReroll didn't use loop simplified form previously, and I've updated
the test case to match the trivially different output.
Finally, I've also factored all the pass initialization for the passes
that use this technique as well, so that should be done regularly and
reliably.
Thanks to James for the help reviewing and thinking about this stuff,
and Ben for help thinking about it as well!
Differential Revision: http://reviews.llvm.org/D17435
llvm-svn: 261316
2016-02-19 18:45:18 +08:00
|
|
|
getLoopAnalysisUsage(AU);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnLoop(Loop *L, LPPassManager &LPM) override;
|
|
|
|
};
|
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
} // end anonymous namespace
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
char IRCELegacyPass::ID = 0;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce",
|
2015-09-09 11:47:18 +08:00
|
|
|
"Inductive range check elimination", false, false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
|
[LPM] Factor all of the loop analysis usage updates into a common helper
routine.
We were getting this wrong in small ways and generally being very
inconsistent about it across loop passes. Instead, let's have a common
place where we do this. One minor downside is that this will require
some analyses like SCEV in more places than they are strictly needed.
However, this seems benign as these analyses are complete no-ops, and
without this consistency we can in many cases end up with the legacy
pass manager scheduling deciding to split up a loop pass pipeline in
order to run the function analysis half-way through. It is very, very
annoying to fix these without just being very pedantic across the board.
The only loop passes I've not updated here are ones that use
AU.setPreservesAll() such as IVUsers (an analysis) and the pass printer.
They seemed less relevant.
With this patch, almost all of the problems in PR24804 around loop pass
pipelines are fixed. The one remaining issue is that we run simplify-cfg
and instcombine in the middle of the loop pass pipeline. We've recently
added some loop variants of these passes that would seem substantially
cleaner to use, but this at least gets us much closer to the previous
state. Notably, the seven loop pass managers is down to three.
I've not updated the loop passes using LoopAccessAnalysis because that
analysis hasn't been fully wired into LoopSimplify/LCSSA, and it isn't
clear that those transforms want to support those forms anyways. They
all run late anyways, so this is harmless. Similarly, LSR is left alone
because it already carefully manages its forms and doesn't need to get
fused into a single loop pass manager with a bunch of other loop passes.
LoopReroll didn't use loop simplified form previously, and I've updated
the test case to match the trivially different output.
Finally, I've also factored all the pass initialization for the passes
that use this technique as well, so that should be done regularly and
reliably.
Thanks to James for the help reviewing and thinking about this stuff,
and Ben for help thinking about it as well!
Differential Revision: http://reviews.llvm.org/D17435
llvm-svn: 261316
2016-02-19 18:45:18 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopPass)
|
2018-03-15 19:01:19 +08:00
|
|
|
INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination",
|
|
|
|
false, false)
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-03-09 10:34:15 +08:00
|
|
|
/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
|
2019-01-15 18:48:45 +08:00
|
|
|
/// be interpreted as a range check, return false and set `Index` and `Length`
|
|
|
|
/// to `nullptr`. Otherwise set `Index` to the value being range checked, and
|
|
|
|
/// set `Length` to the upper limit `Index` is being range checked.
|
|
|
|
bool
|
2015-03-25 03:29:18 +08:00
|
|
|
InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
|
|
|
|
ScalarEvolution &SE, Value *&Index,
|
2017-10-25 14:47:39 +08:00
|
|
|
Value *&Length, bool &IsSigned) {
|
2018-04-09 14:01:22 +08:00
|
|
|
auto IsLoopInvariant = [&SE, L](Value *V) {
|
|
|
|
return SE.isLoopInvariant(SE.getSCEV(V), L);
|
2015-03-25 03:29:18 +08:00
|
|
|
};
|
2015-03-17 08:42:13 +08:00
|
|
|
|
|
|
|
ICmpInst::Predicate Pred = ICI->getPredicate();
|
|
|
|
Value *LHS = ICI->getOperand(0);
|
|
|
|
Value *RHS = ICI->getOperand(1);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
switch (Pred) {
|
|
|
|
default:
|
2019-01-15 18:48:45 +08:00
|
|
|
return false;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
case ICmpInst::ICMP_SLE:
|
|
|
|
std::swap(LHS, RHS);
|
2016-08-17 13:10:15 +08:00
|
|
|
LLVM_FALLTHROUGH;
|
2015-01-16 09:03:22 +08:00
|
|
|
case ICmpInst::ICMP_SGE:
|
2017-10-25 14:47:39 +08:00
|
|
|
IsSigned = true;
|
2015-03-17 08:42:13 +08:00
|
|
|
if (match(RHS, m_ConstantInt<0>())) {
|
|
|
|
Index = LHS;
|
2019-01-15 18:48:45 +08:00
|
|
|
return true; // Lower.
|
2015-03-17 08:42:13 +08:00
|
|
|
}
|
2019-01-15 18:48:45 +08:00
|
|
|
return false;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
case ICmpInst::ICMP_SLT:
|
|
|
|
std::swap(LHS, RHS);
|
2016-08-17 13:10:15 +08:00
|
|
|
LLVM_FALLTHROUGH;
|
2015-01-16 09:03:22 +08:00
|
|
|
case ICmpInst::ICMP_SGT:
|
2017-10-25 14:47:39 +08:00
|
|
|
IsSigned = true;
|
2015-03-17 08:42:13 +08:00
|
|
|
if (match(RHS, m_ConstantInt<-1>())) {
|
|
|
|
Index = LHS;
|
2019-01-15 18:48:45 +08:00
|
|
|
return true; // Lower.
|
2015-03-17 08:42:13 +08:00
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2018-04-09 14:01:22 +08:00
|
|
|
if (IsLoopInvariant(LHS)) {
|
2015-03-17 08:42:13 +08:00
|
|
|
Index = RHS;
|
|
|
|
Length = LHS;
|
2019-01-15 18:48:45 +08:00
|
|
|
return true; // Upper.
|
2015-03-17 08:42:13 +08:00
|
|
|
}
|
2019-01-15 18:48:45 +08:00
|
|
|
return false;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-03-17 08:42:13 +08:00
|
|
|
case ICmpInst::ICMP_ULT:
|
2015-01-16 09:03:22 +08:00
|
|
|
std::swap(LHS, RHS);
|
2016-08-17 13:10:15 +08:00
|
|
|
LLVM_FALLTHROUGH;
|
2015-01-16 09:03:22 +08:00
|
|
|
case ICmpInst::ICMP_UGT:
|
2017-10-25 14:47:39 +08:00
|
|
|
IsSigned = false;
|
2018-04-09 14:01:22 +08:00
|
|
|
if (IsLoopInvariant(LHS)) {
|
2015-03-17 08:42:13 +08:00
|
|
|
Index = RHS;
|
|
|
|
Length = LHS;
|
2019-01-15 18:48:45 +08:00
|
|
|
return true; // Both lower and upper.
|
2015-03-17 08:42:13 +08:00
|
|
|
}
|
2019-01-15 18:48:45 +08:00
|
|
|
return false;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
2015-03-17 08:42:13 +08:00
|
|
|
|
|
|
|
llvm_unreachable("default clause returns!");
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
void InductiveRangeCheck::extractRangeChecksFromCond(
|
|
|
|
Loop *L, ScalarEvolution &SE, Use &ConditionUse,
|
|
|
|
SmallVectorImpl<InductiveRangeCheck> &Checks,
|
|
|
|
SmallPtrSetImpl<Value *> &Visited) {
|
2016-05-26 08:08:24 +08:00
|
|
|
Value *Condition = ConditionUse.get();
|
2016-05-26 08:09:02 +08:00
|
|
|
if (!Visited.insert(Condition).second)
|
|
|
|
return;
|
2016-05-26 08:08:24 +08:00
|
|
|
|
2017-11-17 14:49:26 +08:00
|
|
|
// TODO: Do the same for OR, XOR, NOT etc?
|
2016-05-26 08:09:02 +08:00
|
|
|
if (match(Condition, m_And(m_Value(), m_Value()))) {
|
|
|
|
extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
|
2017-11-17 14:49:26 +08:00
|
|
|
Checks, Visited);
|
2016-05-26 08:09:02 +08:00
|
|
|
extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
|
2017-11-17 14:49:26 +08:00
|
|
|
Checks, Visited);
|
2016-05-26 08:09:02 +08:00
|
|
|
return;
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
|
|
|
|
if (!ICI)
|
|
|
|
return;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
Value *Length = nullptr, *Index;
|
2017-10-25 14:47:39 +08:00
|
|
|
bool IsSigned;
|
2019-01-15 18:48:45 +08:00
|
|
|
if (!parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned))
|
2016-05-26 08:09:02 +08:00
|
|
|
return;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:08:24 +08:00
|
|
|
const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
|
|
|
|
bool IsAffineIndex =
|
|
|
|
IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:08:24 +08:00
|
|
|
if (!IsAffineIndex)
|
2016-05-26 08:09:02 +08:00
|
|
|
return;
|
2016-05-26 08:08:24 +08:00
|
|
|
|
2018-01-12 18:00:26 +08:00
|
|
|
const SCEV *End = nullptr;
|
|
|
|
// We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
|
|
|
|
// We can potentially do much better here.
|
|
|
|
if (Length)
|
|
|
|
End = SE.getSCEV(Length);
|
|
|
|
else {
|
|
|
|
// So far we can only reach this point for Signed range check. This may
|
|
|
|
// change in future. In this case we will need to pick Unsigned max for the
|
|
|
|
// unsigned range check.
|
|
|
|
unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
|
|
|
|
const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
|
|
|
|
End = SIntMax;
|
|
|
|
}
|
|
|
|
|
2016-05-26 08:08:24 +08:00
|
|
|
InductiveRangeCheck IRC;
|
2018-01-12 18:00:26 +08:00
|
|
|
IRC.End = End;
|
2017-10-31 14:19:05 +08:00
|
|
|
IRC.Begin = IndexAddRec->getStart();
|
|
|
|
IRC.Step = IndexAddRec->getStepRecurrence(SE);
|
2016-05-26 08:08:24 +08:00
|
|
|
IRC.CheckUse = &ConditionUse;
|
2017-10-25 14:47:39 +08:00
|
|
|
IRC.IsSigned = IsSigned;
|
2016-05-26 08:09:02 +08:00
|
|
|
Checks.push_back(IRC);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
void InductiveRangeCheck::extractRangeChecksFromBranch(
|
2018-03-15 19:01:19 +08:00
|
|
|
BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
|
2016-05-26 08:09:02 +08:00
|
|
|
SmallVectorImpl<InductiveRangeCheck> &Checks) {
|
2015-01-16 09:03:22 +08:00
|
|
|
if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
|
2016-05-26 08:09:02 +08:00
|
|
|
return;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-01-28 05:38:12 +08:00
|
|
|
BranchProbability LikelyTaken(15, 16);
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
if (!SkipProfitabilityChecks && BPI &&
|
|
|
|
BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
|
2016-05-26 08:09:02 +08:00
|
|
|
return;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-05-26 08:09:02 +08:00
|
|
|
SmallPtrSet<Value *, 8> Visited;
|
|
|
|
InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
|
|
|
|
Checks, Visited);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-12-14 05:05:21 +08:00
|
|
|
// Add metadata to the loop L to disable loop optimizations. Callers need to
|
|
|
|
// confirm that optimizing loop L is not beneficial.
|
|
|
|
static void DisableAllLoopOptsOnLoop(Loop &L) {
|
|
|
|
// We do not care about any existing loopID related metadata for L, since we
|
|
|
|
// are setting all loop metadata to false.
|
|
|
|
LLVMContext &Context = L.getHeader()->getContext();
|
|
|
|
// Reserve first location for self reference to the LoopID metadata node.
|
|
|
|
MDNode *Dummy = MDNode::get(Context, {});
|
|
|
|
MDNode *DisableUnroll = MDNode::get(
|
|
|
|
Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
|
|
|
|
Metadata *FalseVal =
|
|
|
|
ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
|
|
|
|
MDNode *DisableVectorize = MDNode::get(
|
|
|
|
Context,
|
|
|
|
{MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
|
|
|
|
MDNode *DisableLICMVersioning = MDNode::get(
|
|
|
|
Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
|
|
|
|
MDNode *DisableDistribution= MDNode::get(
|
|
|
|
Context,
|
|
|
|
{MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
|
|
|
|
MDNode *NewLoopID =
|
|
|
|
MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
|
|
|
|
DisableLICMVersioning, DisableDistribution});
|
|
|
|
// Set operand 0 to refer to the loop id itself.
|
|
|
|
NewLoopID->replaceOperandWith(0, NewLoopID);
|
|
|
|
L.setLoopID(NewLoopID);
|
|
|
|
}
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
namespace {
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
// Keeps track of the structure of a loop. This is similar to llvm::Loop,
|
|
|
|
// except that it is more lightweight and can track the state of a loop through
|
|
|
|
// changing and potentially invalid IR. This structure also formalizes the
|
|
|
|
// kinds of loops we can deal with -- ones that have a single latch that is also
|
|
|
|
// an exiting block *and* have a canonical induction variable.
|
|
|
|
struct LoopStructure {
|
2017-10-25 05:24:53 +08:00
|
|
|
const char *Tag = "";
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
BasicBlock *Header = nullptr;
|
|
|
|
BasicBlock *Latch = nullptr;
|
2015-02-26 16:19:31 +08:00
|
|
|
|
|
|
|
// `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
|
|
|
|
// successor is `LatchExit', the exit block of the loop.
|
2017-10-25 05:24:53 +08:00
|
|
|
BranchInst *LatchBr = nullptr;
|
|
|
|
BasicBlock *LatchExit = nullptr;
|
|
|
|
unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2017-02-08 07:59:07 +08:00
|
|
|
// The loop represented by this instance of LoopStructure is semantically
|
|
|
|
// equivalent to:
|
|
|
|
//
|
|
|
|
// intN_ty inc = IndVarIncreasing ? 1 : -1;
|
2017-09-21 12:50:41 +08:00
|
|
|
// pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
|
2017-02-08 07:59:07 +08:00
|
|
|
//
|
2017-09-21 12:50:41 +08:00
|
|
|
// for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
|
2017-02-08 07:59:07 +08:00
|
|
|
// ... body ...
|
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
Value *IndVarBase = nullptr;
|
|
|
|
Value *IndVarStart = nullptr;
|
|
|
|
Value *IndVarStep = nullptr;
|
|
|
|
Value *LoopExitAt = nullptr;
|
|
|
|
bool IndVarIncreasing = false;
|
|
|
|
bool IsSignedPredicate = true;
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
LoopStructure() = default;
|
2015-02-26 16:19:31 +08:00
|
|
|
|
|
|
|
template <typename M> LoopStructure map(M Map) const {
|
|
|
|
LoopStructure Result;
|
|
|
|
Result.Tag = Tag;
|
|
|
|
Result.Header = cast<BasicBlock>(Map(Header));
|
|
|
|
Result.Latch = cast<BasicBlock>(Map(Latch));
|
|
|
|
Result.LatchBr = cast<BranchInst>(Map(LatchBr));
|
|
|
|
Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
|
|
|
|
Result.LatchBrExitIdx = LatchBrExitIdx;
|
2017-08-31 13:58:15 +08:00
|
|
|
Result.IndVarBase = Map(IndVarBase);
|
2015-02-26 16:19:31 +08:00
|
|
|
Result.IndVarStart = Map(IndVarStart);
|
2017-08-04 15:01:04 +08:00
|
|
|
Result.IndVarStep = Map(IndVarStep);
|
2015-02-26 16:19:31 +08:00
|
|
|
Result.LoopExitAt = Map(LoopExitAt);
|
|
|
|
Result.IndVarIncreasing = IndVarIncreasing;
|
2017-08-04 13:40:20 +08:00
|
|
|
Result.IsSignedPredicate = IsSignedPredicate;
|
2015-02-26 16:19:31 +08:00
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2015-02-26 16:56:04 +08:00
|
|
|
static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
|
2018-03-15 19:01:19 +08:00
|
|
|
BranchProbabilityInfo *BPI,
|
|
|
|
Loop &, const char *&);
|
2015-02-26 16:19:31 +08:00
|
|
|
};
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
/// This class is used to constrain loops to run within a given iteration space.
|
|
|
|
/// The algorithm this class implements is given a Loop and a range [Begin,
|
|
|
|
/// End). The algorithm then tries to break out a "main loop" out of the loop
|
|
|
|
/// it is given in a way that the "main loop" runs with the induction variable
|
|
|
|
/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
|
|
|
|
/// loops to run any remaining iterations. The pre loop runs any iterations in
|
|
|
|
/// which the induction variable is < Begin, and the post loop runs any
|
|
|
|
/// iterations in which the induction variable is >= End.
|
|
|
|
class LoopConstrainer {
|
|
|
|
// The representation of a clone of the original loop we started out with.
|
|
|
|
struct ClonedLoop {
|
|
|
|
// The cloned blocks
|
|
|
|
std::vector<BasicBlock *> Blocks;
|
|
|
|
|
|
|
|
// `Map` maps values in the clonee into values in the cloned version
|
|
|
|
ValueToValueMapTy Map;
|
|
|
|
|
|
|
|
// An instance of `LoopStructure` for the cloned loop
|
|
|
|
LoopStructure Structure;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Result of rewriting the range of a loop. See changeIterationSpaceEnd for
|
|
|
|
// more details on what these fields mean.
|
|
|
|
struct RewrittenRangeInfo {
|
2017-10-25 05:24:53 +08:00
|
|
|
BasicBlock *PseudoExit = nullptr;
|
|
|
|
BasicBlock *ExitSelector = nullptr;
|
2015-01-16 09:03:22 +08:00
|
|
|
std::vector<PHINode *> PHIValuesAtPseudoExit;
|
2017-10-25 05:24:53 +08:00
|
|
|
PHINode *IndVarEnd = nullptr;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
RewrittenRangeInfo() = default;
|
2015-01-16 09:03:22 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Calculated subranges we restrict the iteration space of the main loop to.
|
|
|
|
// See the implementation of `calculateSubRanges' for more details on how
|
2015-02-26 16:19:31 +08:00
|
|
|
// these fields are computed. `LowLimit` is None if there is no restriction
|
|
|
|
// on low end of the restricted iteration space of the main loop. `HighLimit`
|
|
|
|
// is None if there is no restriction on high end of the restricted iteration
|
|
|
|
// space of the main loop.
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
struct SubRanges {
|
2015-02-26 16:19:31 +08:00
|
|
|
Optional<const SCEV *> LowLimit;
|
|
|
|
Optional<const SCEV *> HighLimit;
|
2015-01-16 09:03:22 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Compute a safe set of limits for the main loop to run in -- effectively the
|
|
|
|
// intersection of `Range' and the iteration space of the original loop.
|
2015-01-22 16:29:18 +08:00
|
|
|
// Return None if unable to compute the set of subranges.
|
2017-08-04 13:40:20 +08:00
|
|
|
Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Clone `OriginalLoop' and return the result in CLResult. The IR after
|
|
|
|
// running `cloneLoop' is well formed except for the PHI nodes in CLResult --
|
|
|
|
// the PHI nodes say that there is an incoming edge from `OriginalPreheader`
|
|
|
|
// but there is no such edge.
|
|
|
|
void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
|
|
|
|
|
2016-08-14 09:04:46 +08:00
|
|
|
// Create the appropriate loop structure needed to describe a cloned copy of
|
|
|
|
// `Original`. The clone is described by `VM`.
|
|
|
|
Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
|
2018-03-15 19:01:19 +08:00
|
|
|
ValueToValueMapTy &VM, bool IsSubloop);
|
2016-08-14 09:04:46 +08:00
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
// Rewrite the iteration space of the loop denoted by (LS, Preheader). The
|
|
|
|
// iteration space of the rewritten loop ends at ExitLoopAt. The start of the
|
|
|
|
// iteration space is not changed. `ExitLoopAt' is assumed to be slt
|
|
|
|
// `OriginalHeaderCount'.
|
|
|
|
//
|
|
|
|
// If there are iterations left to execute, control is made to jump to
|
|
|
|
// `ContinuationBlock', otherwise they take the normal loop exit. The
|
|
|
|
// returned `RewrittenRangeInfo' object is populated as follows:
|
|
|
|
//
|
|
|
|
// .PseudoExit is a basic block that unconditionally branches to
|
|
|
|
// `ContinuationBlock'.
|
|
|
|
//
|
|
|
|
// .ExitSelector is a basic block that decides, on exit from the loop,
|
|
|
|
// whether to branch to the "true" exit or to `PseudoExit'.
|
|
|
|
//
|
|
|
|
// .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
|
|
|
|
// for each PHINode in the loop header on taking the pseudo exit.
|
|
|
|
//
|
|
|
|
// After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
|
|
|
|
// preheader because it is made to branch to the loop header only
|
|
|
|
// conditionally.
|
|
|
|
RewrittenRangeInfo
|
|
|
|
changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
|
|
|
|
Value *ExitLoopAt,
|
|
|
|
BasicBlock *ContinuationBlock) const;
|
|
|
|
|
|
|
|
// The loop denoted by `LS' has `OldPreheader' as its preheader. This
|
|
|
|
// function creates a new preheader for `LS' and returns it.
|
2015-02-26 16:19:31 +08:00
|
|
|
BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
|
|
|
|
const char *Tag) const;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// `ContinuationBlockAndPreheader' was the continuation block for some call to
|
|
|
|
// `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
|
|
|
|
// This function rewrites the PHI nodes in `LS.Header' to start with the
|
|
|
|
// correct value.
|
|
|
|
void rewriteIncomingValuesForPHIs(
|
2015-02-26 16:19:31 +08:00
|
|
|
LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
|
2015-01-16 09:03:22 +08:00
|
|
|
const LoopConstrainer::RewrittenRangeInfo &RRI) const;
|
|
|
|
|
|
|
|
// Even though we do not preserve any passes at this time, we at least need to
|
|
|
|
// keep the parent loop structure consistent. The `LPPassManager' seems to
|
|
|
|
// verify this after running a loop pass. This function adds the list of
|
2015-02-06 22:43:49 +08:00
|
|
|
// blocks denoted by BBs to this loops parent loop if required.
|
|
|
|
void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Some global state.
|
|
|
|
Function &F;
|
|
|
|
LLVMContext &Ctx;
|
|
|
|
ScalarEvolution &SE;
|
2016-08-03 03:31:54 +08:00
|
|
|
DominatorTree &DT;
|
2016-08-14 09:04:50 +08:00
|
|
|
LoopInfo &LI;
|
2018-03-15 19:01:19 +08:00
|
|
|
function_ref<void(Loop *, bool)> LPMAddNewLoop;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Information about the original loop we started out with.
|
|
|
|
Loop &OriginalLoop;
|
2017-10-25 05:24:53 +08:00
|
|
|
|
|
|
|
const SCEV *LatchTakenCount = nullptr;
|
|
|
|
BasicBlock *OriginalPreheader = nullptr;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// The preheader of the main loop. This may or may not be different from
|
|
|
|
// `OriginalPreheader'.
|
2017-10-25 05:24:53 +08:00
|
|
|
BasicBlock *MainLoopPreheader = nullptr;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// The range we need to run the main loop in.
|
|
|
|
InductiveRangeCheck::Range Range;
|
|
|
|
|
|
|
|
// The structure of the main loop (see comment at the beginning of this class
|
|
|
|
// for a definition)
|
|
|
|
LoopStructure MainLoopStructure;
|
|
|
|
|
|
|
|
public:
|
2018-03-15 19:01:19 +08:00
|
|
|
LoopConstrainer(Loop &L, LoopInfo &LI,
|
|
|
|
function_ref<void(Loop *, bool)> LPMAddNewLoop,
|
2016-08-14 09:04:46 +08:00
|
|
|
const LoopStructure &LS, ScalarEvolution &SE,
|
|
|
|
DominatorTree &DT, InductiveRangeCheck::Range R)
|
2015-02-26 16:19:31 +08:00
|
|
|
: F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
|
2018-03-15 19:01:19 +08:00
|
|
|
SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
|
|
|
|
Range(R), MainLoopStructure(LS) {}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Entry point for the algorithm. Returns true on success.
|
|
|
|
bool run();
|
|
|
|
};
|
|
|
|
|
2017-10-25 05:24:53 +08:00
|
|
|
} // end anonymous namespace
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2018-03-27 16:24:53 +08:00
|
|
|
/// Given a loop with an deccreasing induction variable, is it possible to
|
|
|
|
/// safely calculate the bounds of a new loop using the given Predicate.
|
|
|
|
static bool isSafeDecreasingBound(const SCEV *Start,
|
|
|
|
const SCEV *BoundSCEV, const SCEV *Step,
|
|
|
|
ICmpInst::Predicate Pred,
|
|
|
|
unsigned LatchBrExitIdx,
|
|
|
|
Loop *L, ScalarEvolution &SE) {
|
|
|
|
if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
|
|
|
|
Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
assert(SE.isKnownNegative(Step) && "expecting negative step");
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
|
|
|
|
<< "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
|
2018-03-27 16:24:53 +08:00
|
|
|
|
|
|
|
bool IsSigned = ICmpInst::isSigned(Pred);
|
|
|
|
// The predicate that we need to check that the induction variable lies
|
|
|
|
// within bounds.
|
|
|
|
ICmpInst::Predicate BoundPred =
|
|
|
|
IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
|
|
|
|
|
|
|
|
if (LatchBrExitIdx == 1)
|
|
|
|
return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
|
|
|
|
|
|
|
|
assert(LatchBrExitIdx == 0 &&
|
|
|
|
"LatchBrExitIdx should be either 0 or 1");
|
2018-07-31 03:41:25 +08:00
|
|
|
|
2018-03-27 16:24:53 +08:00
|
|
|
const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
|
|
|
|
unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
|
|
|
|
APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) :
|
|
|
|
APInt::getMinValue(BitWidth);
|
|
|
|
const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
|
|
|
|
|
|
|
|
const SCEV *MinusOne =
|
|
|
|
SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
|
|
|
|
|
|
|
|
return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) &&
|
|
|
|
SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit);
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
}
|
|
|
|
|
2018-03-26 17:29:42 +08:00
|
|
|
/// Given a loop with an increasing induction variable, is it possible to
|
|
|
|
/// safely calculate the bounds of a new loop using the given Predicate.
|
|
|
|
static bool isSafeIncreasingBound(const SCEV *Start,
|
|
|
|
const SCEV *BoundSCEV, const SCEV *Step,
|
|
|
|
ICmpInst::Predicate Pred,
|
|
|
|
unsigned LatchBrExitIdx,
|
|
|
|
Loop *L, ScalarEvolution &SE) {
|
|
|
|
if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
|
|
|
|
Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
|
|
|
|
return false;
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
|
|
|
|
<< "\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
|
2018-03-26 17:29:42 +08:00
|
|
|
|
|
|
|
bool IsSigned = ICmpInst::isSigned(Pred);
|
|
|
|
// The predicate that we need to check that the induction variable lies
|
|
|
|
// within bounds.
|
|
|
|
ICmpInst::Predicate BoundPred =
|
|
|
|
IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
|
|
|
|
|
|
|
|
if (LatchBrExitIdx == 1)
|
|
|
|
return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
|
|
|
|
|
|
|
|
assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
|
|
|
|
|
|
|
|
const SCEV *StepMinusOne =
|
|
|
|
SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
|
|
|
|
unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
|
2018-07-31 03:41:25 +08:00
|
|
|
APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) :
|
2018-03-26 17:29:42 +08:00
|
|
|
APInt::getMaxValue(BitWidth);
|
|
|
|
const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
|
|
|
|
|
|
|
|
return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start,
|
|
|
|
SE.getAddExpr(BoundSCEV, Step)) &&
|
|
|
|
SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit));
|
2017-08-04 15:01:04 +08:00
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
Optional<LoopStructure>
|
2017-08-04 13:40:20 +08:00
|
|
|
LoopStructure::parseLoopStructure(ScalarEvolution &SE,
|
2018-03-15 19:01:19 +08:00
|
|
|
BranchProbabilityInfo *BPI, Loop &L,
|
|
|
|
const char *&FailureReason) {
|
2016-08-14 09:04:31 +08:00
|
|
|
if (!L.isLoopSimplifyForm()) {
|
|
|
|
FailureReason = "loop not in LoopSimplify form";
|
2016-08-14 07:36:35 +08:00
|
|
|
return None;
|
2016-08-14 09:04:31 +08:00
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
BasicBlock *Latch = L.getLoopLatch();
|
2016-08-14 07:36:35 +08:00
|
|
|
assert(Latch && "Simplified loops only have one latch!");
|
|
|
|
|
2016-08-14 09:04:36 +08:00
|
|
|
if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
|
|
|
|
FailureReason = "loop has already been cloned";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
if (!L.isLoopExiting(Latch)) {
|
2015-01-16 09:03:22 +08:00
|
|
|
FailureReason = "no loop latch";
|
2015-02-26 16:19:31 +08:00
|
|
|
return None;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
BasicBlock *Header = L.getHeader();
|
|
|
|
BasicBlock *Preheader = L.getLoopPreheader();
|
2015-01-16 09:03:22 +08:00
|
|
|
if (!Preheader) {
|
|
|
|
FailureReason = "no preheader";
|
2015-02-26 16:19:31 +08:00
|
|
|
return None;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-06-24 02:03:26 +08:00
|
|
|
BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
|
2015-02-26 16:19:31 +08:00
|
|
|
if (!LatchBr || LatchBr->isUnconditional()) {
|
|
|
|
FailureReason = "latch terminator not conditional branch";
|
|
|
|
return None;
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
|
|
|
|
|
2015-02-26 16:56:04 +08:00
|
|
|
BranchProbability ExitProbability =
|
2018-03-15 19:01:19 +08:00
|
|
|
BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx)
|
|
|
|
: BranchProbability::getZero();
|
2015-02-26 16:56:04 +08:00
|
|
|
|
2016-07-22 08:40:56 +08:00
|
|
|
if (!SkipProfitabilityChecks &&
|
|
|
|
ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
|
2015-02-26 16:56:04 +08:00
|
|
|
FailureReason = "short running loop, not profitable";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
|
|
|
|
if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
|
|
|
|
FailureReason = "latch terminator branch not conditional on integral icmp";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
const SCEV *LatchCount = SE.getExitCount(&L, Latch);
|
2015-01-16 09:03:22 +08:00
|
|
|
if (isa<SCEVCouldNotCompute>(LatchCount)) {
|
|
|
|
FailureReason = "could not compute latch count";
|
2015-02-26 16:19:31 +08:00
|
|
|
return None;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
ICmpInst::Predicate Pred = ICI->getPredicate();
|
|
|
|
Value *LeftValue = ICI->getOperand(0);
|
|
|
|
const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
|
|
|
|
IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
|
|
|
|
|
|
|
|
Value *RightValue = ICI->getOperand(1);
|
|
|
|
const SCEV *RightSCEV = SE.getSCEV(RightValue);
|
|
|
|
|
|
|
|
// We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
|
|
|
|
if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
|
|
|
|
if (isa<SCEVAddRecExpr>(RightSCEV)) {
|
|
|
|
std::swap(LeftSCEV, RightSCEV);
|
|
|
|
std::swap(LeftValue, RightValue);
|
|
|
|
Pred = ICmpInst::getSwappedPredicate(Pred);
|
|
|
|
} else {
|
|
|
|
FailureReason = "no add recurrences in the icmp";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-03-25 03:29:22 +08:00
|
|
|
auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
|
|
|
|
if (AR->getNoWrapFlags(SCEV::FlagNSW))
|
|
|
|
return true;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
IntegerType *Ty = cast<IntegerType>(AR->getType());
|
|
|
|
IntegerType *WideTy =
|
|
|
|
IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
const SCEVAddRecExpr *ExtendAfterOp =
|
|
|
|
dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
|
2015-03-25 03:29:22 +08:00
|
|
|
if (ExtendAfterOp) {
|
|
|
|
const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
|
|
|
|
const SCEV *ExtendedStep =
|
|
|
|
SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
|
|
|
|
|
|
|
|
bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
|
|
|
|
ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
|
|
|
|
|
|
|
|
if (NoSignedWrap)
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We may have proved this when computing the sign extension above.
|
|
|
|
return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
|
|
|
|
};
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2017-09-21 12:50:41 +08:00
|
|
|
// `ICI` is interpreted as taking the backedge if the *next* value of the
|
|
|
|
// induction variable satisfies some constraint.
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2017-08-31 13:58:15 +08:00
|
|
|
const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
|
2018-04-18 21:50:28 +08:00
|
|
|
if (!IndVarBase->isAffine()) {
|
|
|
|
FailureReason = "LHS in icmp not induction variable";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
const SCEV* StepRec = IndVarBase->getStepRecurrence(SE);
|
2018-05-04 15:34:35 +08:00
|
|
|
if (!isa<SCEVConstant>(StepRec)) {
|
2015-02-26 16:19:31 +08:00
|
|
|
FailureReason = "LHS in icmp not induction variable";
|
|
|
|
return None;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
2018-05-04 15:34:35 +08:00
|
|
|
ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
|
|
|
|
|
2018-04-18 21:50:28 +08:00
|
|
|
if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
|
|
|
|
FailureReason = "LHS in icmp needs nsw for equality predicates";
|
|
|
|
return None;
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2018-04-18 21:50:28 +08:00
|
|
|
assert(!StepCI->isZero() && "Zero step?");
|
|
|
|
bool IsIncreasing = !StepCI->isNegative();
|
2019-07-12 22:58:15 +08:00
|
|
|
bool IsSignedPredicate;
|
2017-09-21 12:50:41 +08:00
|
|
|
const SCEV *StartNext = IndVarBase->getStart();
|
|
|
|
const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
|
|
|
|
const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
|
2017-08-04 15:01:04 +08:00
|
|
|
const SCEV *Step = SE.getSCEV(StepCI);
|
2017-02-08 07:59:07 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
ConstantInt *One = ConstantInt::get(IndVarTy, 1);
|
|
|
|
if (IsIncreasing) {
|
2017-07-18 12:53:48 +08:00
|
|
|
bool DecreasedRightValueByOne = false;
|
2017-08-04 15:01:04 +08:00
|
|
|
if (StepCI->isOne()) {
|
|
|
|
// Try to turn eq/ne predicates to those we can work with.
|
|
|
|
if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
|
|
|
|
// while (++i != len) { while (++i < len) {
|
|
|
|
// ... ---> ...
|
|
|
|
// } }
|
|
|
|
// If both parts are known non-negative, it is profitable to use
|
|
|
|
// unsigned comparison in increasing loop. This allows us to make the
|
|
|
|
// comparison check against "RightSCEV + 1" more optimistic.
|
2018-04-12 20:49:40 +08:00
|
|
|
if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) &&
|
|
|
|
isKnownNonNegativeInLoop(RightSCEV, &L, SE))
|
2017-08-04 15:01:04 +08:00
|
|
|
Pred = ICmpInst::ICMP_ULT;
|
|
|
|
else
|
|
|
|
Pred = ICmpInst::ICMP_SLT;
|
2018-03-26 17:29:42 +08:00
|
|
|
else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
|
2017-08-04 15:01:04 +08:00
|
|
|
// while (true) { while (true) {
|
|
|
|
// if (++i == len) ---> if (++i > len - 1)
|
|
|
|
// break; break;
|
|
|
|
// ... ...
|
|
|
|
// } }
|
2018-03-26 17:29:42 +08:00
|
|
|
if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
|
2019-01-15 17:51:34 +08:00
|
|
|
cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) {
|
2018-03-26 17:29:42 +08:00
|
|
|
Pred = ICmpInst::ICMP_UGT;
|
|
|
|
RightSCEV = SE.getMinusSCEV(RightSCEV,
|
|
|
|
SE.getOne(RightSCEV->getType()));
|
|
|
|
DecreasedRightValueByOne = true;
|
2019-01-15 17:51:34 +08:00
|
|
|
} else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) {
|
2018-03-26 17:29:42 +08:00
|
|
|
Pred = ICmpInst::ICMP_SGT;
|
|
|
|
RightSCEV = SE.getMinusSCEV(RightSCEV,
|
|
|
|
SE.getOne(RightSCEV->getType()));
|
|
|
|
DecreasedRightValueByOne = true;
|
|
|
|
}
|
2017-08-04 15:01:04 +08:00
|
|
|
}
|
2017-07-18 12:53:48 +08:00
|
|
|
}
|
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
|
|
|
|
bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
|
2015-02-26 16:19:31 +08:00
|
|
|
bool FoundExpectedPred =
|
2017-08-04 13:40:20 +08:00
|
|
|
(LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
|
2015-02-26 16:19:31 +08:00
|
|
|
|
|
|
|
if (!FoundExpectedPred) {
|
|
|
|
FailureReason = "expected icmp slt semantically, found something else";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2018-03-26 17:29:42 +08:00
|
|
|
IsSignedPredicate = ICmpInst::isSigned(Pred);
|
2017-10-04 14:53:22 +08:00
|
|
|
if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
|
|
|
|
FailureReason = "unsigned latch conditions are explicitly prohibited";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2018-03-26 17:29:42 +08:00
|
|
|
if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
|
|
|
|
LatchBrExitIdx, &L, SE)) {
|
|
|
|
FailureReason = "Unsafe loop bounds";
|
|
|
|
return None;
|
|
|
|
}
|
2015-02-26 16:19:31 +08:00
|
|
|
if (LatchBrExitIdx == 0) {
|
2017-07-18 12:53:48 +08:00
|
|
|
// We need to increase the right value unless we have already decreased
|
|
|
|
// it virtually when we replaced EQ with SGT.
|
|
|
|
if (!DecreasedRightValueByOne) {
|
|
|
|
IRBuilder<> B(Preheader->getTerminator());
|
|
|
|
RightValue = B.CreateAdd(RightValue, One);
|
|
|
|
}
|
2017-02-08 07:59:07 +08:00
|
|
|
} else {
|
2017-07-18 12:53:48 +08:00
|
|
|
assert(!DecreasedRightValueByOne &&
|
|
|
|
"Right value can be decreased only for LatchBrExitIdx == 0!");
|
2015-02-26 16:19:31 +08:00
|
|
|
}
|
|
|
|
} else {
|
2017-07-18 12:53:48 +08:00
|
|
|
bool IncreasedRightValueByOne = false;
|
2017-08-04 15:01:04 +08:00
|
|
|
if (StepCI->isMinusOne()) {
|
|
|
|
// Try to turn eq/ne predicates to those we can work with.
|
|
|
|
if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
|
|
|
|
// while (--i != len) { while (--i > len) {
|
|
|
|
// ... ---> ...
|
|
|
|
// } }
|
|
|
|
// We intentionally don't turn the predicate into UGT even if we know
|
|
|
|
// that both operands are non-negative, because it will only pessimize
|
|
|
|
// our check against "RightSCEV - 1".
|
|
|
|
Pred = ICmpInst::ICMP_SGT;
|
2018-03-27 16:24:53 +08:00
|
|
|
else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
|
2017-08-04 15:01:04 +08:00
|
|
|
// while (true) { while (true) {
|
|
|
|
// if (--i == len) ---> if (--i < len + 1)
|
|
|
|
// break; break;
|
|
|
|
// ... ...
|
|
|
|
// } }
|
2018-03-27 16:24:53 +08:00
|
|
|
if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
|
2019-01-15 17:51:34 +08:00
|
|
|
cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
|
2018-03-27 16:24:53 +08:00
|
|
|
Pred = ICmpInst::ICMP_ULT;
|
|
|
|
RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
|
|
|
|
IncreasedRightValueByOne = true;
|
2019-01-15 17:51:34 +08:00
|
|
|
} else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
|
2018-03-27 16:24:53 +08:00
|
|
|
Pred = ICmpInst::ICMP_SLT;
|
|
|
|
RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
|
|
|
|
IncreasedRightValueByOne = true;
|
|
|
|
}
|
2017-08-04 15:01:04 +08:00
|
|
|
}
|
2017-07-18 12:53:48 +08:00
|
|
|
}
|
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
|
|
|
|
bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
bool FoundExpectedPred =
|
2017-08-04 13:40:20 +08:00
|
|
|
(GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
|
2015-02-26 16:19:31 +08:00
|
|
|
|
|
|
|
if (!FoundExpectedPred) {
|
|
|
|
FailureReason = "expected icmp sgt semantically, found something else";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
IsSignedPredicate =
|
|
|
|
Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
|
2017-10-04 14:53:22 +08:00
|
|
|
|
|
|
|
if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
|
|
|
|
FailureReason = "unsigned latch conditions are explicitly prohibited";
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2018-03-27 16:24:53 +08:00
|
|
|
if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
|
|
|
|
LatchBrExitIdx, &L, SE)) {
|
|
|
|
FailureReason = "Unsafe bounds";
|
|
|
|
return None;
|
|
|
|
}
|
2017-08-04 13:40:20 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
if (LatchBrExitIdx == 0) {
|
2017-07-18 12:53:48 +08:00
|
|
|
// We need to decrease the right value unless we have already increased
|
|
|
|
// it virtually when we replaced EQ with SLT.
|
|
|
|
if (!IncreasedRightValueByOne) {
|
|
|
|
IRBuilder<> B(Preheader->getTerminator());
|
|
|
|
RightValue = B.CreateSub(RightValue, One);
|
|
|
|
}
|
2017-02-08 07:59:07 +08:00
|
|
|
} else {
|
2017-07-18 12:53:48 +08:00
|
|
|
assert(!IncreasedRightValueByOne &&
|
|
|
|
"Right value can be increased only for LatchBrExitIdx == 0!");
|
2015-02-26 16:19:31 +08:00
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
assert(SE.getLoopDisposition(LatchCount, &L) ==
|
2015-01-16 09:03:22 +08:00
|
|
|
ScalarEvolution::LoopInvariant &&
|
|
|
|
"loop variant exit count doesn't make sense!");
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
assert(!L.contains(LatchExit) && "expected an exit block!");
|
2015-03-10 10:37:25 +08:00
|
|
|
const DataLayout &DL = Preheader->getModule()->getDataLayout();
|
|
|
|
Value *IndVarStartV =
|
|
|
|
SCEVExpander(SE, DL, "irce")
|
2016-06-24 02:03:26 +08:00
|
|
|
.expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
|
2015-02-26 16:19:31 +08:00
|
|
|
IndVarStartV->setName("indvar.start");
|
|
|
|
|
|
|
|
LoopStructure Result;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
Result.Tag = "main";
|
|
|
|
Result.Header = Header;
|
|
|
|
Result.Latch = Latch;
|
|
|
|
Result.LatchBr = LatchBr;
|
|
|
|
Result.LatchExit = LatchExit;
|
|
|
|
Result.LatchBrExitIdx = LatchBrExitIdx;
|
|
|
|
Result.IndVarStart = IndVarStartV;
|
2017-08-04 15:01:04 +08:00
|
|
|
Result.IndVarStep = StepCI;
|
2017-08-31 13:58:15 +08:00
|
|
|
Result.IndVarBase = LeftValue;
|
2015-02-26 16:19:31 +08:00
|
|
|
Result.IndVarIncreasing = IsIncreasing;
|
|
|
|
Result.LoopExitAt = RightValue;
|
2017-08-04 13:40:20 +08:00
|
|
|
Result.IsSignedPredicate = IsSignedPredicate;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
FailureReason = nullptr;
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
return Result;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2019-01-23 15:20:56 +08:00
|
|
|
/// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
|
|
|
|
/// signed or unsigned extension of \p S to type \p Ty.
|
|
|
|
static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,
|
|
|
|
bool Signed) {
|
|
|
|
return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty);
|
|
|
|
}
|
|
|
|
|
2015-01-22 16:29:18 +08:00
|
|
|
Optional<LoopConstrainer::SubRanges>
|
2017-08-04 13:40:20 +08:00
|
|
|
LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
|
2015-01-16 09:03:22 +08:00
|
|
|
IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
|
|
|
|
|
2019-01-23 15:20:56 +08:00
|
|
|
auto *RTy = cast<IntegerType>(Range.getType());
|
|
|
|
|
|
|
|
// We only support wide range checks and narrow latches.
|
|
|
|
if (!AllowNarrowLatchCondition && RTy != Ty)
|
|
|
|
return None;
|
|
|
|
if (RTy->getBitWidth() < Ty->getBitWidth())
|
2015-01-22 16:29:18 +08:00
|
|
|
return None;
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
LoopConstrainer::SubRanges Result;
|
|
|
|
|
|
|
|
// I think we can be more aggressive here and make this nuw / nsw if the
|
|
|
|
// addition that feeds into the icmp for the latch's terminating branch is nuw
|
|
|
|
// / nsw. In any case, a wrapping 2's complement addition is safe.
|
2019-01-23 15:20:56 +08:00
|
|
|
const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart),
|
|
|
|
RTy, SE, IsSignedPredicate);
|
|
|
|
const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,
|
|
|
|
SE, IsSignedPredicate);
|
2015-02-26 16:19:31 +08:00
|
|
|
|
|
|
|
bool Increasing = MainLoopStructure.IndVarIncreasing;
|
2015-03-17 08:42:16 +08:00
|
|
|
|
2017-07-14 14:35:03 +08:00
|
|
|
// We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
|
|
|
|
// [Smallest, GreatestSeen] is the range of values the induction variable
|
|
|
|
// takes.
|
2015-03-17 08:42:16 +08:00
|
|
|
|
2017-07-14 14:35:03 +08:00
|
|
|
const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
|
2015-03-17 08:42:16 +08:00
|
|
|
|
2019-01-23 15:20:56 +08:00
|
|
|
const SCEV *One = SE.getOne(RTy);
|
2015-03-17 08:42:16 +08:00
|
|
|
if (Increasing) {
|
|
|
|
Smallest = Start;
|
|
|
|
Greatest = End;
|
2017-07-14 14:35:03 +08:00
|
|
|
// No overflow, because the range [Smallest, GreatestSeen] is not empty.
|
|
|
|
GreatestSeen = SE.getMinusSCEV(End, One);
|
2015-03-17 08:42:16 +08:00
|
|
|
} else {
|
|
|
|
// These two computations may sign-overflow. Here is why that is okay:
|
|
|
|
//
|
|
|
|
// We know that the induction variable does not sign-overflow on any
|
|
|
|
// iteration except the last one, and it starts at `Start` and ends at
|
|
|
|
// `End`, decrementing by one every time.
|
|
|
|
//
|
|
|
|
// * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
|
|
|
|
// induction variable is decreasing we know that that the smallest value
|
|
|
|
// the loop body is actually executed with is `INT_SMIN` == `Smallest`.
|
|
|
|
//
|
|
|
|
// * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
|
|
|
|
// that case, `Clamp` will always return `Smallest` and
|
|
|
|
// [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
|
|
|
|
// will be an empty range. Returning an empty range is always safe.
|
|
|
|
|
2017-06-28 12:57:45 +08:00
|
|
|
Smallest = SE.getAddExpr(End, One);
|
|
|
|
Greatest = SE.getAddExpr(Start, One);
|
2017-07-14 14:35:03 +08:00
|
|
|
GreatestSeen = Start;
|
2015-03-17 08:42:16 +08:00
|
|
|
}
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
|
2017-11-01 21:21:56 +08:00
|
|
|
return IsSignedPredicate
|
2017-08-04 13:40:20 +08:00
|
|
|
? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
|
|
|
|
: SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
|
2015-02-26 16:19:31 +08:00
|
|
|
};
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
// In some cases we can prove that we don't need a pre or post loop.
|
|
|
|
ICmpInst::Predicate PredLE =
|
|
|
|
IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
|
|
|
|
ICmpInst::Predicate PredLT =
|
|
|
|
IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
bool ProvablyNoPreloop =
|
2017-08-04 13:40:20 +08:00
|
|
|
SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
|
2015-02-26 16:19:31 +08:00
|
|
|
if (!ProvablyNoPreloop)
|
|
|
|
Result.LowLimit = Clamp(Range.getBegin());
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
bool ProvablyNoPostLoop =
|
2017-08-04 13:40:20 +08:00
|
|
|
SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
|
2015-02-26 16:19:31 +08:00
|
|
|
if (!ProvablyNoPostLoop)
|
|
|
|
Result.HighLimit = Clamp(Range.getEnd());
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
|
|
|
void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
|
|
|
|
const char *Tag) const {
|
|
|
|
for (BasicBlock *BB : OriginalLoop.getBlocks()) {
|
|
|
|
BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
|
|
|
|
Result.Blocks.push_back(Clone);
|
|
|
|
Result.Map[BB] = Clone;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto GetClonedValue = [&Result](Value *V) {
|
|
|
|
assert(V && "null values not in domain!");
|
|
|
|
auto It = Result.Map.find(V);
|
|
|
|
if (It == Result.Map.end())
|
|
|
|
return V;
|
|
|
|
return static_cast<Value *>(It->second);
|
|
|
|
};
|
|
|
|
|
2016-08-14 09:04:36 +08:00
|
|
|
auto *ClonedLatch =
|
|
|
|
cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
|
|
|
|
ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
|
|
|
|
MDNode::get(Ctx, {}));
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
Result.Structure = MainLoopStructure.map(GetClonedValue);
|
|
|
|
Result.Structure.Tag = Tag;
|
|
|
|
|
|
|
|
for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
|
|
|
|
BasicBlock *ClonedBB = Result.Blocks[i];
|
|
|
|
BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
|
|
|
|
|
|
|
|
assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
|
|
|
|
|
|
|
|
for (Instruction &I : *ClonedBB)
|
|
|
|
RemapInstruction(&I, Result.Map,
|
2016-04-07 08:26:43 +08:00
|
|
|
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Exit blocks will now have one more predecessor and their PHI nodes need
|
|
|
|
// to be edited to reflect that. No phi nodes need to be introduced because
|
|
|
|
// the loop is in LCSSA.
|
|
|
|
|
2016-08-14 06:00:09 +08:00
|
|
|
for (auto *SBB : successors(OriginalBB)) {
|
|
|
|
if (OriginalLoop.contains(SBB))
|
2015-01-16 09:03:22 +08:00
|
|
|
continue; // not an exit block
|
|
|
|
|
2017-12-30 23:27:33 +08:00
|
|
|
for (PHINode &PN : SBB->phis()) {
|
|
|
|
Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
|
|
|
|
PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
|
2015-02-26 16:19:31 +08:00
|
|
|
const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
|
2015-01-16 09:03:22 +08:00
|
|
|
BasicBlock *ContinuationBlock) const {
|
|
|
|
// We start with a loop with a single latch:
|
|
|
|
//
|
|
|
|
// +--------------------+
|
|
|
|
// | |
|
|
|
|
// | preheader |
|
|
|
|
// | |
|
|
|
|
// +--------+-----------+
|
|
|
|
// | ----------------\
|
|
|
|
// | / |
|
|
|
|
// +--------v----v------+ |
|
|
|
|
// | | |
|
|
|
|
// | header | |
|
|
|
|
// | | |
|
|
|
|
// +--------------------+ |
|
|
|
|
// |
|
|
|
|
// ..... |
|
|
|
|
// |
|
|
|
|
// +--------------------+ |
|
|
|
|
// | | |
|
|
|
|
// | latch >----------/
|
|
|
|
// | |
|
|
|
|
// +-------v------------+
|
|
|
|
// |
|
|
|
|
// |
|
|
|
|
// | +--------------------+
|
|
|
|
// | | |
|
|
|
|
// +---> original exit |
|
|
|
|
// | |
|
|
|
|
// +--------------------+
|
|
|
|
//
|
|
|
|
// We change the control flow to look like
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// +--------------------+
|
|
|
|
// | |
|
|
|
|
// | preheader >-------------------------+
|
|
|
|
// | | |
|
|
|
|
// +--------v-----------+ |
|
|
|
|
// | /-------------+ |
|
|
|
|
// | / | |
|
|
|
|
// +--------v--v--------+ | |
|
|
|
|
// | | | |
|
|
|
|
// | header | | +--------+ |
|
|
|
|
// | | | | | |
|
|
|
|
// +--------------------+ | | +-----v-----v-----------+
|
|
|
|
// | | | |
|
|
|
|
// | | | .pseudo.exit |
|
|
|
|
// | | | |
|
|
|
|
// | | +-----------v-----------+
|
|
|
|
// | | |
|
|
|
|
// ..... | | |
|
|
|
|
// | | +--------v-------------+
|
|
|
|
// +--------------------+ | | | |
|
|
|
|
// | | | | | ContinuationBlock |
|
|
|
|
// | latch >------+ | | |
|
|
|
|
// | | | +----------------------+
|
|
|
|
// +---------v----------+ |
|
|
|
|
// | |
|
|
|
|
// | |
|
|
|
|
// | +---------------^-----+
|
|
|
|
// | | |
|
|
|
|
// +-----> .exit.selector |
|
|
|
|
// | |
|
|
|
|
// +----------v----------+
|
|
|
|
// |
|
|
|
|
// +--------------------+ |
|
|
|
|
// | | |
|
|
|
|
// | original exit <----+
|
|
|
|
// | |
|
|
|
|
// +--------------------+
|
|
|
|
|
|
|
|
RewrittenRangeInfo RRI;
|
|
|
|
|
2016-08-17 09:16:17 +08:00
|
|
|
BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
|
2015-01-16 09:03:22 +08:00
|
|
|
RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
|
2016-08-17 09:16:17 +08:00
|
|
|
&F, BBInsertLocation);
|
2015-01-16 09:03:22 +08:00
|
|
|
RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
|
2016-08-17 09:16:17 +08:00
|
|
|
BBInsertLocation);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-06-24 02:03:26 +08:00
|
|
|
BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
|
2015-02-26 16:19:31 +08:00
|
|
|
bool Increasing = LS.IndVarIncreasing;
|
2017-08-04 13:40:20 +08:00
|
|
|
bool IsSignedPredicate = LS.IsSignedPredicate;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
IRBuilder<> B(PreheaderJump);
|
2019-01-23 15:20:56 +08:00
|
|
|
auto *RangeTy = Range.getBegin()->getType();
|
|
|
|
auto NoopOrExt = [&](Value *V) {
|
|
|
|
if (V->getType() == RangeTy)
|
|
|
|
return V;
|
|
|
|
return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName())
|
|
|
|
: B.CreateZExt(V, RangeTy, "wide." + V->getName());
|
|
|
|
};
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// EnterLoopCond - is it okay to start executing this `LS'?
|
2017-08-04 13:40:20 +08:00
|
|
|
Value *EnterLoopCond = nullptr;
|
2019-01-15 19:16:14 +08:00
|
|
|
auto Pred =
|
|
|
|
Increasing
|
|
|
|
? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT)
|
|
|
|
: (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
|
2019-01-23 15:20:56 +08:00
|
|
|
Value *IndVarStart = NoopOrExt(LS.IndVarStart);
|
2019-01-17 14:20:42 +08:00
|
|
|
EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
|
|
|
|
PreheaderJump->eraseFromParent();
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
|
2015-01-16 09:03:22 +08:00
|
|
|
B.SetInsertPoint(LS.LatchBr);
|
2019-01-23 15:20:56 +08:00
|
|
|
Value *IndVarBase = NoopOrExt(LS.IndVarBase);
|
2019-01-17 14:20:42 +08:00
|
|
|
Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
|
2019-01-15 19:16:14 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
Value *CondForBranch = LS.LatchBrExitIdx == 1
|
|
|
|
? TakeBackedgeLoopCond
|
|
|
|
: B.CreateNot(TakeBackedgeLoopCond);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
LS.LatchBr->setCondition(CondForBranch);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
B.SetInsertPoint(RRI.ExitSelector);
|
|
|
|
|
|
|
|
// IterationsLeft - are there any more iterations left, given the original
|
|
|
|
// upper bound on the induction variable? If not, we branch to the "real"
|
|
|
|
// exit.
|
2019-01-23 15:20:56 +08:00
|
|
|
Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
|
2019-01-17 14:20:42 +08:00
|
|
|
Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt);
|
2015-01-16 09:03:22 +08:00
|
|
|
B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
|
|
|
|
|
|
|
|
BranchInst *BranchToContinuation =
|
|
|
|
BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
|
|
|
|
|
|
|
|
// We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
|
|
|
|
// each of the PHI nodes in the loop header. This feeds into the initial
|
|
|
|
// value of the same PHI nodes if/when we continue execution.
|
2017-12-30 23:27:33 +08:00
|
|
|
for (PHINode &PN : LS.Header->phis()) {
|
|
|
|
PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
|
2015-01-16 09:03:22 +08:00
|
|
|
BranchToContinuation);
|
|
|
|
|
2017-12-30 23:27:33 +08:00
|
|
|
NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
|
|
|
|
NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
|
2017-09-21 12:50:41 +08:00
|
|
|
RRI.ExitSelector);
|
2015-01-16 09:03:22 +08:00
|
|
|
RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
|
|
|
|
}
|
|
|
|
|
2019-01-17 14:20:42 +08:00
|
|
|
RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end",
|
2015-02-26 16:19:31 +08:00
|
|
|
BranchToContinuation);
|
2019-01-17 14:20:42 +08:00
|
|
|
RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
|
|
|
|
RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
// The latch exit now has a branch from `RRI.ExitSelector' instead of
|
|
|
|
// `LS.Latch'. The PHI nodes need to be updated to reflect that.
|
2019-05-06 02:59:39 +08:00
|
|
|
LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
return RRI;
|
|
|
|
}
|
|
|
|
|
|
|
|
void LoopConstrainer::rewriteIncomingValuesForPHIs(
|
2015-02-26 16:19:31 +08:00
|
|
|
LoopStructure &LS, BasicBlock *ContinuationBlock,
|
2015-01-16 09:03:22 +08:00
|
|
|
const LoopConstrainer::RewrittenRangeInfo &RRI) const {
|
|
|
|
unsigned PHIIndex = 0;
|
2017-12-30 23:27:33 +08:00
|
|
|
for (PHINode &PN : LS.Header->phis())
|
PHINode: introduce setIncomingValueForBlock() function, and use it.
Summary:
There is PHINode::getBasicBlockIndex() and PHINode::setIncomingValue()
but no function to replace incoming value for a specified BasicBlock*
predecessor.
Clearly, there are a lot of places that could use that functionality.
Reviewer: craig.topper, lebedev.ri, Meinersbur, kbarton, fhahn
Reviewed By: Meinersbur, fhahn
Subscribers: fhahn, hiraditya, zzheng, jsji, llvm-commits
Tag: LLVM
Differential Revision: https://reviews.llvm.org/D63338
llvm-svn: 363566
2019-06-17 22:38:56 +08:00
|
|
|
PN.setIncomingValueForBlock(ContinuationBlock,
|
|
|
|
RRI.PHIValuesAtPseudoExit[PHIIndex++]);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
LS.IndVarStart = RRI.IndVarEnd;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
|
|
|
|
BasicBlock *OldPreheader,
|
|
|
|
const char *Tag) const {
|
2015-01-16 09:03:22 +08:00
|
|
|
BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
|
|
|
|
BranchInst::Create(LS.Header, Preheader);
|
|
|
|
|
2019-05-06 02:59:39 +08:00
|
|
|
LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
return Preheader;
|
|
|
|
}
|
|
|
|
|
2015-02-06 22:43:49 +08:00
|
|
|
void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
|
2015-01-16 09:03:22 +08:00
|
|
|
Loop *ParentLoop = OriginalLoop.getParentLoop();
|
|
|
|
if (!ParentLoop)
|
|
|
|
return;
|
|
|
|
|
2015-02-06 22:43:49 +08:00
|
|
|
for (BasicBlock *BB : BBs)
|
2016-08-03 03:32:01 +08:00
|
|
|
ParentLoop->addBasicBlockToLoop(BB, LI);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2016-08-14 09:04:46 +08:00
|
|
|
Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
|
2018-03-15 19:01:19 +08:00
|
|
|
ValueToValueMapTy &VM,
|
|
|
|
bool IsSubloop) {
|
2017-09-28 10:45:42 +08:00
|
|
|
Loop &New = *LI.AllocateLoop();
|
2017-05-25 11:01:31 +08:00
|
|
|
if (Parent)
|
|
|
|
Parent->addChildLoop(&New);
|
|
|
|
else
|
|
|
|
LI.addTopLevelLoop(&New);
|
2018-03-15 19:01:19 +08:00
|
|
|
LPMAddNewLoop(&New, IsSubloop);
|
2016-08-14 09:04:46 +08:00
|
|
|
|
|
|
|
// Add all of the blocks in Original to the new loop.
|
|
|
|
for (auto *BB : Original->blocks())
|
|
|
|
if (LI.getLoopFor(BB) == Original)
|
|
|
|
New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
|
|
|
|
|
|
|
|
// Add all of the subloops to the new loop.
|
|
|
|
for (Loop *SubLoop : *Original)
|
2018-03-15 19:01:19 +08:00
|
|
|
createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
|
2016-08-14 09:04:46 +08:00
|
|
|
|
|
|
|
return &New;
|
|
|
|
}
|
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
bool LoopConstrainer::run() {
|
|
|
|
BasicBlock *Preheader = nullptr;
|
2015-02-26 16:19:31 +08:00
|
|
|
LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
|
|
|
|
Preheader = OriginalLoop.getLoopPreheader();
|
|
|
|
assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
|
|
|
|
"preconditions!");
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
OriginalPreheader = Preheader;
|
|
|
|
MainLoopPreheader = Preheader;
|
|
|
|
|
2017-08-04 13:40:20 +08:00
|
|
|
bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
|
|
|
|
Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
|
2015-01-22 16:29:18 +08:00
|
|
|
if (!MaybeSR.hasValue()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
|
2015-01-22 16:29:18 +08:00
|
|
|
return false;
|
|
|
|
}
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2015-01-22 16:29:18 +08:00
|
|
|
SubRanges SR = MaybeSR.getValue();
|
2015-02-26 16:19:31 +08:00
|
|
|
bool Increasing = MainLoopStructure.IndVarIncreasing;
|
|
|
|
IntegerType *IVTy =
|
2019-01-23 15:20:56 +08:00
|
|
|
cast<IntegerType>(Range.getBegin()->getType());
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2015-03-10 10:37:25 +08:00
|
|
|
SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
|
2015-02-26 16:19:31 +08:00
|
|
|
Instruction *InsertPt = OriginalPreheader->getTerminator();
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// It would have been better to make `PreLoop' and `PostLoop'
|
|
|
|
// `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
|
|
|
|
// constructor.
|
|
|
|
ClonedLoop PreLoop, PostLoop;
|
2015-02-26 16:19:31 +08:00
|
|
|
bool NeedsPreLoop =
|
|
|
|
Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
|
|
|
|
bool NeedsPostLoop =
|
|
|
|
Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
|
|
|
|
|
|
|
|
Value *ExitPreLoopAt = nullptr;
|
|
|
|
Value *ExitMainLoopAt = nullptr;
|
|
|
|
const SCEVConstant *MinusOneS =
|
|
|
|
cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
|
|
|
|
|
|
|
|
if (NeedsPreLoop) {
|
|
|
|
const SCEV *ExitPreLoopAtSCEV = nullptr;
|
|
|
|
|
|
|
|
if (Increasing)
|
|
|
|
ExitPreLoopAtSCEV = *SR.LowLimit;
|
2019-01-15 18:01:46 +08:00
|
|
|
else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
|
|
|
|
IsSignedPredicate))
|
|
|
|
ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
|
2015-02-26 16:19:31 +08:00
|
|
|
else {
|
2019-01-15 18:01:46 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
|
|
|
|
<< "preloop exit limit. HighLimit = "
|
|
|
|
<< *(*SR.HighLimit) << "\n");
|
|
|
|
return false;
|
2015-02-26 16:19:31 +08:00
|
|
|
}
|
2017-09-21 12:50:41 +08:00
|
|
|
|
2017-11-16 14:06:27 +08:00
|
|
|
if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
|
|
|
|
<< " preloop exit limit " << *ExitPreLoopAtSCEV
|
|
|
|
<< " at block " << InsertPt->getParent()->getName()
|
|
|
|
<< "\n");
|
2017-11-16 14:06:27 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
|
|
|
|
ExitPreLoopAt->setName("exit.preloop.at");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (NeedsPostLoop) {
|
|
|
|
const SCEV *ExitMainLoopAtSCEV = nullptr;
|
|
|
|
|
|
|
|
if (Increasing)
|
|
|
|
ExitMainLoopAtSCEV = *SR.HighLimit;
|
2019-01-15 18:01:46 +08:00
|
|
|
else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
|
|
|
|
IsSignedPredicate))
|
|
|
|
ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
|
2015-02-26 16:19:31 +08:00
|
|
|
else {
|
2019-01-15 18:01:46 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
|
|
|
|
<< "mainloop exit limit. LowLimit = "
|
|
|
|
<< *(*SR.LowLimit) << "\n");
|
|
|
|
return false;
|
2015-02-26 16:19:31 +08:00
|
|
|
}
|
2017-09-21 12:50:41 +08:00
|
|
|
|
2017-11-16 14:06:27 +08:00
|
|
|
if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
|
|
|
|
<< " main loop exit limit " << *ExitMainLoopAtSCEV
|
|
|
|
<< " at block " << InsertPt->getParent()->getName()
|
|
|
|
<< "\n");
|
2017-11-16 14:06:27 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
|
|
|
|
ExitMainLoopAt->setName("exit.mainloop.at");
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// We clone these ahead of time so that we don't have to deal with changing
|
|
|
|
// and temporarily invalid IR as we transform the loops.
|
|
|
|
if (NeedsPreLoop)
|
|
|
|
cloneLoop(PreLoop, "preloop");
|
|
|
|
if (NeedsPostLoop)
|
|
|
|
cloneLoop(PostLoop, "postloop");
|
|
|
|
|
|
|
|
RewrittenRangeInfo PreLoopRRI;
|
|
|
|
|
|
|
|
if (NeedsPreLoop) {
|
|
|
|
Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
|
|
|
|
PreLoop.Structure.Header);
|
|
|
|
|
|
|
|
MainLoopPreheader =
|
|
|
|
createPreheader(MainLoopStructure, Preheader, "mainloop");
|
2015-02-26 16:19:31 +08:00
|
|
|
PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
|
|
|
|
ExitPreLoopAt, MainLoopPreheader);
|
2015-01-16 09:03:22 +08:00
|
|
|
rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
|
|
|
|
PreLoopRRI);
|
|
|
|
}
|
|
|
|
|
|
|
|
BasicBlock *PostLoopPreheader = nullptr;
|
|
|
|
RewrittenRangeInfo PostLoopRRI;
|
|
|
|
|
|
|
|
if (NeedsPostLoop) {
|
|
|
|
PostLoopPreheader =
|
|
|
|
createPreheader(PostLoop.Structure, Preheader, "postloop");
|
|
|
|
PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
|
2015-02-26 16:19:31 +08:00
|
|
|
ExitMainLoopAt, PostLoopPreheader);
|
2015-01-16 09:03:22 +08:00
|
|
|
rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
|
|
|
|
PostLoopRRI);
|
|
|
|
}
|
|
|
|
|
2015-02-06 22:43:49 +08:00
|
|
|
BasicBlock *NewMainLoopPreheader =
|
|
|
|
MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
|
|
|
|
BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
|
|
|
|
PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
|
|
|
|
PostLoopRRI.ExitSelector, NewMainLoopPreheader};
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
// Some of the above may be nullptr, filter them out before passing to
|
|
|
|
// addToParentLoopIfNeeded.
|
2015-02-06 22:43:49 +08:00
|
|
|
auto NewBlocksEnd =
|
|
|
|
std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-06 22:43:49 +08:00
|
|
|
addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2016-08-03 03:31:54 +08:00
|
|
|
DT.recalculate(F);
|
2016-08-14 09:04:46 +08:00
|
|
|
|
2017-06-06 22:54:01 +08:00
|
|
|
// We need to first add all the pre and post loop blocks into the loop
|
|
|
|
// structures (as part of createClonedLoopStructure), and then update the
|
|
|
|
// LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
|
|
|
|
// LI when LoopSimplifyForm is generated.
|
|
|
|
Loop *PreL = nullptr, *PostL = nullptr;
|
2016-08-14 09:04:46 +08:00
|
|
|
if (!PreLoop.Blocks.empty()) {
|
2018-03-15 19:01:19 +08:00
|
|
|
PreL = createClonedLoopStructure(&OriginalLoop,
|
|
|
|
OriginalLoop.getParentLoop(), PreLoop.Map,
|
|
|
|
/* IsSubLoop */ false);
|
2016-08-14 09:04:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!PostLoop.Blocks.empty()) {
|
2018-03-15 19:01:19 +08:00
|
|
|
PostL =
|
|
|
|
createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
|
|
|
|
PostLoop.Map, /* IsSubLoop */ false);
|
2017-06-06 22:54:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
|
|
|
|
auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
|
2016-08-14 09:04:46 +08:00
|
|
|
formLCSSARecursively(*L, DT, &LI, &SE);
|
[MemorySSA] Teach LoopSimplify to preserve MemorySSA.
Summary:
Preserve MemorySSA in LoopSimplify, in the old pass manager, if the analysis is available.
Do not preserve it in the new pass manager.
Update tests.
Subscribers: nemanjai, jlebar, javed.absar, Prazek, kbarton, zzheng, jsji, llvm-commits, george.burgess.iv, chandlerc
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D60833
llvm-svn: 360270
2019-05-09 01:05:36 +08:00
|
|
|
simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true);
|
2017-06-06 22:54:01 +08:00
|
|
|
// Pre/post loops are slow paths, we do not need to perform any loop
|
2016-12-14 05:05:21 +08:00
|
|
|
// optimizations on them.
|
2017-06-06 22:54:01 +08:00
|
|
|
if (!IsOriginalLoop)
|
|
|
|
DisableAllLoopOptsOnLoop(*L);
|
|
|
|
};
|
|
|
|
if (PreL)
|
|
|
|
CanonicalizeLoop(PreL, false);
|
|
|
|
if (PostL)
|
|
|
|
CanonicalizeLoop(PostL, false);
|
|
|
|
CanonicalizeLoop(&OriginalLoop, true);
|
2016-08-03 03:31:54 +08:00
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-02-22 06:20:22 +08:00
|
|
|
/// Computes and returns a range of values for the induction variable (IndVar)
|
|
|
|
/// in which the range check can be safely elided. If it cannot compute such a
|
|
|
|
/// range, returns None.
|
2015-01-16 09:03:22 +08:00
|
|
|
Optional<InductiveRangeCheck::Range>
|
2016-05-21 10:31:51 +08:00
|
|
|
InductiveRangeCheck::computeSafeIterationSpace(
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
|
|
|
|
bool IsLatchSigned) const {
|
2019-01-23 15:20:56 +08:00
|
|
|
// We can deal when types of latch check and range checks don't match in case
|
|
|
|
// if latch check is more narrow.
|
|
|
|
auto *IVType = cast<IntegerType>(IndVar->getType());
|
|
|
|
auto *RCType = cast<IntegerType>(getBegin()->getType());
|
|
|
|
if (IVType->getBitWidth() > RCType->getBitWidth())
|
|
|
|
return None;
|
2015-02-22 06:20:22 +08:00
|
|
|
// IndVar is of the form "A + B * I" (where "I" is the canonical induction
|
|
|
|
// variable, that may or may not exist as a real llvm::Value in the loop) and
|
|
|
|
// this inductive range check is a range check on the "C + D * I" ("C" is
|
2017-10-31 14:19:05 +08:00
|
|
|
// getBegin() and "D" is getStep()). We rewrite the value being range
|
2015-02-22 06:20:22 +08:00
|
|
|
// checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
|
|
|
|
//
|
|
|
|
// The actual inequalities we solve are of the form
|
2015-01-16 09:03:22 +08:00
|
|
|
//
|
2015-02-22 06:20:22 +08:00
|
|
|
// 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
|
2015-01-16 09:03:22 +08:00
|
|
|
//
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Here L stands for upper limit of the safe iteration space.
|
|
|
|
// The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
|
|
|
|
// overflows when calculating (0 - M) and (L - M) we, depending on type of
|
|
|
|
// IV's iteration space, limit the calculations by borders of the iteration
|
|
|
|
// space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
|
|
|
|
// If we figured out that "anything greater than (-M) is safe", we strengthen
|
|
|
|
// this to "everything greater than 0 is safe", assuming that values between
|
|
|
|
// -M and 0 just do not exist in unsigned iteration space, and we don't want
|
|
|
|
// to deal with overflown values.
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-22 06:20:22 +08:00
|
|
|
if (!IndVar->isAffine())
|
|
|
|
return None;
|
|
|
|
|
2019-01-23 15:20:56 +08:00
|
|
|
const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned);
|
|
|
|
const SCEVConstant *B = dyn_cast<SCEVConstant>(
|
|
|
|
NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned));
|
2015-02-22 06:20:22 +08:00
|
|
|
if (!B)
|
2015-01-16 09:03:22 +08:00
|
|
|
return None;
|
2017-08-01 14:49:29 +08:00
|
|
|
assert(!B->isZero() && "Recurrence with zero step?");
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2017-10-31 14:19:05 +08:00
|
|
|
const SCEV *C = getBegin();
|
|
|
|
const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
|
2015-02-22 06:20:22 +08:00
|
|
|
if (D != B)
|
|
|
|
return None;
|
|
|
|
|
2017-08-04 15:41:24 +08:00
|
|
|
assert(!D->getValue()->isZero() && "Recurrence with zero step?");
|
2019-01-23 15:20:56 +08:00
|
|
|
unsigned BitWidth = RCType->getBitWidth();
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
|
2015-02-22 06:20:22 +08:00
|
|
|
|
2018-02-12 13:16:28 +08:00
|
|
|
// Subtract Y from X so that it does not go through border of the IV
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// iteration space. Mathematically, it is equivalent to:
|
|
|
|
//
|
2018-02-12 13:16:28 +08:00
|
|
|
// ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
//
|
2018-02-12 13:16:28 +08:00
|
|
|
// In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// any width of bit grid). But after we take min/max, the result is
|
|
|
|
// guaranteed to be within [INT_MIN, INT_MAX].
|
|
|
|
//
|
|
|
|
// In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
|
|
|
|
// values, depending on type of latch condition that defines IV iteration
|
|
|
|
// space.
|
2018-02-12 13:16:28 +08:00
|
|
|
auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
|
[IRCE] Fix miscompile with range checks against negative values
In the patch rL329547, we have lifted the over-restrictive limitation on collected range
checks, allowing to work with range checks with the end of their range not being
provably non-negative. However it appeared that the non-negativity of this value was
assumed in the utility function `ClampedSubtract`. In particular, its reasoning is based
on the fact that `0 <= SINT_MAX - X`, which is not true if `X` is negative.
The function `ClampedSubtract` is only called twice, once with `X = 0` (which is OK)
and the second time with `X = IRC.getEnd()`, where we may now see the problem if
the end is actually a negative value. In this case, we may sometimes miscompile.
This patch is the conservative fix of the miscompile problem. Rather than rejecting
non-provably non-negative `getEnd()` values, we will check it for non-negativity in
runtime. For this, we use function `smax(smin(X, 0), -1) + 1` that is equal to `1` if `X`
is non-negative and is equal to 0 if `X` is negative. If we multiply `Begin, End` of safe
iteration space by this function calculated for `X = IRC.getEnd()`, we will get the original
`[Begin, End)` if `IRC.getEnd()` was non-negative (and, thus, `ClampedSubtract` worked
correctly) and the empty range `[0, 0)` in case if ` IRC.getEnd()` was negative.
So we in fact prohibit execution of the main loop if at least one of range checks was
made against a negative value (and we figured it out in runtime). It is still better than
what we have before (non-negativity had to be proved in compile time) and prevents
us from miscompile, however it is sometiles too restrictive for unsigned range checks
against a negative value (which in fact can be eliminated).
Once we re-implement `ClampedSubtract` in a way that it handles negative `X` correctly,
this limitation can be lifted, too.
Differential Revision: https://reviews.llvm.org/D46860
Reviewed By: samparker
llvm-svn: 332809
2018-05-19 21:06:37 +08:00
|
|
|
// FIXME: The current implementation assumes that X is in [0, SINT_MAX].
|
|
|
|
// This is required to ensure that SINT_MAX - X does not overflow signed and
|
|
|
|
// that X - Y does not overflow unsigned if Y is negative. Can we lift this
|
|
|
|
// restriction and make it work for negative X either?
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
if (IsLatchSigned) {
|
|
|
|
// X is a number from signed range, Y is interpreted as signed.
|
|
|
|
// Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
|
|
|
|
// thing we should care about is that we didn't cross SINT_MAX.
|
2018-02-12 13:16:28 +08:00
|
|
|
// So, if Y is positive, we subtract Y safely.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 1: Y > 0 ---> Y.
|
2018-02-12 13:16:28 +08:00
|
|
|
// If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 2: Y >=s (X - SINT_MAX) ---> Y.
|
2018-02-12 13:16:28 +08:00
|
|
|
// If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
|
2018-02-12 13:16:28 +08:00
|
|
|
// It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
|
2017-11-23 14:14:39 +08:00
|
|
|
return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
|
|
|
|
SCEV::FlagNSW);
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
} else
|
|
|
|
// X is a number from unsigned range, Y is interpreted as signed.
|
|
|
|
// Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
|
|
|
|
// thing we should care about is that we didn't cross zero.
|
2018-02-12 13:16:28 +08:00
|
|
|
// So, if Y is negative, we subtract Y safely.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 1: Y <s 0 ---> Y.
|
2018-02-12 13:16:28 +08:00
|
|
|
// If 0 <= Y <= X, we subtract Y safely.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 2: Y <=s X ---> Y.
|
2018-02-12 13:16:28 +08:00
|
|
|
// If 0 <= X < Y, we should stop at 0 and can only subtract X.
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
// Rule 3: Y >s X ---> X.
|
2018-02-12 13:16:28 +08:00
|
|
|
// It gives us smin(X, Y) to subtract in all cases.
|
2017-11-23 14:14:39 +08:00
|
|
|
return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
};
|
2015-02-22 06:20:22 +08:00
|
|
|
const SCEV *M = SE.getMinusSCEV(C, A);
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
const SCEV *Zero = SE.getZero(M->getType());
|
[IRCE] Fix miscompile with range checks against negative values
In the patch rL329547, we have lifted the over-restrictive limitation on collected range
checks, allowing to work with range checks with the end of their range not being
provably non-negative. However it appeared that the non-negativity of this value was
assumed in the utility function `ClampedSubtract`. In particular, its reasoning is based
on the fact that `0 <= SINT_MAX - X`, which is not true if `X` is negative.
The function `ClampedSubtract` is only called twice, once with `X = 0` (which is OK)
and the second time with `X = IRC.getEnd()`, where we may now see the problem if
the end is actually a negative value. In this case, we may sometimes miscompile.
This patch is the conservative fix of the miscompile problem. Rather than rejecting
non-provably non-negative `getEnd()` values, we will check it for non-negativity in
runtime. For this, we use function `smax(smin(X, 0), -1) + 1` that is equal to `1` if `X`
is non-negative and is equal to 0 if `X` is negative. If we multiply `Begin, End` of safe
iteration space by this function calculated for `X = IRC.getEnd()`, we will get the original
`[Begin, End)` if `IRC.getEnd()` was non-negative (and, thus, `ClampedSubtract` worked
correctly) and the empty range `[0, 0)` in case if ` IRC.getEnd()` was negative.
So we in fact prohibit execution of the main loop if at least one of range checks was
made against a negative value (and we figured it out in runtime). It is still better than
what we have before (non-negativity had to be proved in compile time) and prevents
us from miscompile, however it is sometiles too restrictive for unsigned range checks
against a negative value (which in fact can be eliminated).
Once we re-implement `ClampedSubtract` in a way that it handles negative `X` correctly,
this limitation can be lifted, too.
Differential Revision: https://reviews.llvm.org/D46860
Reviewed By: samparker
llvm-svn: 332809
2018-05-19 21:06:37 +08:00
|
|
|
|
|
|
|
// This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
|
|
|
|
auto SCEVCheckNonNegative = [&](const SCEV *X) {
|
|
|
|
const Loop *L = IndVar->getLoop();
|
|
|
|
const SCEV *One = SE.getOne(X->getType());
|
|
|
|
// Can we trivially prove that X is a non-negative or negative value?
|
|
|
|
if (isKnownNonNegativeInLoop(X, L, SE))
|
|
|
|
return One;
|
|
|
|
else if (isKnownNegativeInLoop(X, L, SE))
|
|
|
|
return Zero;
|
|
|
|
// If not, we will have to figure it out during the execution.
|
|
|
|
// Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
|
|
|
|
const SCEV *NegOne = SE.getNegativeSCEV(One);
|
|
|
|
return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
|
|
|
|
};
|
|
|
|
// FIXME: Current implementation of ClampedSubtract implicitly assumes that
|
|
|
|
// X is non-negative (in sense of a signed value). We need to re-implement
|
|
|
|
// this function in a way that it will correctly handle negative X as well.
|
|
|
|
// We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
|
|
|
|
// end up with a negative X and produce wrong results. So currently we ensure
|
|
|
|
// that if getEnd() is negative then both ends of the safe range are zero.
|
|
|
|
// Note that this may pessimize elimination of unsigned range checks against
|
|
|
|
// negative values.
|
|
|
|
const SCEV *REnd = getEnd();
|
|
|
|
const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
|
|
|
|
|
|
|
|
const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
|
|
|
|
const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
|
2015-01-22 17:32:02 +08:00
|
|
|
return InductiveRangeCheck::Range(Begin, End);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2015-01-22 16:29:18 +08:00
|
|
|
static Optional<InductiveRangeCheck::Range>
|
2017-10-25 14:47:39 +08:00
|
|
|
IntersectSignedRange(ScalarEvolution &SE,
|
|
|
|
const Optional<InductiveRangeCheck::Range> &R1,
|
|
|
|
const InductiveRangeCheck::Range &R2) {
|
2017-10-25 14:10:02 +08:00
|
|
|
if (R2.isEmpty(SE, /* IsSigned */ true))
|
2017-10-11 14:53:07 +08:00
|
|
|
return None;
|
2017-10-19 13:33:28 +08:00
|
|
|
if (!R1.hasValue())
|
|
|
|
return R2;
|
2015-01-16 09:03:22 +08:00
|
|
|
auto &R1Value = R1.getValue();
|
2017-10-19 13:33:28 +08:00
|
|
|
// We never return empty ranges from this function, and R1 is supposed to be
|
|
|
|
// a result of intersection. Thus, R1 is never empty.
|
2017-10-25 14:10:02 +08:00
|
|
|
assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
|
|
|
|
"We should never have empty R1!");
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-01-22 16:29:18 +08:00
|
|
|
// TODO: we could widen the smaller range and have this work; but for now we
|
|
|
|
// bail out to keep things simple.
|
2015-01-22 17:32:02 +08:00
|
|
|
if (R1Value.getType() != R2.getType())
|
2015-01-22 16:29:18 +08:00
|
|
|
return None;
|
|
|
|
|
2015-02-22 06:07:32 +08:00
|
|
|
const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
|
|
|
|
const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
|
|
|
|
|
2017-10-11 14:53:07 +08:00
|
|
|
// If the resulting range is empty, just return None.
|
|
|
|
auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
|
2017-10-25 14:10:02 +08:00
|
|
|
if (Ret.isEmpty(SE, /* IsSigned */ true))
|
2017-10-11 14:53:07 +08:00
|
|
|
return None;
|
|
|
|
return Ret;
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
|
2017-10-25 14:47:39 +08:00
|
|
|
static Optional<InductiveRangeCheck::Range>
|
|
|
|
IntersectUnsignedRange(ScalarEvolution &SE,
|
|
|
|
const Optional<InductiveRangeCheck::Range> &R1,
|
|
|
|
const InductiveRangeCheck::Range &R2) {
|
|
|
|
if (R2.isEmpty(SE, /* IsSigned */ false))
|
|
|
|
return None;
|
|
|
|
if (!R1.hasValue())
|
|
|
|
return R2;
|
|
|
|
auto &R1Value = R1.getValue();
|
|
|
|
// We never return empty ranges from this function, and R1 is supposed to be
|
|
|
|
// a result of intersection. Thus, R1 is never empty.
|
|
|
|
assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
|
|
|
|
"We should never have empty R1!");
|
|
|
|
|
|
|
|
// TODO: we could widen the smaller range and have this work; but for now we
|
|
|
|
// bail out to keep things simple.
|
|
|
|
if (R1Value.getType() != R2.getType())
|
|
|
|
return None;
|
|
|
|
|
|
|
|
const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
|
|
|
|
const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
|
|
|
|
|
|
|
|
// If the resulting range is empty, just return None.
|
|
|
|
auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
|
|
|
|
if (Ret.isEmpty(SE, /* IsSigned */ false))
|
|
|
|
return None;
|
|
|
|
return Ret;
|
|
|
|
}
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM,
|
|
|
|
LoopStandardAnalysisResults &AR,
|
|
|
|
LPMUpdater &U) {
|
|
|
|
Function *F = L.getHeader()->getParent();
|
|
|
|
const auto &FAM =
|
|
|
|
AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
|
|
|
|
auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
|
|
|
|
InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI);
|
|
|
|
auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) {
|
|
|
|
if (!IsSubloop)
|
|
|
|
U.addSiblingLoops(NL);
|
|
|
|
};
|
|
|
|
bool Changed = IRCE.run(&L, LPMAddNewLoop);
|
|
|
|
if (!Changed)
|
|
|
|
return PreservedAnalyses::all();
|
|
|
|
|
|
|
|
return getLoopPassPreservedAnalyses();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
|
2016-05-04 06:32:30 +08:00
|
|
|
if (skipLoop(L))
|
|
|
|
return false;
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
|
|
|
|
BranchProbabilityInfo &BPI =
|
|
|
|
getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
|
|
|
|
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
|
|
|
|
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
|
|
|
|
InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
|
|
|
|
auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) {
|
|
|
|
LPM.addLoop(*NL);
|
|
|
|
};
|
|
|
|
return IRCE.run(L, LPMAddNewLoop);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool InductiveRangeCheckElimination::run(
|
|
|
|
Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
|
2015-01-16 09:03:22 +08:00
|
|
|
if (L->getBlocks().size() >= LoopSizeCutoff) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
|
2015-01-16 09:03:22 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
BasicBlock *Preheader = L->getLoopPreheader();
|
|
|
|
if (!Preheader) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
|
2015-01-16 09:03:22 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
LLVMContext &Context = Preheader->getContext();
|
2016-05-21 10:52:13 +08:00
|
|
|
SmallVector<InductiveRangeCheck, 16> RangeChecks;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
for (auto BBI : L->getBlocks())
|
|
|
|
if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
|
2016-05-26 08:09:02 +08:00
|
|
|
InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
|
|
|
|
RangeChecks);
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
if (RangeChecks.empty())
|
|
|
|
return false;
|
|
|
|
|
2015-03-17 09:40:22 +08:00
|
|
|
auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
|
|
|
|
OS << "irce: looking at loop "; L->print(OS);
|
|
|
|
OS << "irce: loop has " << RangeChecks.size()
|
|
|
|
<< " inductive range checks: \n";
|
2016-05-21 10:52:13 +08:00
|
|
|
for (InductiveRangeCheck &IRC : RangeChecks)
|
|
|
|
IRC.print(OS);
|
2015-03-17 09:40:22 +08:00
|
|
|
};
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
|
2015-03-17 09:40:22 +08:00
|
|
|
|
|
|
|
if (PrintRangeChecks)
|
|
|
|
PrintRecognizedRangeChecks(errs());
|
2015-01-16 09:03:22 +08:00
|
|
|
|
2015-02-26 16:19:31 +08:00
|
|
|
const char *FailureReason = nullptr;
|
|
|
|
Optional<LoopStructure> MaybeLoopStructure =
|
2015-02-26 16:56:04 +08:00
|
|
|
LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
|
2015-02-26 16:19:31 +08:00
|
|
|
if (!MaybeLoopStructure.hasValue()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
|
|
|
|
<< FailureReason << "\n";);
|
2015-02-26 16:19:31 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
LoopStructure LS = MaybeLoopStructure.getValue();
|
|
|
|
const SCEVAddRecExpr *IndVar =
|
2017-09-21 12:50:41 +08:00
|
|
|
cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
|
2015-02-26 16:19:31 +08:00
|
|
|
|
2015-01-16 09:03:22 +08:00
|
|
|
Optional<InductiveRangeCheck::Range> SafeIterRange;
|
|
|
|
Instruction *ExprInsertPt = Preheader->getTerminator();
|
|
|
|
|
2016-05-21 10:52:13 +08:00
|
|
|
SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
|
2017-10-25 14:47:39 +08:00
|
|
|
// Basing on the type of latch predicate, we interpret the IV iteration range
|
|
|
|
// as signed or unsigned range. We use different min/max functions (signed or
|
|
|
|
// unsigned) when intersecting this range with safe iteration ranges implied
|
|
|
|
// by range checks.
|
|
|
|
auto IntersectRange =
|
|
|
|
LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
IRBuilder<> B(ExprInsertPt);
|
2016-05-21 10:52:13 +08:00
|
|
|
for (InductiveRangeCheck &IRC : RangeChecks) {
|
[IRCE] Smart range intersection
In rL316552, we ban intersection of unsigned latch range with signed range check and vice
versa, unless the entire range check iteration space is known positive. It was a correct
functional fix that saved us from dealing with ambiguous values, but it also appeared
to be a very restrictive limitation. In particular, in the following case:
loop:
%iv = phi i32 [ 0, %preheader ], [ %iv.next, %latch]
%iv.offset = add i32 %iv, 10
%rc = icmp slt i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
Here, the unsigned iteration range is `[0, 100)`, and the safe range for range
check is `[-10, %len - 10)`. For unsigned iteration spaces, we use unsigned
min/max functions for range intersection. Given this, we wanted to avoid dealing
with `-10` because it is interpreted as a very big unsigned value. Semantically, range
check's safe range goes through unsigned border, so in fact it is two disjoint
ranges in IV's iteration space. Intersection of such ranges is not trivial, so we prohibited
this case saying that we are not allowed to intersect such ranges.
What semantics of this safe range actually means is that we can start from `-10` and go
up increasing the `%iv` by one until we reach `%len - 10` (for simplicity let's assume that
`%len - 10` is a reasonably big positive value).
In particular, this safe iteration space includes `0, 1, 2, ..., %len - 11`. So if we were able to return
safe iteration space `[0, %len - 10)`, we could safely intersect it with IV's iteration space. All
values in this range are non-negative, so using signed/unsigned min/max for them is unambiguous.
In this patch, we alter the algorithm of safe range calculation so that it returnes a subset of the
original safe space which is represented by one continuous range that does not go through wrap.
In order to reach this, we use modified SCEV substraction function. It can be imagined as a function
that substracts by `1` (or `-1`) as long as the further substraction does not cause a wrap in IV iteration
space. This allows us to perform IRCE in many situations when we deal with IV space and range check
of different types (in terms of signed/unsigned).
We apply this approach for both matching and not matching types of IV iteration space and the
range check. One implication of this is that now IRCE became smarter in detection of empty safe
ranges. For example, in this case:
loop:
%iv = phi i32 [ %begin, %preheader ], [ %iv.next, %latch]
%iv.offset = sub i32 %iv, 10
%rc = icmp ult i32 %iv.offset, %len
br i1 %rc, label %latch, label %deopt
latch:
%iv.next = add i32 %iv, 11
%cond = icmp i32 ult %iv.next, 100
br it %cond, label %loop, label %exit
If `%len` was less than 10 but SCEV failed to trivially prove that `%begin - 10 >u %len- 10`,
we could end up executing entire loop in safe preloop while the main loop was still generated,
but never executed. Now, cutting the ranges so that if both `begin - 10` and `%len - 10` overflow,
we have a trivially empty range of `[0, 0)`. This in some cases prevents us from meaningless optimization.
Differential Revision: https://reviews.llvm.org/D39954
llvm-svn: 318639
2017-11-20 14:07:57 +08:00
|
|
|
auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
|
|
|
|
LS.IsSignedPredicate);
|
2015-01-16 09:03:22 +08:00
|
|
|
if (Result.hasValue()) {
|
2015-01-22 16:29:18 +08:00
|
|
|
auto MaybeSafeIterRange =
|
2016-05-21 10:31:51 +08:00
|
|
|
IntersectRange(SE, SafeIterRange, Result.getValue());
|
2015-01-22 16:29:18 +08:00
|
|
|
if (MaybeSafeIterRange.hasValue()) {
|
2017-10-25 14:10:02 +08:00
|
|
|
assert(
|
|
|
|
!MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
|
|
|
|
"We should never return empty ranges!");
|
2015-01-22 16:29:18 +08:00
|
|
|
RangeChecksToEliminate.push_back(IRC);
|
|
|
|
SafeIterRange = MaybeSafeIterRange.getValue();
|
|
|
|
}
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!SafeIterRange.hasValue())
|
|
|
|
return false;
|
|
|
|
|
2018-03-15 19:01:19 +08:00
|
|
|
LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
|
|
|
|
SafeIterRange.getValue());
|
2015-01-16 09:03:22 +08:00
|
|
|
bool Changed = LC.run();
|
|
|
|
|
|
|
|
if (Changed) {
|
|
|
|
auto PrintConstrainedLoopInfo = [L]() {
|
|
|
|
dbgs() << "irce: in function ";
|
|
|
|
dbgs() << L->getHeader()->getParent()->getName() << ": ";
|
|
|
|
dbgs() << "constrained ";
|
|
|
|
L->print(dbgs());
|
|
|
|
};
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(PrintConstrainedLoopInfo());
|
2015-01-16 09:03:22 +08:00
|
|
|
|
|
|
|
if (PrintChangedLoops)
|
|
|
|
PrintConstrainedLoopInfo();
|
|
|
|
|
|
|
|
// Optimize away the now-redundant range checks.
|
|
|
|
|
2016-05-21 10:52:13 +08:00
|
|
|
for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
|
|
|
|
ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
|
2015-01-16 09:03:22 +08:00
|
|
|
? ConstantInt::getTrue(Context)
|
|
|
|
: ConstantInt::getFalse(Context);
|
2016-05-24 06:16:45 +08:00
|
|
|
IRC.getCheckUse()->set(FoldedRangeCheck);
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
|
|
|
Pass *llvm::createInductiveRangeCheckEliminationPass() {
|
2018-03-15 19:01:19 +08:00
|
|
|
return new IRCELegacyPass();
|
2015-01-16 09:03:22 +08:00
|
|
|
}
|