LLVM 24.0.0git
ScalarEvolutionDivision.cpp
Go to the documentation of this file.
1//===- ScalarEvolutionDivision.h - See below --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the class that knows how to divide SCEV's.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/DenseMap.h"
21#include <cassert>
22#include <cstdint>
23
24#define DEBUG_TYPE "scev-division"
25
26namespace llvm {
27class Type;
28} // namespace llvm
29
30using namespace llvm;
31
32static inline int sizeOfSCEV(const SCEV *S) {
33 struct FindSCEVSize {
34 int Size = 0;
35
36 FindSCEVSize() = default;
37
38 bool follow(const SCEV *S) {
39 ++Size;
40 // Keep looking at all operands of S.
41 return true;
42 }
43
44 bool isDone() const { return false; }
45 };
46
47 FindSCEVSize F;
49 ST.visitAll(S);
50 return F.Size;
51}
52
53// Computes the Quotient and Remainder of the division of Numerator by
54// Denominator.
55void SCEVDivision::divide(ScalarEvolution &SE, const SCEV *Numerator,
56 const SCEV *Denominator, const SCEV **Quotient,
57 const SCEV **Remainder) {
58 assert(Numerator && Denominator && "Uninitialized SCEV");
59 assert(Numerator->getType() == Denominator->getType() &&
60 "Numerator and Denominator must have the same type");
61
62 SCEVDivision D(SE, Numerator, Denominator);
63
64 // Check for the trivial case here to avoid having to check for it in the
65 // rest of the code.
66 if (Numerator == Denominator) {
67 *Quotient = D.One;
68 *Remainder = D.Zero;
69 return;
70 }
71
72 if (Numerator->isZero()) {
73 *Quotient = D.Zero;
74 *Remainder = D.Zero;
75 return;
76 }
77
78 // A simple case when N/1. The quotient is N.
79 if (Denominator->isOne()) {
80 *Quotient = Numerator;
81 *Remainder = D.Zero;
82 return;
83 }
84
85 // Split the Denominator when it is a product.
86 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
87 const SCEV *Q, *R;
88 *Quotient = Numerator;
89 for (const SCEV *Op : T->operands()) {
90 divide(SE, *Quotient, Op, &Q, &R);
91 *Quotient = Q;
92
93 // Bail out when the Numerator is not divisible by one of the terms of
94 // the Denominator.
95 if (!R->isZero()) {
96 *Quotient = D.Zero;
97 *Remainder = Numerator;
98 return;
99 }
100 }
101 *Remainder = D.Zero;
102 return;
103 }
104
105 D.visit(Numerator);
106 *Quotient = D.Quotient;
107 *Remainder = D.Remainder;
108}
109
111 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
112 APInt NumeratorVal = Numerator->getAPInt();
113 APInt DenominatorVal = D->getAPInt();
114 assert(NumeratorVal.getBitWidth() == DenominatorVal.getBitWidth() &&
115 "Numerator and Denominator must have the same bit width");
116
117 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
118 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
119 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
120 Quotient = SE.getConstant(QuotientVal);
121 Remainder = SE.getConstant(RemainderVal);
122 return;
123 }
124}
125
126void SCEVDivision::visitVScale(const SCEVVScale *Numerator) {
127 return cannotDivide(Numerator);
128}
129
131 const SCEV *StartQ, *StartR, *StepQ, *StepR;
132 if (!Numerator->isAffine())
133 return cannotDivide(Numerator);
134 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
135 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
136 // Bail out if the types do not match.
137 Type *Ty = Denominator->getType();
138 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
139 Ty != StepQ->getType() || Ty != StepR->getType())
140 return cannotDivide(Numerator);
141
142 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
143 SCEV::NoWrapFlags::FlagAnyWrap);
144 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
145 SCEV::NoWrapFlags::FlagAnyWrap);
146}
147
150 Type *Ty = Denominator->getType();
151
152 for (const SCEV *Op : Numerator->operands()) {
153 const SCEV *Q, *R;
154 divide(SE, Op, Denominator, &Q, &R);
155
156 // Bail out if types do not match.
157 if (Ty != Q->getType() || Ty != R->getType())
158 return cannotDivide(Numerator);
159
160 Qs.push_back(Q);
161 Rs.push_back(R);
162 }
163
164 if (Qs.size() == 1) {
165 Quotient = Qs[0];
166 Remainder = Rs[0];
167 return;
168 }
169
170 Quotient = SE.getAddExpr(Qs);
171 Remainder = SE.getAddExpr(Rs);
172}
173
176 Type *Ty = Denominator->getType();
177
178 bool FoundDenominatorTerm = false;
179 for (const SCEV *Op : Numerator->operands()) {
180 // Bail out if types do not match.
181 if (Ty != Op->getType())
182 return cannotDivide(Numerator);
183
184 if (FoundDenominatorTerm) {
185 Qs.push_back(Op);
186 continue;
187 }
188
189 // Check whether Denominator divides one of the product operands.
190 const SCEV *Q, *R;
191 divide(SE, Op, Denominator, &Q, &R);
192 if (!R->isZero()) {
193 Qs.push_back(Op);
194 continue;
195 }
196
197 // Bail out if types do not match.
198 if (Ty != Q->getType())
199 return cannotDivide(Numerator);
200
201 FoundDenominatorTerm = true;
202 Qs.push_back(Q);
203 }
204
205 if (FoundDenominatorTerm) {
206 Remainder = Zero;
207 if (Qs.size() == 1)
208 Quotient = Qs[0];
209 else
210 Quotient = SE.getMulExpr(Qs);
211 return;
212 }
213
214 if (!isa<SCEVUnknown>(Denominator))
215 return cannotDivide(Numerator);
216
217 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
218 ValueToSCEVMapTy RewriteMap;
219 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = Zero;
220 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap);
221
222 if (Remainder->isZero()) {
223 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
224 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = One;
225 Quotient = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap);
226 return;
227 }
228
229 // Quotient is (Numerator - Remainder) divided by Denominator.
230 const SCEV *Q, *R;
231 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
232 // This SCEV does not seem to simplify: fail the division here.
233 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
234 return cannotDivide(Numerator);
235 divide(SE, Diff, Denominator, &Q, &R);
236 if (R != Zero)
237 return cannotDivide(Numerator);
238 Quotient = Q;
239}
240
241SCEVDivision::SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
242 const SCEV *Denominator)
243 : SE(S), Denominator(Denominator) {
244 Zero = SE.getZero(Denominator->getType());
245 One = SE.getOne(Denominator->getType());
246
247 // We generally do not know how to divide Expr by Denominator. We initialize
248 // the division to a "cannot divide" state to simplify the rest of the code.
249 cannotDivide(Numerator);
250}
251
252// Convenience function for giving up on the division. We set the quotient to
253// be equal to zero and the remainder to be equal to the numerator.
254void SCEVDivision::cannotDivide(const SCEV *Numerator) {
255 Quotient = Zero;
256 Remainder = Numerator;
257}
258
259void SCEVDivisionPrinterPass::runImpl(Function &F, ScalarEvolution &SE) {
260 OS << "Printing analysis 'Scalar Evolution Division' for function '"
261 << F.getName() << "':\n";
262 for (Instruction &Inst : instructions(F)) {
263 BinaryOperator *Div = dyn_cast<BinaryOperator>(&Inst);
264 if (!Div || Div->getOpcode() != Instruction::SDiv)
265 continue;
266
267 const SCEV *Numerator = SE.getSCEV(Div->getOperand(0));
268 const SCEV *Denominator = SE.getSCEV(Div->getOperand(1));
269 const SCEV *Quotient, *Remainder;
270 SCEVDivision::divide(SE, Numerator, Denominator, &Quotient, &Remainder);
271
272 OS << "Instruction: " << *Div << "\n";
273 OS.indent(2) << "Numerator: " << *Numerator << "\n";
274 OS.indent(2) << "Denominator: " << *Denominator << "\n";
275 OS.indent(2) << "Quotient: " << *Quotient << "\n";
276 OS.indent(2) << "Remainder: " << *Remainder << "\n";
277 }
278}
279
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
Expand Atomic instructions
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
static int sizeOfSCEV(const SCEV *S)
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition APInt.h:78
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1925
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
const APInt & getAPInt() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This node represents multiplication of some number of SCEVs.
ArrayRef< SCEVUse > operands() const
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
Visit all nodes in the expression tree using worklist traversal.
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Value * getOperand(unsigned i) const
Definition User.h:207
This is an optimization pass for GlobalISel generic memory operations.
DenseMap< const Value *, const SCEV * > ValueToSCEVMapTy
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static LLVM_ABI void divide(ScalarEvolution &SE, const SCEV *Numerator, const SCEV *Denominator, const SCEV **Quotient, const SCEV **Remainder)
Computes the Quotient and Remainder of the division of Numerator by Denominator.
LLVM_ABI void visitVScale(const SCEVVScale *Numerator)
LLVM_ABI void visitAddRecExpr(const SCEVAddRecExpr *Numerator)
LLVM_ABI void visitConstant(const SCEVConstant *Numerator)
LLVM_ABI void visitAddExpr(const SCEVAddExpr *Numerator)
LLVM_ABI void visitMulExpr(const SCEVMulExpr *Numerator)