MLIR  20.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"
20 #include "mlir/IR/OpDefinition.h"
21 #include "mlir/Support/LLVM.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/SmallVectorExtras.h"
24 
25 namespace mlir {
26 
27 /// Return true if `v` is an IntegerAttr with value `0` of a ConstantIndexOp
28 /// with attribute with value `0`.
29 bool isZeroIndex(OpFoldResult v);
30 
31 /// Represents a range (offset, size, and stride) where each element of the
32 /// triple may be dynamic or static.
33 struct Range {
37 };
38 
39 /// Given an array of Range values, return a tuple of (offset vector, sizes
40 /// vector, and strides vector) formed by separating out the individual
41 /// elements of each range.
42 std::tuple<SmallVector<OpFoldResult>, SmallVector<OpFoldResult>,
45 
46 /// Helper function to dispatch an OpFoldResult into `staticVec` if:
47 /// a) it is an IntegerAttr
48 /// In other cases, the OpFoldResult is dispached to the `dynamicVec`.
49 /// In such dynamic cases, ShapedType::kDynamic is also pushed to
50 /// `staticVec`. This is useful to extract mixed static and dynamic entries
51 /// that come from an AttrSizedOperandSegments trait.
53  SmallVectorImpl<Value> &dynamicVec,
54  SmallVectorImpl<int64_t> &staticVec);
55 
56 /// Helper function to dispatch multiple OpFoldResults according to the
57 /// behavior of `dispatchIndexOpFoldResult(OpFoldResult ofr` for a single
58 /// OpFoldResult.
60  SmallVectorImpl<Value> &dynamicVec,
61  SmallVectorImpl<int64_t> &staticVec);
62 
63 /// Extract integer values from the assumed ArrayAttr of IntegerAttr.
64 template <typename IntTy>
66  return llvm::to_vector(
67  llvm::map_range(cast<ArrayAttr>(attr), [](Attribute a) -> IntTy {
68  return cast<IntegerAttr>(a).getInt();
69  }));
70 }
71 
72 /// Given a value, try to extract a constant Attribute. If this fails, return
73 /// the original value.
74 OpFoldResult getAsOpFoldResult(Value val);
75 /// Given an array of values, try to extract a constant Attribute from each
76 /// value. If this fails, return the original value.
77 SmallVector<OpFoldResult> getAsOpFoldResult(ValueRange values);
78 /// Convert `arrayAttr` to a vector of OpFoldResult.
79 SmallVector<OpFoldResult> getAsOpFoldResult(ArrayAttr arrayAttr);
80 
81 /// Convert int64_t to integer attributes of index type and return them as
82 /// OpFoldResult.
83 OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val);
84 SmallVector<OpFoldResult> getAsIndexOpFoldResult(MLIRContext *ctx,
85  ArrayRef<int64_t> values);
86 
87 /// If ofr is a constant integer or an IntegerAttr, return the integer.
88 std::optional<int64_t> getConstantIntValue(OpFoldResult ofr);
89 /// If all ofrs are constant integers or IntegerAttrs, return the integers.
90 std::optional<SmallVector<int64_t>>
91 getConstantIntValues(ArrayRef<OpFoldResult> ofrs);
92 
93 /// Return true if `ofr` is constant integer equal to `value`.
94 bool isConstantIntValue(OpFoldResult ofr, int64_t value);
95 /// Return true if all of `ofrs` are constant integers equal to `value`.
96 bool areAllConstantIntValue(ArrayRef<OpFoldResult> ofrs, int64_t value);
97 /// Return true if all of `ofrs` are constant integers equal to the
98 /// corresponding value in `values`.
99 bool areConstantIntValues(ArrayRef<OpFoldResult> ofrs,
100  ArrayRef<int64_t> values);
101 
102 /// Return true if ofr1 and ofr2 are the same integer constant attribute
103 /// values or the same SSA value. Ignore integer bitwitdh and type mismatch
104 /// that come from the fact there is no IndexAttr and that IndexType have no
105 /// bitwidth.
106 bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2);
107 bool isEqualConstantIntOrValueArray(ArrayRef<OpFoldResult> ofrs1,
108  ArrayRef<OpFoldResult> ofrs2);
109 
110 // To convert an OpFoldResult to a Value of index type, see:
111 // mlir/include/mlir/Dialect/Arith/Utils/Utils.h
112 // TODO: find a better common landing place.
113 //
114 // Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc,
115 // OpFoldResult ofr);
116 
117 // To convert an OpFoldResult to a Value of index type, see:
118 // mlir/include/mlir/Dialect/Arith/Utils/Utils.h
119 // TODO: find a better common landing place.
120 //
121 // SmallVector<Value>
122 // getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc,
123 // ArrayRef<OpFoldResult> valueOrAttrVec);
124 
125 /// Return a vector of OpFoldResults with the same size a staticValues, but
126 /// all elements for which ShapedType::isDynamic is true, will be replaced by
127 /// dynamicValues.
128 SmallVector<OpFoldResult> getMixedValues(ArrayRef<int64_t> staticValues,
129  ValueRange dynamicValues, Builder &b);
130 
131 /// Decompose a vector of mixed static or dynamic values into the
132 /// corresponding pair of arrays. This is the inverse function of
133 /// `getMixedValues`.
134 std::pair<SmallVector<int64_t>, SmallVector<Value>>
135 decomposeMixedValues(const SmallVectorImpl<OpFoldResult> &mixedValues);
136 
137 /// Helper to sort `values` according to matching `keys`.
138 SmallVector<Value>
139 getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<Value> values,
140  llvm::function_ref<bool(Attribute, Attribute)> compare);
141 SmallVector<OpFoldResult>
142 getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<OpFoldResult> values,
143  llvm::function_ref<bool(Attribute, Attribute)> compare);
144 SmallVector<int64_t>
145 getValuesSortedByKey(ArrayRef<Attribute> keys, ArrayRef<int64_t> values,
146  llvm::function_ref<bool(Attribute, Attribute)> compare);
147 
148 /// Helper function to check whether the passed in `sizes` or `offsets` are
149 /// valid. This can be used to re-check whether dimensions are still valid
150 /// after constant folding the dynamic dimensions.
151 bool hasValidSizesOffsets(SmallVector<int64_t> sizesOrOffsets);
152 
153 /// Helper function to check whether the passed in `strides` are valid. This
154 /// can be used to re-check whether dimensions are still valid after constant
155 /// folding the dynamic dimensions.
156 bool hasValidStrides(SmallVector<int64_t> strides);
157 
158 /// Returns "success" when any of the elements in `ofrs` is a constant value. In
159 /// that case the value is replaced by an attribute. Returns "failure" when no
160 /// folding happened. If `onlyNonNegative` and `onlyNonZero` are set, only
161 /// non-negative and non-zero constant values are folded respectively.
162 LogicalResult foldDynamicIndexList(SmallVectorImpl<OpFoldResult> &ofrs,
163  bool onlyNonNegative = false,
164  bool onlyNonZero = false);
165 
166 /// Returns "success" when any of the elements in `offsetsOrSizes` is a
167 /// constant value. In that case the value is replaced by an attribute. Returns
168 /// "failure" when no folding happened. Invalid values are not folded to avoid
169 /// canonicalization crashes.
170 LogicalResult
171 foldDynamicOffsetSizeList(SmallVectorImpl<OpFoldResult> &offsetsOrSizes);
172 
173 /// Returns "success" when any of the elements in `strides` is a constant
174 /// value. In that case the value is replaced by an attribute. Returns
175 /// "failure" when no folding happened. Invalid values are not folded to avoid
176 /// canonicalization crashes.
177 LogicalResult foldDynamicStrideList(SmallVectorImpl<OpFoldResult> &strides);
178 
179 /// Return the number of iterations for a loop with a lower bound `lb`, upper
180 /// bound `ub` and step `step`.
181 std::optional<int64_t> constantTripCount(OpFoldResult lb, OpFoldResult ub,
182  OpFoldResult step);
183 
184 /// Idiomatic saturated operations on values like offsets, sizes, and strides.
186  static SaturatedInteger wrap(int64_t v) {
187  return (ShapedType::isDynamic(v)) ? SaturatedInteger{true, 0}
188  : SaturatedInteger{false, v};
189  }
190  int64_t asInteger() { return saturated ? ShapedType::kDynamic : v; }
191  FailureOr<SaturatedInteger> desaturate(SaturatedInteger other) {
192  if (saturated && !other.saturated)
193  return other;
194  if (!saturated && !other.saturated && v != other.v)
195  return failure();
196  return *this;
197  }
199  return (saturated && other.saturated) ||
200  (!saturated && !other.saturated && v == other.v);
201  }
202  bool operator!=(SaturatedInteger other) { return !(*this == other); }
204  if (saturated || other.saturated)
205  return SaturatedInteger{true, 0};
206  return SaturatedInteger{false, other.v + v};
207  }
209  // Multiplication with 0 is always 0.
210  if (!other.saturated && other.v == 0)
211  return SaturatedInteger{false, 0};
212  if (!saturated && v == 0)
213  return SaturatedInteger{false, 0};
214  // Otherwise, if this or the other integer is dynamic, so is the result.
215  if (saturated || other.saturated)
216  return SaturatedInteger{true, 0};
217  return SaturatedInteger{false, other.v * v};
218  }
219  bool saturated = true;
220  int64_t v = 0;
221 };
222 
223 } // namespace mlir
224 
225 #endif // MLIR_DIALECT_UTILS_STATICVALUEUTILS_H
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
int compare(const Fraction &x, const Fraction &y)
Three-way comparison between two fractions.
Definition: Fraction.h:68
Include the generated interface declarations.
bool isConstantIntValue(OpFoldResult ofr, int64_t value)
Return true if ofr is constant integer equal to value.
bool isZeroIndex(OpFoldResult v)
Return true if v is an IntegerAttr with value 0 of a ConstantIndexOp with attribute with value 0.
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.
SmallVector< IntTy > extractFromIntegerArrayAttr(Attribute attr)
Extract integer values from the assumed ArrayAttr of IntegerAttr.
bool hasValidSizesOffsets(SmallVector< int64_t > sizesOrOffsets)
Helper function to check whether the passed in sizes or offsets are valid.
std::optional< int64_t > constantTripCount(OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
Return the number of iterations for a loop with a lower bound lb, upper bound ub and step step.
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...
std::pair< SmallVector< int64_t >, SmallVector< Value > > decomposeMixedValues(const SmallVectorImpl< OpFoldResult > &mixedValues)
Decompose a vector of mixed static or dynamic values into the corresponding pair of arrays.
bool isEqualConstantIntOrValueArray(ArrayRef< OpFoldResult > ofrs1, ArrayRef< OpFoldResult > ofrs2)
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, Builder &b)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
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::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.
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)
SaturatedInteger operator*(SaturatedInteger other)
FailureOr< SaturatedInteger > desaturate(SaturatedInteger other)
bool operator!=(SaturatedInteger other)
bool operator==(SaturatedInteger other)