MLIR 22.0.0git
StaticValueUtils.h
Go to the documentation of this file.
1//===- StaticValueUtils.h - Utilities for static values ---------*- 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 header file defines utilities for dealing with static values, e.g.,
10// converting back and forth between Value and OpFoldResult. Such functionality
11// is used in multiple dialects.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef MLIR_DIALECT_UTILS_STATICVALUEUTILS_H
16#define MLIR_DIALECT_UTILS_STATICVALUEUTILS_H
17
18#include "mlir/IR/Builders.h"
21#include "mlir/Support/LLVM.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/SmallVectorExtras.h"
24
25namespace mlir {
26
27/// Return "true" if `v` is an integer value/attribute with constant value `0`.
29
30/// Return "true" if `v` is a float value/attribute with constant value `0.0`.
32
33/// Return "true" if `v` is an integer/float value/attribute with constant
34/// value zero.
36
37/// Return true if `v` is an IntegerAttr with value `1`.
39
40/// Represents a range (offset, size, and stride) where each element of the
41/// triple may be dynamic or static.
47
48/// Given an array of Range values, return a tuple of (offset vector, sizes
49/// vector, and strides vector) formed by separating out the individual
50/// elements of each range.
51std::tuple<SmallVector<OpFoldResult>, SmallVector<OpFoldResult>,
54
55/// Helper function to dispatch an OpFoldResult into `staticVec` if:
56/// a) it is an IntegerAttr
57/// In other cases, the OpFoldResult is dispached to the `dynamicVec`.
58/// In such dynamic cases, ShapedType::kDynamic is also pushed to
59/// `staticVec`. This is useful to extract mixed static and dynamic entries
60/// that come from an AttrSizedOperandSegments trait.
62 SmallVectorImpl<Value> &dynamicVec,
63 SmallVectorImpl<int64_t> &staticVec);
64
65/// Helper function to dispatch multiple OpFoldResults according to the
66/// behavior of `dispatchIndexOpFoldResult(OpFoldResult ofr` for a single
67/// OpFoldResult.
69 SmallVectorImpl<Value> &dynamicVec,
70 SmallVectorImpl<int64_t> &staticVec);
71
72/// Given OpFoldResult representing dim size value (*), generates a pair of
73/// sizes:
74/// * 1st result, static value, contains an int64_t dim size that can be used
75/// to build ShapedType (ShapedType::kDynamic is used for truly dynamic dims),
76/// * 2nd result, dynamic value, contains OpFoldResult encapsulating the
77/// actual dim size (either original or updated input value).
78/// For input sizes for which it is possible to extract a constant Attribute,
79/// replaces the original size value with an integer attribute (unless it's
80/// already a constant Attribute). The 1st return value also becomes the actual
81/// integer size (as opposed ShapedType::kDynamic).
82///
83/// (*) This hook is usually used when, given input sizes as OpFoldResult,
84/// it's required to generate two vectors:
85/// * sizes as int64_t to generate a shape,
86/// * sizes as OpFoldResult for sizes-like attribute.
87/// Please update this comment if you identify other use cases.
88std::pair<int64_t, OpFoldResult>
90
91/// Extract integer values from the assumed ArrayAttr of IntegerAttr.
92template <typename IntTy>
94 return llvm::to_vector(
95 llvm::map_range(cast<ArrayAttr>(attr), [](Attribute a) -> IntTy {
96 return cast<IntegerAttr>(a).getInt();
97 }));
98}
99
100/// Given a value, try to extract a constant Attribute. If this fails, return
101/// the original value.
102OpFoldResult getAsOpFoldResult(Value val);
103/// Given an array of values, try to extract a constant Attribute from each
104/// value. If this fails, return the original value.
106/// Convert `arrayAttr` to a vector of OpFoldResult.
108
109/// Convert int64_t to integer attributes of index type and return them as
110/// OpFoldResult.
111OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val);
113 ArrayRef<int64_t> values);
114
115/// If ofr is a constant integer or an IntegerAttr, return the integer.
116/// The second return value indicates whether the value is an index type
117/// and thus the bitwidth is not defined (the APInt will be set with 64bits).
118std::optional<std::pair<APInt, bool>> getConstantAPIntValue(OpFoldResult ofr);
119/// If ofr is a constant integer or an IntegerAttr, return the integer.
120std::optional<int64_t> getConstantIntValue(OpFoldResult ofr);
121/// If all ofrs are constant integers or IntegerAttrs, return the integers.
122std::optional<SmallVector<int64_t>>
123getConstantIntValues(ArrayRef<OpFoldResult> ofrs);
124
125/// Return true if `ofr` is constant integer equal to `value`.
126bool isConstantIntValue(OpFoldResult ofr, int64_t value);
127/// Return true if all of `ofrs` are constant integers equal to `value`.
128bool areAllConstantIntValue(ArrayRef<OpFoldResult> ofrs, int64_t value);
129/// Return true if all of `ofrs` are constant integers equal to the
130/// corresponding value in `values`.
131bool areConstantIntValues(ArrayRef<OpFoldResult> ofrs,
132 ArrayRef<int64_t> values);
133
134/// Return true if ofr1 and ofr2 are the same integer constant attribute
135/// values or the same SSA value. Ignore integer bitwitdh and type mismatch
136/// that come from the fact there is no IndexAttr and that IndexType have no
137/// bitwidth.
138bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2);
139bool isEqualConstantIntOrValueArray(ArrayRef<OpFoldResult> ofrs1,
140 ArrayRef<OpFoldResult> ofrs2);
141
142// To convert an OpFoldResult to a Value of index type, see:
143// mlir/include/mlir/Dialect/Arith/Utils/Utils.h
144// TODO: find a better common landing place.
145//
146// Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc,
147// OpFoldResult ofr);
148
149// To convert an OpFoldResult to a Value of index type, see:
150// mlir/include/mlir/Dialect/Arith/Utils/Utils.h
151// TODO: find a better common landing place.
152//
153// SmallVector<Value>
154// getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc,
155// ArrayRef<OpFoldResult> valueOrAttrVec);
156
157/// Return a vector of OpFoldResults with the same size a staticValues, but
158/// all elements for which ShapedType::isDynamic is true, will be replaced by
159/// dynamicValues.
160SmallVector<OpFoldResult> getMixedValues(ArrayRef<int64_t> staticValues,
161 ValueRange dynamicValues,
162 MLIRContext *context);
163SmallVector<OpFoldResult> getMixedValues(ArrayRef<int64_t> staticValues,
164 ValueRange dynamicValues, Builder &b);
165
166/// Decompose a vector of mixed static or dynamic values into the
167/// corresponding pair of arrays. This is the inverse function of
168/// `getMixedValues`.
169std::pair<SmallVector<int64_t>, SmallVector<Value>>
170decomposeMixedValues(ArrayRef<OpFoldResult> mixedValues);
171
172/// Helper to sort `values` according to matching `keys`.
174getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<Value> values,
175 llvm::function_ref<bool(Attribute, Attribute)> compare);
177getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<OpFoldResult> values,
178 llvm::function_ref<bool(Attribute, Attribute)> compare);
180getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<int64_t> values,
181 llvm::function_ref<bool(Attribute, Attribute)> compare);
182
183/// Helper function to check whether the passed in `sizes` or `offsets` are
184/// valid. This can be used to re-check whether dimensions are still valid
185/// after constant folding the dynamic dimensions.
186bool hasValidSizesOffsets(SmallVector<int64_t> sizesOrOffsets);
187
188/// Helper function to check whether the passed in `strides` are valid. This
189/// can be used to re-check whether dimensions are still valid after constant
190/// folding the dynamic dimensions.
192
193/// Returns "success" when any of the elements in `ofrs` is a constant value. In
194/// that case the value is replaced by an attribute. Returns "failure" when no
195/// folding happened. If `onlyNonNegative` and `onlyNonZero` are set, only
196/// non-negative and non-zero constant values are folded respectively.
197LogicalResult foldDynamicIndexList(SmallVectorImpl<OpFoldResult> &ofrs,
198 bool onlyNonNegative = false,
199 bool onlyNonZero = false);
200
201/// Returns "success" when any of the elements in `offsetsOrSizes` is a
202/// constant value. In that case the value is replaced by an attribute. Returns
203/// "failure" when no folding happened. Invalid values are not folded to avoid
204/// canonicalization crashes.
205LogicalResult
206foldDynamicOffsetSizeList(SmallVectorImpl<OpFoldResult> &offsetsOrSizes);
207
208/// Returns "success" when any of the elements in `strides` is a constant
209/// value. In that case the value is replaced by an attribute. Returns
210/// "failure" when no folding happened. Invalid values are not folded to avoid
211/// canonicalization crashes.
212LogicalResult foldDynamicStrideList(SmallVectorImpl<OpFoldResult> &strides);
213
214/// Return the number of iterations for a loop with a lower bound `lb`, upper
215/// bound `ub` and step `step`. The `isSigned` flag indicates whether the loop
216/// comparison between lb and ub is signed or unsigned. A negative step or a
217/// lower bound greater than the upper bound are considered invalid and will
218/// yield a zero trip count.
219/// The `computeUbMinusLb` callback is invoked to compute the difference between
220/// the upper and lower bound when not constant. It can be used by the client
221/// to compute a static difference when the bounds are not constant.
222///
223/// For example, the following code:
224///
225/// %ub = arith.addi nsw %lb, %c16_i32 : i32
226/// %1 = scf.for %arg0 = %lb to %ub ...
227///
228/// where %ub is computed as a static offset from %lb.
229/// Note: the matched addition should be nsw/nuw (matching the loop comparison)
230/// to avoid overflow, otherwise an overflow would imply a zero trip count.
231std::optional<APInt> constantTripCount(
232 OpFoldResult lb, OpFoldResult ub, OpFoldResult step, bool isSigned,
233 llvm::function_ref<std::optional<llvm::APSInt>(Value, Value, bool)>
234 computeUbMinusLb);
235
236/// Idiomatic saturated operations on values like offsets, sizes, and strides.
239 return (ShapedType::isDynamic(v)) ? SaturatedInteger{true, 0}
240 : SaturatedInteger{false, v};
241 }
242 int64_t asInteger() { return saturated ? ShapedType::kDynamic : v; }
243 FailureOr<SaturatedInteger> desaturate(SaturatedInteger other) {
244 if (saturated && !other.saturated)
245 return other;
246 if (!saturated && !other.saturated && v != other.v)
247 return failure();
248 return *this;
249 }
251 return (saturated && other.saturated) ||
252 (!saturated && !other.saturated && v == other.v);
253 }
254 bool operator!=(SaturatedInteger other) { return !(*this == other); }
256 if (saturated || other.saturated)
257 return SaturatedInteger{true, 0};
258 return SaturatedInteger{false, other.v + v};
259 }
261 // Multiplication with 0 is always 0.
262 if (!other.saturated && other.v == 0)
263 return SaturatedInteger{false, 0};
264 if (!saturated && v == 0)
265 return SaturatedInteger{false, 0};
266 // Otherwise, if this or the other integer is dynamic, so is the result.
267 if (saturated || other.saturated)
268 return SaturatedInteger{true, 0};
269 return SaturatedInteger{false, other.v * v};
270 }
271 bool saturated = true;
273};
274
275} // namespace mlir
276
277#endif // MLIR_DIALECT_UTILS_STATICVALUEUTILS_H
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
This class represents a single result from folding an operation.
Include the generated interface declarations.
bool isConstantIntValue(OpFoldResult ofr, int64_t value)
Return true if ofr is constant integer equal to value.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
bool areConstantIntValues(ArrayRef< OpFoldResult > ofrs, ArrayRef< int64_t > values)
Return true if all of ofrs are constant integers equal to the corresponding value in values.
OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val)
Convert int64_t to integer attributes of index type and return them as OpFoldResult.
std::tuple< SmallVector< OpFoldResult >, SmallVector< OpFoldResult >, SmallVector< OpFoldResult > > getOffsetsSizesAndStrides(ArrayRef< Range > ranges)
Given an array of Range values, return a tuple of (offset vector, sizes vector, and strides vector) f...
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
LogicalResult foldDynamicStrideList(SmallVectorImpl< OpFoldResult > &strides)
Returns "success" when any of the elements in strides is a constant value.
bool areAllConstantIntValue(ArrayRef< OpFoldResult > ofrs, int64_t value)
Return true if all of ofrs are constant integers equal to value.
bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2)
Return true if ofr1 and ofr2 are the same integer constant attribute values or the same SSA value.
bool isZeroIntegerOrFloat(OpFoldResult v)
Return "true" if v is an integer/float value/attribute with constant value zero.
bool hasValidSizesOffsets(SmallVector< int64_t > sizesOrOffsets)
Helper function to check whether the passed in sizes or offsets are valid.
std::optional< std::pair< APInt, bool > > getConstantAPIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
bool hasValidStrides(SmallVector< int64_t > strides)
Helper function to check whether the passed in strides are valid.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
bool isEqualConstantIntOrValueArray(ArrayRef< OpFoldResult > ofrs1, ArrayRef< OpFoldResult > ofrs2)
void dispatchIndexOpFoldResult(OpFoldResult ofr, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch an OpFoldResult into staticVec if: a) it is an IntegerAttr In other cases...
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
std::pair< int64_t, OpFoldResult > getSimplifiedOfrAndStaticSizePair(OpFoldResult ofr, Builder &b)
Given OpFoldResult representing dim size value (*), generates a pair of sizes:
SmallVector< IntTy > extractFromIntegerArrayAttr(Attribute attr)
Extract integer values from the assumed ArrayAttr of IntegerAttr.
std::optional< SmallVector< int64_t > > getConstantIntValues(ArrayRef< OpFoldResult > ofrs)
If all ofrs are constant integers or IntegerAttrs, return the integers.
SmallVector< Value > getValuesSortedByKey(ArrayRef< Attribute > keys, ArrayRef< Value > values, llvm::function_ref< bool(Attribute, Attribute)> compare)
Helper to sort values according to matching keys.
LogicalResult foldDynamicOffsetSizeList(SmallVectorImpl< OpFoldResult > &offsetsOrSizes)
Returns "success" when any of the elements in offsetsOrSizes is a constant value.
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
std::optional< APInt > constantTripCount(OpFoldResult lb, OpFoldResult ub, OpFoldResult step, bool isSigned, llvm::function_ref< std::optional< llvm::APSInt >(Value, Value, bool)> computeUbMinusLb)
Return the number of iterations for a loop with a lower bound lb, upper bound ub and step step.
bool isZeroFloat(OpFoldResult v)
Return "true" if v is a float value/attribute with constant value 0.0.
std::pair< SmallVector< int64_t >, SmallVector< Value > > decomposeMixedValues(ArrayRef< OpFoldResult > mixedValues)
Decompose a vector of mixed static or dynamic values into the corresponding pair of arrays.
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
OpFoldResult stride
OpFoldResult size
OpFoldResult offset
Idiomatic saturated operations on values like offsets, sizes, and strides.
SaturatedInteger operator+(SaturatedInteger other)
static SaturatedInteger wrap(int64_t v)
FailureOr< SaturatedInteger > desaturate(SaturatedInteger other)
SaturatedInteger operator*(SaturatedInteger other)
bool operator!=(SaturatedInteger other)
bool operator==(SaturatedInteger other)