Skip to content

Commit 9344055

Browse files
committed
[MLIR] Fix VectorEmulateNarrowType constant op mask bug
This commit adds support for handling mask constants generated by the `arith.constant` op in the `VectorEmulateNarrowType` pattern. Previously, this pattern would not match due to the lack of mask constant handling in `getCompressedMaskOp`. The changes include: 1. Updating `getCompressedMaskOp` to recognize and handle `arith.constant` ops as mask value sources. 2. Handling cases where the mask is not aligned with the emulated load width. The compressed mask is adjusted to account for the offset. Limitations: - The arith.constant op can only have 1-dimensional constant values. Resolves: #115742 Signed-off-by: Alan Li <[email protected]>
1 parent 618f231 commit 9344055

File tree

3 files changed

+194
-59
lines changed

3 files changed

+194
-59
lines changed

mlir/lib/Dialect/Vector/Transforms/VectorEmulateNarrowType.cpp

Lines changed: 106 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -75,83 +75,132 @@ static FailureOr<Operation *> getCompressedMaskOp(OpBuilder &rewriter,
7575
int numSrcElemsPerDest,
7676
int numFrontPadElems = 0) {
7777

78-
assert(numFrontPadElems < numSrcElemsPerDest && "intraDataOffset must be less than scale");
78+
assert(numFrontPadElems < numSrcElemsPerDest &&
79+
"numFrontPadElems must be less than numSrcElemsPerDest");
7980

80-
auto numElements = (numFrontPadElems + numSrcElems + numSrcElemsPerDest - 1) /
81+
auto numDestElems = (numFrontPadElems + numSrcElems + numSrcElemsPerDest - 1) /
8182
numSrcElemsPerDest;
8283

8384
Operation *maskOp = mask.getDefiningOp();
8485
SmallVector<vector::ExtractOp, 2> extractOps;
86+
// TODO: add support to `vector.splat`.
8587
// Finding the mask creation operation.
86-
while (maskOp && !isa<vector::CreateMaskOp, vector::ConstantMaskOp>(maskOp)) {
88+
while (maskOp &&
89+
!isa<arith::ConstantOp, vector::CreateMaskOp, vector::ConstantMaskOp>(
90+
maskOp)) {
8791
if (auto extractOp = dyn_cast<vector::ExtractOp>(maskOp)) {
8892
maskOp = extractOp.getVector().getDefiningOp();
8993
extractOps.push_back(extractOp);
9094
}
9195
}
92-
auto createMaskOp = dyn_cast_or_null<vector::CreateMaskOp>(maskOp);
93-
auto constantMaskOp = dyn_cast_or_null<vector::ConstantMaskOp>(maskOp);
94-
if (!createMaskOp && !constantMaskOp)
96+
97+
if (!isa<arith::ConstantOp, vector::CreateMaskOp, vector::ConstantMaskOp>(
98+
maskOp))
9599
return failure();
96100

97101
// Computing the "compressed" mask. All the emulation logic (i.e. computing
98102
// new mask index) only happens on the last dimension of the vectors.
99-
Operation *newMask = nullptr;
100-
SmallVector<int64_t> shape(
103+
SmallVector<int64_t> maskShape(
101104
cast<VectorType>(maskOp->getResultTypes()[0]).getShape());
102-
shape.back() = numElements;
103-
auto newMaskType = VectorType::get(shape, rewriter.getI1Type());
104-
if (createMaskOp) {
105-
OperandRange maskOperands = createMaskOp.getOperands();
106-
size_t numMaskOperands = maskOperands.size();
107-
AffineExpr s0;
108-
bindSymbols(rewriter.getContext(), s0);
109-
s0 = s0 + numSrcElemsPerDest - 1;
110-
s0 = s0.floorDiv(numSrcElemsPerDest);
111-
OpFoldResult origIndex =
112-
getAsOpFoldResult(maskOperands[numMaskOperands - 1]);
113-
OpFoldResult maskIndex =
114-
affine::makeComposedFoldedAffineApply(rewriter, loc, s0, origIndex);
115-
SmallVector<Value> newMaskOperands(maskOperands.drop_back());
116-
newMaskOperands.push_back(
117-
getValueOrCreateConstantIndexOp(rewriter, loc, maskIndex));
118-
newMask = rewriter.create<vector::CreateMaskOp>(loc, newMaskType,
119-
newMaskOperands);
120-
} else if (constantMaskOp) {
121-
ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
122-
size_t numMaskOperands = maskDimSizes.size();
123-
int64_t origIndex = maskDimSizes[numMaskOperands - 1];
124-
int64_t startIndex = numFrontPadElems / numSrcElemsPerDest;
125-
int64_t maskIndex =
126-
llvm::divideCeil(numFrontPadElems + origIndex, numSrcElemsPerDest);
127-
128-
// TODO: we only want the mask between [startIndex, maskIndex] to be true,
129-
// the rest are false.
130-
if (numFrontPadElems != 0 && maskDimSizes.size() > 1)
131-
return failure();
132-
133-
SmallVector<int64_t> newMaskDimSizes(maskDimSizes.drop_back());
134-
newMaskDimSizes.push_back(maskIndex);
135-
136-
if (numFrontPadElems == 0) {
137-
newMask = rewriter.create<vector::ConstantMaskOp>(loc, newMaskType,
138-
newMaskDimSizes);
139-
} else {
140-
SmallVector<bool> newMaskValues;
141-
for (int64_t i = 0; i < numElements; ++i)
142-
newMaskValues.push_back(i >= startIndex && i < maskIndex);
143-
auto denseAttr = DenseElementsAttr::get(newMaskType, newMaskValues);
144-
newMask = rewriter.create<arith::ConstantOp>(loc, newMaskType, denseAttr);
145-
}
146-
}
105+
maskShape.back() = numDestElems;
106+
auto newMaskType = VectorType::get(maskShape, rewriter.getI1Type());
107+
std::optional<Operation *> newMask =
108+
TypeSwitch<Operation *, std::optional<Operation *>>(maskOp)
109+
.Case<vector::CreateMaskOp>(
110+
[&](auto createMaskOp) -> std::optional<Operation *> {
111+
OperandRange maskOperands = createMaskOp.getOperands();
112+
size_t numMaskOperands = maskOperands.size();
113+
AffineExpr s0;
114+
bindSymbols(rewriter.getContext(), s0);
115+
s0 = s0 + numSrcElemsPerDest - 1;
116+
s0 = s0.floorDiv(numSrcElemsPerDest);
117+
OpFoldResult origIndex =
118+
getAsOpFoldResult(maskOperands[numMaskOperands - 1]);
119+
OpFoldResult maskIndex = affine::makeComposedFoldedAffineApply(
120+
rewriter, loc, s0, origIndex);
121+
SmallVector<Value> newMaskOperands(maskOperands.drop_back());
122+
newMaskOperands.push_back(
123+
getValueOrCreateConstantIndexOp(rewriter, loc, maskIndex));
124+
return rewriter.create<vector::CreateMaskOp>(loc, newMaskType,
125+
newMaskOperands);
126+
})
127+
.Case<vector::ConstantMaskOp>([&](auto constantMaskOp)
128+
-> std::optional<Operation *> {
129+
ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
130+
size_t numMaskOperands = maskDimSizes.size();
131+
int64_t origIndex = maskDimSizes[numMaskOperands - 1];
132+
int64_t startIndex = numFrontPadElems / numSrcElemsPerDest;
133+
int64_t maskIndex = llvm::divideCeil(numFrontPadElems + origIndex,
134+
numSrcElemsPerDest);
135+
136+
// TODO: we only want the mask between [startIndex, maskIndex]
137+
// to be true, the rest are false.
138+
if (numFrontPadElems != 0 && maskDimSizes.size() > 1)
139+
return std::nullopt;
140+
141+
SmallVector<int64_t> newMaskDimSizes(maskDimSizes.drop_back());
142+
newMaskDimSizes.push_back(maskIndex);
143+
144+
if (numFrontPadElems == 0)
145+
return rewriter.create<vector::ConstantMaskOp>(loc, newMaskType,
146+
newMaskDimSizes);
147+
148+
SmallVector<bool> newMaskValues;
149+
for (int64_t i = 0; i < numDestElems; ++i)
150+
newMaskValues.push_back(i >= startIndex && i < maskIndex);
151+
auto denseAttr = DenseElementsAttr::get(newMaskType, newMaskValues);
152+
return rewriter.create<arith::ConstantOp>(loc, newMaskType,
153+
denseAttr);
154+
})
155+
.Case<arith::ConstantOp>([&](auto constantOp)
156+
-> std::optional<Operation *> {
157+
// TODO: Support multiple dimensions.
158+
if (maskShape.size() != 1)
159+
return std::nullopt;
160+
// Rearrange the original mask values to cover the whole potential
161+
// loading region. For example, in the case of using byte-size for
162+
// emulation, given the following mask:
163+
//
164+
// %mask = [0, 1, 0, 1, 0, 0]
165+
//
166+
// With front offset of 1, the mask will be padded 0s in the front
167+
// and back so that:
168+
// 1. It is aligned with the effective loading bits
169+
// 2. Its length is multiple of `numSrcElemPerDest` (and the total
170+
// coverage size is mulitiple of bytes). The new mask will be like
171+
// this before compressing:
172+
//
173+
// %new_mask = [0, 0, 1, 0, 1, 0, 0, 0]
174+
auto denseAttr =
175+
cast<DenseIntElementsAttr>(constantOp.getValue());
176+
SmallVector<bool> paddedMaskValues(numFrontPadElems, false);
177+
paddedMaskValues.append(denseAttr.template value_begin<bool>(),
178+
denseAttr.template value_end<bool>());
179+
paddedMaskValues.resize(numDestElems * numSrcElemsPerDest, false);
180+
181+
// Compressing by combining every `numSrcElemsPerDest` elements:
182+
SmallVector<bool> compressedMaskValues;
183+
for (size_t i = 0; i < paddedMaskValues.size(); i += numSrcElemsPerDest) {
184+
bool combinedValue = false;
185+
for (int j = 0; j < numSrcElemsPerDest; ++j) {
186+
combinedValue |= paddedMaskValues[i + j];
187+
}
188+
compressedMaskValues.push_back(combinedValue);
189+
}
190+
return rewriter.create<arith::ConstantOp>(
191+
loc, DenseElementsAttr::get(newMaskType, compressedMaskValues));
192+
});
193+
194+
if (!newMask)
195+
return failure();
147196

148197
while (!extractOps.empty()) {
149198
newMask = rewriter.create<vector::ExtractOp>(
150-
loc, newMask->getResults()[0], extractOps.back().getMixedPosition());
199+
loc, (*newMask)->getResults()[0], extractOps.back().getMixedPosition());
151200
extractOps.pop_back();
152201
}
153202

154-
return newMask;
203+
return *newMask;
155204
}
156205

157206
/// Extracts 1-D subvector from a 1-D vector. It is a wrapper function for
@@ -185,12 +234,10 @@ static Value staticallyExtractSubvector(OpBuilder &rewriter, Location loc,
185234
/// `vector.insert_strided_slice`.
186235
static Value staticallyInsertSubvector(OpBuilder &rewriter, Location loc,
187236
Value src, Value dest, int64_t offset) {
188-
auto srcType = cast<VectorType>(src.getType());
189-
auto destType = cast<VectorType>(dest.getType());
237+
[[maybe_unused]] auto srcType = cast<VectorType>(src.getType());
238+
[[maybe_unused]] auto destType = cast<VectorType>(dest.getType());
190239
assert(srcType.getRank() == 1 && destType.getRank() == 1 &&
191240
"expected source and dest to be vector type");
192-
(void)srcType;
193-
(void)destType;
194241
auto offsets = rewriter.getI64ArrayAttr({offset});
195242
auto strides = rewriter.getI64ArrayAttr({1});
196243
return rewriter.create<vector::InsertStridedSliceOp>(loc, dest.getType(), src,

mlir/test/Dialect/Vector/vector-emulate-narrow-type-unaligned.mlir

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,41 @@ func.func @vector_maskedload_i2_dynamic_indexing_mixed(%passthru: vector<3xi2>,
249249
// CHECK: %[[IN8:.+]] = vector.insert %[[EX8]], %[[IN7]] [1] : i2 into vector<3xi2>
250250
// CHECK: %[[EX9:.+]] = vector.extract %[[SELECT]][%[[INCIDX2]]] : i2 from vector<8xi2>
251251
// CHECK: %[[IN9:.+]] = vector.insert %[[EX9]], %[[IN8]] [2] : i2 into vector<3xi2>
252+
253+
// -----
254+
255+
func.func @vector_maskedload_i4_constant_mask_unaligned(%passthru: vector<5xi2>) -> vector<5xi2> {
256+
%0 = memref.alloc() : memref<3x5xi2>
257+
%mask = arith.constant dense<[false, true, true, true, false]> : vector<5xi1>
258+
%c0 = arith.constant 0 : index
259+
%c1 = arith.constant 1 : index
260+
%1 = vector.maskedload %0[%c1, %c0], %mask, %passthru :
261+
memref<3x5xi2>, vector<5xi1>, vector<5xi2> into vector<5xi2>
262+
return %1 : vector<5xi2>
263+
}
264+
265+
// CHECK: func @vector_maskedload_i4_constant_mask_unaligned(
266+
// CHECK-SAME: %[[PTH:.+]]: vector<5xi2>) -> vector<5xi2>
267+
// CHECK: %[[ALLOC:.+]] = memref.alloc() : memref<4xi8>
268+
// CHECK: %[[MASK:.+]] = arith.constant dense<[false, true, true, true, false]> : vector<5xi1>
269+
270+
// CHECK: %[[COMPRESSED_MASK:.+]] = arith.constant dense<true> : vector<2xi1>
271+
// CHECK: %[[EMPTY:.+]] = arith.constant dense<0> : vector<8xi2>
272+
// CHECK: %[[PTH_PADDED:.+]] = vector.insert_strided_slice %[[PTH]], %[[EMPTY]]
273+
// CHECK-SAME: {offsets = [1], strides = [1]} : vector<5xi2> into vector<8xi2>
274+
275+
// Emulated masked load from alloc:
276+
// CHECK: %[[PTH_PADDED_UPCAST:.+]] = vector.bitcast %[[PTH_PADDED]] : vector<8xi2> to vector<2xi8>
277+
// CHECK: %[[C1:.+]] = arith.constant 1 : index
278+
// CHECK: %[[MASKLOAD:.+]] = vector.maskedload %[[ALLOC]][%[[C1]]], %[[COMPRESSED_MASK]], %[[PTH_PADDED_UPCAST]]
279+
// CHECK: %[[MASKLOAD_DOWNCAST:.+]] = vector.bitcast %[[MASKLOAD]] : vector<2xi8> to vector<8xi2>
280+
281+
// Select from emulated loaded vector and passthru vector:
282+
// TODO: fold this part if possible.
283+
// CHECK: %[[EMPTY_MASK:.+]] = arith.constant dense<false> : vector<8xi1>
284+
// CHECK: %[[MASK_PADDED:.+]] = vector.insert_strided_slice %[[MASK]], %[[EMPTY_MASK]]
285+
// CHECK-SAME: {offsets = [1], strides = [1]} : vector<5xi1> into vector<8xi1>
286+
// CHECK: %[[SELECT:.+]] = arith.select %[[MASK_PADDED]], %[[MASKLOAD_DOWNCAST]], %[[PTH_PADDED]] : vector<8xi1>, vector<8xi2>
287+
// CHECK: %[[RESULT:.+]] = vector.extract_strided_slice %[[SELECT]]
288+
// CHECK-SAME: {offsets = [1], sizes = [5], strides = [1]} : vector<8xi2> to vector<5xi2>
289+
// CHECK: return %[[RESULT]] : vector<5xi2>

mlir/test/Dialect/Vector/vector-emulate-narrow-type.mlir

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,30 @@ func.func @vector_maskedload_i4_constant_mask(%arg1: index, %arg2: index, %passt
275275

276276
// -----
277277

278+
func.func @vector_maskedload_i4_arith_constant(%passthru: vector<8xi4>) -> vector<8xi4> {
279+
%0 = memref.alloc() : memref<3x8xi4>
280+
%cst = arith.constant dense<0> : vector<8xi4>
281+
%mask = arith.constant dense<[false, true, true, true, true, false, false, false]> : vector<8xi1>
282+
%c0 = arith.constant 0 : index
283+
%1 = vector.maskedload %0[%c0, %c0], %mask, %passthru :
284+
memref<3x8xi4>, vector<8xi1>, vector<8xi4> into vector<8xi4>
285+
return %1 : vector<8xi4>
286+
}
287+
288+
// CHECK: func @vector_maskedload_i4_arith_constant(
289+
// CHECK-SAME: %[[PASSTHRU:[a-zA-Z0-9]+]]
290+
// CHECK: %[[ALLOC:.+]] = memref.alloc() : memref<12xi8>
291+
// CHECK: %[[MASK:.+]] = arith.constant dense<[false, true, true, true, true, false, false, false]> : vector<8xi1>
292+
293+
// Emit a new, compressed mask for emulated maskedload:
294+
// CHECK: %[[COMPRESSED_MASK:.+]] = arith.constant dense<[true, true, true, false]> : vector<4xi1>
295+
// CHECK: %[[PTHU_UPCAST:.+]] = vector.bitcast %[[PASSTHRU]] : vector<8xi4> to vector<4xi8>
296+
// CHECK: %[[C0:.+]] = arith.constant 0 : index
297+
// CHECK: %[[LOAD:.+]] = vector.maskedload %[[ALLOC]][%[[C0]]], %[[COMPRESSED_MASK]], %[[PTHU_UPCAST]]
298+
// CHECK: %[[LOAD_DOWNCAST:.+]] = vector.bitcast %[[LOAD]] : vector<4xi8> to vector<8xi4>
299+
// CHECK: %[[SELECT:.+]] = arith.select %[[MASK]], %[[LOAD_DOWNCAST]], %[[PASSTHRU]] : vector<8xi1>, vector<8xi4>
300+
// CHECK: return %[[SELECT]] : vector<8xi4>
301+
278302
///----------------------------------------------------------------------------------------
279303
/// vector.extract -> vector.masked_load
280304
///----------------------------------------------------------------------------------------
@@ -624,3 +648,29 @@ func.func @vector_maskedstore_i4_constant_mask(
624648
// CHECK32: %[[SELECT:.+]] = arith.select %[[ORIG_MASK]], %[[VAL_TO_STORE]], %[[BITCAST]] : vector<8xi1>, vector<8xi4>
625649
// CHECK32: %[[NEW_VAL:.+]] = vector.bitcast %[[SELECT]] : vector<8xi4> to vector<1xi32>
626650
// CHECK32: vector.maskedstore %[[ALLOC]]{{\[}}%[[LIDX]]], %[[NEW_MASK]], %[[NEW_VAL]] : memref<3xi32>, vector<1xi1>, vector<1xi32>
651+
652+
// -----
653+
654+
func.func @vector_maskedstore_i4_arith_constant(%val_to_store: vector<8xi4>) {
655+
%0 = memref.alloc() : memref<5x8xi4>
656+
%cst = arith.constant dense<0> : vector<8xi4>
657+
%mask = arith.constant dense<[false, true, true, true, true, true, false, false]> : vector<8xi1>
658+
%c0 = arith.constant 0 : index
659+
%c3 = arith.constant 3 : index
660+
vector.maskedstore %0[%c3, %c0], %mask, %val_to_store :
661+
memref<5x8xi4>, vector<8xi1>, vector<8xi4>
662+
return
663+
}
664+
665+
// CHECK-LABEL: func @vector_maskedstore_i4_arith_constant
666+
// CHECK-SAME: %[[VAL_TO_STORE:[a-zA-Z0-9]+]]:
667+
// CHECK: %[[ALLOC:.+]] = memref.alloc() : memref<20xi8>
668+
// CHECK: %[[MASK:.+]] = arith.constant dense<[false, true, true, true, true, true, false, false]> : vector<8xi1>
669+
// CHECK: %[[C12:.+]] = arith.constant 12 : index
670+
// CHECK: %[[COMPRESSED_MASK:.+]] = arith.constant dense<[true, true, true, false]> : vector<4xi1>
671+
// CHECK: %[[EMPTY:.+]] = arith.constant dense<0> : vector<4xi8>
672+
// CHECK: %[[MASKEDLOAD:.+]] = vector.maskedload %[[ALLOC]][%[[C12]]], %[[COMPRESSED_MASK]], %[[EMPTY]]
673+
// CHECK: %[[LOAD_UPCAST:.+]] = vector.bitcast %[[MASKEDLOAD]]
674+
// CHECK: %[[SELECT:.+]] = arith.select %[[MASK]], %[[VAL_TO_STORE]], %[[LOAD_UPCAST]]
675+
// CHECK: %[[SELECT_DOWNCAST:.+]] = vector.bitcast %[[SELECT]]
676+
// CHECK: vector.maskedstore %[[ALLOC]][%[[C12]]], %[[COMPRESSED_MASK]], %[[SELECT_DOWNCAST]]

0 commit comments

Comments
 (0)