MLIR 24.0.0git
VectorMaskElimination.cpp
Go to the documentation of this file.
1//===- VectorMaskElimination.cpp - Eliminate Vector Masks -----------------===//
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
14
15namespace mlir {
16namespace vector {
17
18#define GEN_PASS_DEF_ELIMINATEVECTORMASKS
19#include "mlir/Dialect/Vector/Transforms/Passes.h.inc"
20
21} // namespace vector
22} // namespace mlir
23
24using namespace mlir;
25using namespace mlir::vector;
26namespace {
27/// Attempts to resolve a CreateMaskOp to an all-false constant mask. A single
28/// nonpositive dimension makes the whole mask all-false.
29LogicalResult resolveAllFalseCreateMaskOp(IRRewriter &rewriter,
30 vector::CreateMaskOp createMaskOp) {
31 SmallVector<Value> unknownDims;
32 bool allFalse = false;
33 for (Value dimSize : createMaskOp.getOperands()) {
34 std::optional<int64_t> size = getConstantIntValue(dimSize);
35 if (!size)
36 size = getConstantVscaleMultiplier(dimSize);
37 if (size) {
38 if (*size <= 0) {
39 allFalse = true;
40 break;
41 }
42 } else {
43 unknownDims.push_back(dimSize);
44 }
45 }
46
47 if (!allFalse) {
49 allFalse = llvm::any_of(unknownDims, [&](Value dimSize) {
51 dimSize, ValueBoundsConstraintSet::LE, zero);
52 });
53 }
54 if (!allFalse)
55 return failure();
56
57 auto allFalseMask = vector::ConstantMaskOp::create(
58 rewriter, createMaskOp.getLoc(), createMaskOp.getVectorType(),
60 rewriter.replaceAllUsesWith(createMaskOp, allFalseMask);
61 return success();
62}
63
64/// Attempts to resolve a CreateMaskOp to an all-true constant mask. All-true
65/// masks can then be eliminated by simple folds. `vscaleRange` is required to
66/// reason about scalable dimensions; without it only fixed-size dimensions can
67/// be proven all-true.
68LogicalResult
69resolveAllTrueCreateMaskOp(IRRewriter &rewriter,
70 vector::CreateMaskOp createMaskOp,
71 std::optional<VscaleRange> vscaleRange) {
72 auto maskType = createMaskOp.getVectorType();
73 auto maskTypeDimScalableFlags = maskType.getScalableDims();
74 auto maskTypeDimSizes = maskType.getShape();
75
76 // Special case: Rank zero shape.
77 constexpr std::array<int64_t, 1> rankZeroShape{1};
78 constexpr std::array<bool, 1> rankZeroScalableDims{false};
79 if (maskType.getRank() == 0) {
80 maskTypeDimSizes = rankZeroShape;
81 maskTypeDimScalableFlags = rankZeroScalableDims;
82 }
83
84 struct UnknownMaskDim {
85 size_t position;
86 Value dimSize;
87 };
88
89 // Loop over the CreateMaskOp operands and collect unknown dims (i.e. dims
90 // that are not obviously constant). If any constant dimension is not all-true
91 // bail out early (as this transform only trying to resolve all-true masks).
92 // This avoids doing value-bounds anaylis in cases like:
93 // `%mask = vector.create_mask %dynamicValue, %c2 : vector<8x4xi1>`
94 // ...where it is known the mask is not all-true by looking at `%c2`.
96 for (auto [i, dimSize] : llvm::enumerate(createMaskOp.getOperands())) {
97 if (auto intSize = getConstantIntValue(dimSize)) {
98 // Mask not all-true for this dim.
99 if (maskTypeDimScalableFlags[i] || intSize < maskTypeDimSizes[i])
100 return failure();
101 } else if (auto vscaleMultiplier = getConstantVscaleMultiplier(dimSize)) {
102 // Mask not all-true for this dim.
103 if (vscaleMultiplier < maskTypeDimSizes[i])
104 return failure();
105 } else {
106 // Unknown (without further analysis).
107 unknownDims.push_back(UnknownMaskDim{i, dimSize});
108 }
109 }
110
111 for (auto [i, dimSize] : unknownDims) {
112 // Compute the lower bound for the unknown dimension (i.e. the smallest
113 // value it could be).
114
115 // Fixed-width case: without a `vscale` range the bound is a plain constant,
116 // which can only prove a fixed-size dimension all-true.
117 if (!vscaleRange) {
118 // A constant bound cannot prove a scalable dim, whose runtime size is
119 // `vscale` times the size in the type. Checked first to skip the query.
120 if (maskTypeDimScalableFlags[i])
121 return failure();
122 FailureOr<int64_t> constantLowerBound =
125 if (failed(constantLowerBound))
126 return failure();
127 // If LB < the mask dim size then this dim is not all-true.
128 if (*constantLowerBound < maskTypeDimSizes[i])
129 return failure();
130 continue;
131 }
132
133 // Scalable case: with a `vscale` range the bound has the form
134 // `base + n * vscale`, which can prove either kind of dimension all-true.
135 FailureOr<ConstantOrScalableBound> dimLowerBound =
137 dimSize, {}, vscaleRange->vscaleMin, vscaleRange->vscaleMax,
139 if (failed(dimLowerBound))
140 return failure();
141 auto dimLowerBoundSize = dimLowerBound->getSize();
142 if (failed(dimLowerBoundSize))
143 return failure();
144 if (dimLowerBoundSize->scalable) {
145 // 1. The lower bound, LB, is scalable. If LB is < the mask dim size then
146 // this dim is not all-true.
147 if (dimLowerBoundSize->baseSize < maskTypeDimSizes[i])
148 return failure();
149 } else {
150 // 2. The lower bound, LB, is a constant.
151 // - If the mask dim size is scalable then this dim is not all-true.
152 if (maskTypeDimScalableFlags[i])
153 return failure();
154 // - If LB < the _fixed-size_ mask dim size then this dim is not all-true.
155 if (dimLowerBoundSize->baseSize < maskTypeDimSizes[i])
156 return failure();
157 }
158 }
159
160 // Replace createMaskOp with an all-true constant. This should result in the
161 // mask being removed in most cases (as xfer ops + vector.mask have folds to
162 // remove all-true masks).
163 auto allTrue = vector::ConstantMaskOp::create(
164 rewriter, createMaskOp.getLoc(), maskType, ConstantMaskKind::AllTrue);
165 rewriter.replaceAllUsesWith(createMaskOp, allTrue);
166 return success();
167}
168
169} // namespace
170
171namespace mlir::vector {
172
173void eliminateVectorMasks(IRRewriter &rewriter, FunctionOpInterface function,
174 std::optional<VscaleRange> vscaleRange) {
175 // Early exit for functions without a body.
176 if (function.isExternal())
177 return;
178
179 OpBuilder::InsertionGuard g(rewriter);
180
181 // Build worklist so we can safely insert new ops in the `resolve*` helpers.
183 function.walk([&](vector::CreateMaskOp createMaskOp) {
184 worklist.push_back(createMaskOp);
185 });
186
187 rewriter.setInsertionPointToStart(&function.front());
188 for (auto mask : worklist) {
189 if (succeeded(resolveAllTrueCreateMaskOp(rewriter, mask, vscaleRange)))
190 continue;
191 (void)resolveAllFalseCreateMaskOp(rewriter, mask);
192 }
193}
194
195namespace {
196struct EliminateVectorMasksPass
197 : public impl::EliminateVectorMasksBase<EliminateVectorMasksPass> {
198 using Base::Base;
199
200 // Checked here rather than in runOnOperation so that a bad range is reported
201 // once, not once per function.
202 LogicalResult initialize(MLIRContext *context) override {
203 bool unset = !vscaleMin && !vscaleMax;
204 bool valid = vscaleMin && vscaleMax && vscaleMin <= vscaleMax;
205 if (unset || valid)
206 return success();
207 return emitError(UnknownLoc::get(context))
208 << "invalid vscale range 'vscale-min="
209 << static_cast<unsigned>(vscaleMin)
210 << " vscale-max=" << static_cast<unsigned>(vscaleMax)
211 << "': expected both to be 0 (unknown), or both non-zero with "
212 "'vscale-min' <= 'vscale-max'";
213 }
214
215 void runOnOperation() override {
216 std::optional<VscaleRange> vscaleRange;
217 if (vscaleMin && vscaleMax)
218 vscaleRange = VscaleRange{vscaleMin, vscaleMax};
219
220 IRRewriter rewriter(&getContext());
221 eliminateVectorMasks(rewriter, getOperation(), vscaleRange);
222 }
223};
224} // namespace
225
226} // namespace mlir::vector
return success()
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
b getContext())
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
A variable that can be added to the constraint set as a "column".
static bool compare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
Return "true" if "lhs cmp rhs" was proven to hold.
static FailureOr< int64_t > computeConstantBound(presburger::BoundType type, const Variable &var, const StopConditionFn &stopCondition=nullptr, ValueBoundsOptions options={})
Compute a constant bound for the given variable.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
std::optional< int64_t > getConstantVscaleMultiplier(Value value)
If value is a constant multiple of vector.vscale (e.g.
void eliminateVectorMasks(IRRewriter &rewriter, FunctionOpInterface function, std::optional< VscaleRange > vscaleRange={})
Split a vector.transfer operation into an in-bounds (i.e., no out-of-bounds masking) fastpath and a s...
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
static FailureOr< ConstantOrScalableBound > computeScalableBound(Value value, std::optional< int64_t > dim, unsigned vscaleMin, unsigned vscaleMax, presburger::BoundType boundType, ValueBoundsOptions options={true}, const StopConditionFn &stopCondition=nullptr)
Computes a (possibly) scalable bound for a given value.