MLIR 24.0.0git
VectorTransferSplitRewritePatterns.cpp
Go to the documentation of this file.
1//===- VectorTransferSplitRewritePatterns.cpp - Transfer Split Rewrites ---===//
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 implements target-independent patterns to rewrite a vector.transfer
10// op into a fully in-bounds part and a partial part.
11//
12//===----------------------------------------------------------------------===//
13
14#include <optional>
15
21#include "llvm/ADT/SmallVectorExtras.h"
22
26
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SmallVectorExtras.h"
29
30#define DEBUG_TYPE "vector-transfer-split"
31
32using namespace mlir;
33using namespace mlir::vector;
34
35/// Build the condition to ensure that a particular VectorTransferOpInterface
36/// is in-bounds.
38 VectorTransferOpInterface xferOp) {
39 assert(xferOp.getPermutationMap().isMinorIdentity() &&
40 "Expected minor identity map");
41 Value inBoundsCond;
42 xferOp.zipResultAndIndexing([&](int64_t resultIdx, int64_t indicesIdx) {
43 // Zip over the resulting vector shape and memref indices.
44 // If the dimension is known to be in-bounds, it does not participate in
45 // the construction of `inBoundsCond`.
46 if (xferOp.isDimInBounds(resultIdx))
47 return;
48 // Fold or create the check that `index + vector_size` <= `memref_size`.
49 Location loc = xferOp.getLoc();
50 int64_t vectorSize = xferOp.getVectorType().getDimSize(resultIdx);
52 b, loc, b.getAffineDimExpr(0) + b.getAffineConstantExpr(vectorSize),
53 {xferOp.getIndices()[indicesIdx]});
54 OpFoldResult dimSz =
55 memref::getMixedSize(b, loc, xferOp.getBase(), indicesIdx);
56 auto maybeCstSum = getConstantIntValue(sum);
57 auto maybeCstDimSz = getConstantIntValue(dimSz);
58 if (maybeCstSum && maybeCstDimSz && *maybeCstSum <= *maybeCstDimSz)
59 return;
60 Value cond =
61 arith::CmpIOp::create(b, loc, arith::CmpIPredicate::sle,
64 // Conjunction over all dims for which we are in-bounds.
65 if (inBoundsCond)
66 inBoundsCond = arith::AndIOp::create(b, loc, inBoundsCond, cond);
67 else
68 inBoundsCond = cond;
69 });
70 return inBoundsCond;
71}
72
73/// Split a vector.transfer operation into an in-bounds (i.e., no out-of-bounds
74/// masking) fast path and a slow path.
75/// If `ifOp` is not null and the result is `success, the `ifOp` points to the
76/// newly created conditional upon function return.
77/// To accommodate for the fact that the original vector.transfer indexing may
78/// be arbitrary and the slow path indexes @[0...0] in the temporary buffer, the
79/// scf.if op returns a view and values of type index.
80/// At this time, only vector.transfer_read case is implemented.
81///
82/// Example (a 2-D vector.transfer_read):
83/// ```
84/// %1 = vector.transfer_read %0[...], %pad : memref<A...>, vector<...>
85/// ```
86/// is transformed into:
87/// ```
88/// %1:3 = scf.if (%inBounds) {
89/// // fast path, direct cast
90/// memref.cast %A: memref<A...> to compatibleMemRefType
91/// scf.yield %view : compatibleMemRefType, index, index
92/// } else {
93/// // slow path, not in-bounds vector.transfer or memref.copy.
94/// memref.cast %alloc: memref<B...> to compatibleMemRefType
95/// scf.yield %4 : compatibleMemRefType, index, index
96// }
97/// %0 = vector.transfer_read %1#0[%1#1, %1#2] {in_bounds = [true ... true]}
98/// ```
99/// where `alloc` is a top of the function alloca'ed buffer of one vector.
100///
101/// Preconditions:
102/// 1. `xferOp.getPermutationMap()` must be a minor identity map
103/// 2. the rank of the `xferOp.memref()` and the rank of the
104/// `xferOp.getVector()` must be equal. This will be relaxed in the future
105/// but requires rank-reducing subviews.
106static LogicalResult
107splitFullAndPartialTransferPrecondition(VectorTransferOpInterface xferOp) {
108 // TODO: support 0-d corner case.
109 if (xferOp.getTransferRank() == 0)
110 return failure();
111
112 // TODO: expand support to these 2 cases.
113 if (!xferOp.getPermutationMap().isMinorIdentity())
114 return failure();
115 // Must have some out-of-bounds dimension to be a candidate for splitting.
116 if (!xferOp.hasOutOfBoundsDim())
117 return failure();
118 // Don't split transfer operations directly under IfOp, this avoids applying
119 // the pattern recursively.
120 // TODO: improve the filtering condition to make it more applicable.
121 if (isa<scf::IfOp>(xferOp->getParentOp()))
122 return failure();
123 // The split is not supported for transfers under an enclosing vector.mask.
124 if (cast<vector::MaskableOpInterface>(xferOp.getOperation()).isMasked())
125 return failure();
126 return success();
127}
128
129/// Given two MemRefTypes `aT` and `bT`, return a MemRefType to which both can
130/// be cast. If the MemRefTypes don't have the same rank or are not strided,
131/// return null; otherwise:
132/// 1. if `aT` and `bT` are cast-compatible, return `aT`.
133/// 2. else return a new MemRefType obtained by iterating over the shape and
134/// strides and:
135/// a. keeping the ones that are static and equal across `aT` and `bT`.
136/// b. using a dynamic shape and/or stride for the dimensions that don't
137/// agree.
138static MemRefType getCastCompatibleMemRefType(MemRefType aT, MemRefType bT) {
139 if (memref::CastOp::areCastCompatible(aT, bT))
140 return aT;
141 if (aT.getRank() != bT.getRank())
142 return MemRefType();
143 int64_t aOffset, bOffset;
144 SmallVector<int64_t, 4> aStrides, bStrides;
145 if (failed(aT.getStridesAndOffset(aStrides, aOffset)) ||
146 failed(bT.getStridesAndOffset(bStrides, bOffset)) ||
147 aStrides.size() != bStrides.size())
148 return MemRefType();
149
150 ArrayRef<int64_t> aShape = aT.getShape(), bShape = bT.getShape();
151 int64_t resOffset;
152 SmallVector<int64_t, 4> resShape(aT.getRank(), 0),
153 resStrides(bT.getRank(), 0);
154 for (int64_t idx = 0, e = aT.getRank(); idx < e; ++idx) {
155 resShape[idx] =
156 (aShape[idx] == bShape[idx]) ? aShape[idx] : ShapedType::kDynamic;
157 resStrides[idx] =
158 (aStrides[idx] == bStrides[idx]) ? aStrides[idx] : ShapedType::kDynamic;
159 }
160 resOffset = (aOffset == bOffset) ? aOffset : ShapedType::kDynamic;
161 return MemRefType::get(
162 resShape, aT.getElementType(),
163 StridedLayoutAttr::get(aT.getContext(), resOffset, resStrides));
164}
165
166/// Casts the given memref to a compatible memref type. If the source memref has
167/// a different address space than the target type, a `memref.memory_space_cast`
168/// is first inserted, followed by a `memref.cast`.
169static Value castToCompatibleMemRefType(OpBuilder &b, Value memref,
170 MemRefType compatibleMemRefType) {
171 MemRefType sourceType = cast<MemRefType>(memref.getType());
172 Value res = memref;
173 if (sourceType.getMemorySpace() != compatibleMemRefType.getMemorySpace()) {
174 sourceType = MemRefType::get(
175 sourceType.getShape(), sourceType.getElementType(),
176 sourceType.getLayout(), compatibleMemRefType.getMemorySpace());
177 res =
178 memref::MemorySpaceCastOp::create(b, memref.getLoc(), sourceType, res);
179 }
180 if (sourceType == compatibleMemRefType)
181 return res;
182 return memref::CastOp::create(b, memref.getLoc(), compatibleMemRefType, res);
183}
184
185/// Operates under a scoped context to build the intersection between the
186/// view `xferOp.getbase()` @ `xferOp.getIndices()` and the view `alloc`.
187// TODO: view intersection/union/differences should be a proper std op.
188static std::pair<Value, Value>
189createSubViewIntersection(RewriterBase &b, VectorTransferOpInterface xferOp,
190 Value alloc) {
191 Location loc = xferOp.getLoc();
192 int64_t memrefRank = xferOp.getShapedType().getRank();
193 // TODO: relax this precondition, will require rank-reducing subviews.
194 assert(memrefRank == cast<MemRefType>(alloc.getType()).getRank() &&
195 "Expected memref rank to match the alloc rank");
196 ValueRange leadingIndices =
197 xferOp.getIndices().take_front(xferOp.getLeadingShapedRank());
199 sizes.append(leadingIndices.begin(), leadingIndices.end());
200 auto isaWrite = isa<vector::TransferWriteOp>(xferOp);
201 xferOp.zipResultAndIndexing([&](int64_t resultIdx, int64_t indicesIdx) {
202 using MapList = ArrayRef<ArrayRef<AffineExpr>>;
203 Value dimMemRef =
204 memref::DimOp::create(b, xferOp.getLoc(), xferOp.getBase(), indicesIdx);
205 Value dimAlloc = memref::DimOp::create(b, loc, alloc, resultIdx);
206 Value index = xferOp.getIndices()[indicesIdx];
207 AffineExpr i, j, k;
208 bindDims(xferOp.getContext(), i, j, k);
210 AffineMap::inferFromExprList(MapList{{i - j, k}}, b.getContext());
211 // affine_min(%dimMemRef - %index, %dimAlloc)
212 Value affineMin =
213 affine::AffineMinOp::create(b, loc, index.getType(), maps[0],
214 ValueRange{dimMemRef, index, dimAlloc});
215 sizes.push_back(affineMin);
216 });
217
218 SmallVector<OpFoldResult> srcIndices = llvm::map_to_vector<4>(
219 xferOp.getIndices(), [](Value idx) -> OpFoldResult { return idx; });
220 SmallVector<OpFoldResult> destIndices(memrefRank, b.getIndexAttr(0));
221 SmallVector<OpFoldResult> strides(memrefRank, b.getIndexAttr(1));
222 auto copySrc = memref::SubViewOp::create(
223 b, loc, isaWrite ? alloc : xferOp.getBase(), srcIndices, sizes, strides);
224 auto copyDest = memref::SubViewOp::create(
225 b, loc, isaWrite ? xferOp.getBase() : alloc, destIndices, sizes, strides);
226 return std::make_pair(copySrc, copyDest);
227}
228
229/// Given an `xferOp` for which:
230/// 1. `inBoundsCond` and a `compatibleMemRefType` have been computed.
231/// 2. a memref of single vector `alloc` has been allocated.
232/// Produce IR resembling:
233/// ```
234/// %1:3 = scf.if (%inBounds) {
235/// (memref.memory_space_cast %A: memref<A..., addr_space> to memref<A...>)
236/// %view = memref.cast %A: memref<A...> to compatibleMemRefType
237/// scf.yield %view, ... : compatibleMemRefType, index, index
238/// } else {
239/// %2 = vector.broadcast %pad : elt to vector<...>
240/// %3 = vector.type_cast %alloc : memref<B...> to memref<vector<...>>
241/// memref.store %2, %3[] : memref<vector<...>>
242/// %4 = subview %view [...][...][...]
243/// %5 = subview %alloc [0, 0] [...] [...]
244/// memref.copy %4, %5
245/// %6 = memref.cast %alloc: memref<B...> to compatibleMemRefType
246/// scf.yield %6, ... : compatibleMemRefType, index, index
247/// }
248/// ```
249/// Return the produced scf::IfOp.
250static scf::IfOp
251createFullPartialMemRefCopy(RewriterBase &b, vector::TransferReadOp xferOp,
252 TypeRange returnTypes, Value inBoundsCond,
253 MemRefType compatibleMemRefType, Value alloc) {
254 Location loc = xferOp.getLoc();
255 Value zero = arith::ConstantIndexOp::create(b, loc, 0);
256 Value memref = xferOp.getBase();
257 return scf::IfOp::create(
258 b, loc, inBoundsCond,
259 [&](OpBuilder &b, Location loc) {
260 Value res = castToCompatibleMemRefType(b, memref, compatibleMemRefType);
261 scf::ValueVector viewAndIndices{res};
262 llvm::append_range(viewAndIndices, xferOp.getIndices());
263 scf::YieldOp::create(b, loc, viewAndIndices);
264 },
265 [&](OpBuilder &b, Location loc) {
266 // Fill the whole buffer with the padding value. The buffer holds
267 // exactly one vector, so a single vector store covers it.
268 Value padding = vector::BroadcastOp::create(
269 b, loc, xferOp.getVectorType(), xferOp.getPadding());
270 memref::StoreOp::create(
271 b, loc, padding,
272 vector::TypeCastOp::create(
273 b, loc, MemRefType::get({}, padding.getType()), alloc));
274 // Take partial subview of memref which guarantees no dimension
275 // overflows.
276 IRRewriter rewriter(b);
277 std::pair<Value, Value> copyArgs = createSubViewIntersection(
278 rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
279 alloc);
280 memref::CopyOp::create(b, loc, copyArgs.first, copyArgs.second);
281 Value casted =
282 castToCompatibleMemRefType(b, alloc, compatibleMemRefType);
283 scf::ValueVector viewAndIndices{casted};
284 viewAndIndices.insert(viewAndIndices.end(), xferOp.getTransferRank(),
285 zero);
286 scf::YieldOp::create(b, loc, viewAndIndices);
287 });
288}
289
290/// Given an `xferOp` for which:
291/// 1. `inBoundsCond` and a `compatibleMemRefType` have been computed.
292/// 2. a memref of single vector `alloc` has been allocated.
293/// Produce IR resembling:
294/// ```
295/// %1:3 = scf.if (%inBounds) {
296/// (memref.memory_space_cast %A: memref<A..., addr_space> to memref<A...>)
297/// memref.cast %A: memref<A...> to compatibleMemRefType
298/// scf.yield %view, ... : compatibleMemRefType, index, index
299/// } else {
300/// %2 = vector.transfer_read %view[...], %pad : memref<A...>, vector<...>
301/// %3 = vector.type_cast %extra_alloc :
302/// memref<...> to memref<vector<...>>
303/// store %2, %3[] : memref<vector<...>>
304/// %4 = memref.cast %alloc: memref<B...> to compatibleMemRefType
305/// scf.yield %4, ... : compatibleMemRefType, index, index
306/// }
307/// ```
308/// Return the produced scf::IfOp.
309static scf::IfOp createFullPartialVectorTransferRead(
310 RewriterBase &b, vector::TransferReadOp xferOp, TypeRange returnTypes,
311 Value inBoundsCond, MemRefType compatibleMemRefType, Value alloc) {
312 Location loc = xferOp.getLoc();
313 scf::IfOp fullPartialIfOp;
314 Value zero = arith::ConstantIndexOp::create(b, loc, 0);
315 Value memref = xferOp.getBase();
316 return scf::IfOp::create(
317 b, loc, inBoundsCond,
318 [&](OpBuilder &b, Location loc) {
319 Value res = castToCompatibleMemRefType(b, memref, compatibleMemRefType);
320 scf::ValueVector viewAndIndices{res};
321 llvm::append_range(viewAndIndices, xferOp.getIndices());
322 scf::YieldOp::create(b, loc, viewAndIndices);
323 },
324 [&](OpBuilder &b, Location loc) {
325 Operation *newXfer = b.clone(*xferOp.getOperation());
326 Value vector = cast<VectorTransferOpInterface>(newXfer).getVector();
327 memref::StoreOp::create(
328 b, loc, vector,
329 vector::TypeCastOp::create(
330 b, loc, MemRefType::get({}, vector.getType()), alloc));
331
332 Value casted =
333 castToCompatibleMemRefType(b, alloc, compatibleMemRefType);
334 scf::ValueVector viewAndIndices{casted};
335 viewAndIndices.insert(viewAndIndices.end(), xferOp.getTransferRank(),
336 zero);
337 scf::YieldOp::create(b, loc, viewAndIndices);
338 });
339}
340
341/// Given an `xferOp` for which:
342/// 1. `inBoundsCond` and a `compatibleMemRefType` have been computed.
343/// 2. a memref of single vector `alloc` has been allocated.
344/// Produce IR resembling:
345/// ```
346/// %1:3 = scf.if (%inBounds) {
347/// memref.cast %A: memref<A...> to compatibleMemRefType
348/// scf.yield %view, ... : compatibleMemRefType, index, index
349/// } else {
350/// %3 = vector.type_cast %extra_alloc :
351/// memref<...> to memref<vector<...>>
352/// %4 = memref.cast %alloc: memref<B...> to compatibleMemRefType
353/// scf.yield %4, ... : compatibleMemRefType, index, index
354/// }
355/// ```
356static ValueRange
357getLocationToWriteFullVec(RewriterBase &b, vector::TransferWriteOp xferOp,
358 TypeRange returnTypes, Value inBoundsCond,
359 MemRefType compatibleMemRefType, Value alloc) {
360 Location loc = xferOp.getLoc();
361 Value zero = arith::ConstantIndexOp::create(b, loc, 0);
362 Value memref = xferOp.getBase();
363 return scf::IfOp::create(
364 b, loc, inBoundsCond,
365 [&](OpBuilder &b, Location loc) {
366 Value res =
367 castToCompatibleMemRefType(b, memref, compatibleMemRefType);
368 scf::ValueVector viewAndIndices{res};
369 llvm::append_range(viewAndIndices, xferOp.getIndices());
370 scf::YieldOp::create(b, loc, viewAndIndices);
371 },
372 [&](OpBuilder &b, Location loc) {
373 Value casted =
374 castToCompatibleMemRefType(b, alloc, compatibleMemRefType);
375 scf::ValueVector viewAndIndices{casted};
376 viewAndIndices.insert(viewAndIndices.end(),
377 xferOp.getTransferRank(), zero);
378 scf::YieldOp::create(b, loc, viewAndIndices);
379 })
380 ->getResults();
381}
382
383/// Given an `xferOp` for which:
384/// 1. `inBoundsCond` has been computed.
385/// 2. a memref of single vector `alloc` has been allocated.
386/// 3. it originally wrote to %view
387/// Produce IR resembling:
388/// ```
389/// %notInBounds = arith.xori %inBounds, %true
390/// scf.if (%notInBounds) {
391/// %3 = subview %alloc [...][...][...]
392/// %4 = subview %view [0, 0][...][...]
393/// memref.copy %3, %4
394/// }
395/// ```
396static void createFullPartialMemRefCopy(RewriterBase &b,
397 vector::TransferWriteOp xferOp,
398 Value inBoundsCond, Value alloc) {
399 Location loc = xferOp.getLoc();
400 auto notInBounds = arith::XOrIOp::create(
401 b, loc, inBoundsCond, arith::ConstantIntOp::create(b, loc, true, 1));
402 scf::IfOp::create(b, loc, notInBounds, [&](OpBuilder &b, Location loc) {
403 IRRewriter rewriter(b);
404 std::pair<Value, Value> copyArgs = createSubViewIntersection(
405 rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
406 alloc);
407 memref::CopyOp::create(b, loc, copyArgs.first, copyArgs.second);
408 scf::YieldOp::create(b, loc, ValueRange{});
409 });
410}
411
412/// Given an `xferOp` for which:
413/// 1. `inBoundsCond` has been computed.
414/// 2. a memref of single vector `alloc` has been allocated.
415/// 3. it originally wrote to %view
416/// Produce IR resembling:
417/// ```
418/// %notInBounds = arith.xori %inBounds, %true
419/// scf.if (%notInBounds) {
420/// %2 = load %alloc : memref<vector<...>>
421/// vector.transfer_write %2, %view[...] : memref<A...>, vector<...>
422/// }
423/// ```
424static void createFullPartialVectorTransferWrite(RewriterBase &b,
425 vector::TransferWriteOp xferOp,
426 Value inBoundsCond,
427 Value alloc) {
428 Location loc = xferOp.getLoc();
429 auto notInBounds = arith::XOrIOp::create(
430 b, loc, inBoundsCond, arith::ConstantIntOp::create(b, loc, true, 1));
431 scf::IfOp::create(b, loc, notInBounds, [&](OpBuilder &b, Location loc) {
432 IRMapping mapping;
433 Value load = memref::LoadOp::create(
434 b, loc,
435 vector::TypeCastOp::create(
436 b, loc, MemRefType::get({}, xferOp.getVector().getType()), alloc),
437 ValueRange());
438 mapping.map(xferOp.getVector(), load);
439 b.clone(*xferOp.getOperation(), mapping);
440 scf::YieldOp::create(b, loc, ValueRange{});
441 });
442}
443
444// TODO: Parallelism and threadlocal considerations with a ParallelScope trait.
445static Operation *getAutomaticAllocationScope(Operation *op) {
446 // Find the closest surrounding allocation scope that is not a known looping
447 // construct (putting alloca's in loops doesn't always lower to deallocation
448 // until the end of the loop).
449 Operation *scope = nullptr;
450 for (Operation *parent = op->getParentOp(); parent != nullptr;
451 parent = parent->getParentOp()) {
452 if (parent->hasTrait<OpTrait::AutomaticAllocationScope>())
453 scope = parent;
454 if (!isa<scf::ForOp, affine::AffineForOp>(parent))
455 break;
456 }
457 assert(scope && "Expected op to be inside automatic allocation scope");
458 return scope;
459}
460
461/// Split a vector.transfer operation into an in-bounds (i.e., no out-of-bounds
462/// masking) fastpath and a slowpath.
463///
464/// For vector.transfer_read:
465/// If `ifOp` is not null and the result is `success, the `ifOp` points to the
466/// newly created conditional upon function return.
467/// To accomodate for the fact that the original vector.transfer indexing may be
468/// arbitrary and the slow path indexes @[0...0] in the temporary buffer, the
469/// scf.if op returns a view and values of type index.
470///
471/// Example (a 2-D vector.transfer_read):
472/// ```
473/// %1 = vector.transfer_read %0[...], %pad : memref<A...>, vector<...>
474/// ```
475/// is transformed into:
476/// ```
477/// %1:3 = scf.if (%inBounds) {
478/// // fastpath, direct cast
479/// memref.cast %A: memref<A...> to compatibleMemRefType
480/// scf.yield %view : compatibleMemRefType, index, index
481/// } else {
482/// // slowpath, not in-bounds vector.transfer or memref.copy.
483/// memref.cast %alloc: memref<B...> to compatibleMemRefType
484/// scf.yield %4 : compatibleMemRefType, index, index
485// }
486/// %0 = vector.transfer_read %1#0[%1#1, %1#2] {in_bounds = [true ... true]}
487/// ```
488/// where `alloc` is a top of the function alloca'ed buffer of one vector.
489///
490/// For vector.transfer_write:
491/// There are 2 conditional blocks. First a block to decide which memref and
492/// indices to use for an unmasked, inbounds write. Then a conditional block to
493/// further copy a partial buffer into the final result in the slow path case.
494///
495/// Example (a 2-D vector.transfer_write):
496/// ```
497/// vector.transfer_write %arg, %0[...], %pad : memref<A...>, vector<...>
498/// ```
499/// is transformed into:
500/// ```
501/// %1:3 = scf.if (%inBounds) {
502/// memref.cast %A: memref<A...> to compatibleMemRefType
503/// scf.yield %view : compatibleMemRefType, index, index
504/// } else {
505/// memref.cast %alloc: memref<B...> to compatibleMemRefType
506/// scf.yield %4 : compatibleMemRefType, index, index
507/// }
508/// %0 = vector.transfer_write %arg, %1#0[%1#1, %1#2] {in_bounds = [true ...
509/// true]}
510/// scf.if (%notInBounds) {
511/// // slowpath: not in-bounds vector.transfer or memref.copy.
512/// }
513/// ```
514/// where `alloc` is a top of the function alloca'ed buffer of one vector.
515///
516/// Preconditions:
517/// 1. `xferOp.getPermutationMap()` must be a minor identity map
518/// 2. the rank of the `xferOp.getBase()` and the rank of the
519/// `xferOp.getVector()` must be equal. This will be relaxed in the future
520/// but requires rank-reducing subviews.
521LogicalResult mlir::vector::splitFullAndPartialTransfer(
522 RewriterBase &b, VectorTransferOpInterface xferOp,
523 VectorTransformsOptions options, scf::IfOp *ifOp) {
524 if (options.vectorTransferSplit == VectorTransferSplit::None)
525 return failure();
526
527 SmallVector<bool, 4> bools(xferOp.getTransferRank(), true);
528 auto inBoundsAttr = b.getBoolArrayAttr(bools);
529 if (options.vectorTransferSplit == VectorTransferSplit::ForceInBounds) {
530 b.modifyOpInPlace(xferOp, [&]() {
531 xferOp->setInherentAttr(b.getStringAttr(xferOp.getInBoundsAttrName()),
532 inBoundsAttr);
533 });
534 return success();
535 }
536
537 // Assert preconditions. Additionally, keep the variables in an inner scope to
538 // ensure they aren't used in the wrong scopes further down.
539 {
540 assert(succeeded(splitFullAndPartialTransferPrecondition(xferOp)) &&
541 "Expected splitFullAndPartialTransferPrecondition to hold");
542
543 auto xferReadOp = dyn_cast<vector::TransferReadOp>(xferOp.getOperation());
544 auto xferWriteOp = dyn_cast<vector::TransferWriteOp>(xferOp.getOperation());
545
546 if (!(xferReadOp || xferWriteOp))
547 return failure();
548 if (xferWriteOp && xferWriteOp.getMask())
549 return failure();
550 if (xferReadOp && xferReadOp.getMask())
551 return failure();
552 }
553
555 b.setInsertionPoint(xferOp);
556 Value inBoundsCond = createInBoundsCond(
557 b, cast<VectorTransferOpInterface>(xferOp.getOperation()));
558 if (!inBoundsCond)
559 return failure();
560
561 // Top of the function `alloc` for transient storage.
562 Value alloc;
563 {
565 Operation *scope = getAutomaticAllocationScope(xferOp);
566 assert(scope->getNumRegions() == 1 &&
567 "AutomaticAllocationScope with >1 regions");
568 b.setInsertionPointToStart(&scope->getRegion(0).front());
569 auto shape = xferOp.getVectorType().getShape();
570 Type elementType = xferOp.getVectorType().getElementType();
571 alloc = memref::AllocaOp::create(b, scope->getLoc(),
572 MemRefType::get(shape, elementType),
573 ValueRange{}, b.getI64IntegerAttr(32));
574 }
575
576 MemRefType compatibleMemRefType =
577 getCastCompatibleMemRefType(cast<MemRefType>(xferOp.getShapedType()),
578 cast<MemRefType>(alloc.getType()));
579 if (!compatibleMemRefType)
580 return failure();
581
582 SmallVector<Type, 4> returnTypes(1 + xferOp.getTransferRank(),
583 b.getIndexType());
584 returnTypes[0] = compatibleMemRefType;
585
586 if (auto xferReadOp =
587 dyn_cast<vector::TransferReadOp>(xferOp.getOperation())) {
588 // Read case: full fill + partial copy -> in-bounds vector.xfer_read.
589 scf::IfOp fullPartialIfOp =
590 options.vectorTransferSplit == VectorTransferSplit::VectorTransfer
591 ? createFullPartialVectorTransferRead(b, xferReadOp, returnTypes,
592 inBoundsCond,
593 compatibleMemRefType, alloc)
594 : createFullPartialMemRefCopy(b, xferReadOp, returnTypes,
595 inBoundsCond, compatibleMemRefType,
596 alloc);
597 if (ifOp)
598 *ifOp = fullPartialIfOp;
599
600 // Set existing read op to in-bounds, it always reads from a full buffer.
601 for (unsigned i = 0, e = returnTypes.size(); i != e; ++i)
602 xferReadOp.setOperand(i, fullPartialIfOp.getResult(i));
603
604 b.modifyOpInPlace(xferOp, [&]() {
605 xferOp->setInherentAttr(b.getStringAttr(xferOp.getInBoundsAttrName()),
606 inBoundsAttr);
607 });
608
609 return success();
610 }
611
612 auto xferWriteOp = cast<vector::TransferWriteOp>(xferOp.getOperation());
613
614 // Decide which location to write the entire vector to.
615 auto memrefAndIndices = getLocationToWriteFullVec(
616 b, xferWriteOp, returnTypes, inBoundsCond, compatibleMemRefType, alloc);
617
618 // Do an in bounds write to either the output or the extra allocated buffer.
619 // The operation is cloned to prevent deleting information needed for the
620 // later IR creation.
621 IRMapping mapping;
622 mapping.map(xferWriteOp.getBase(), memrefAndIndices.front());
623 mapping.map(xferWriteOp.getIndices(), memrefAndIndices.drop_front());
624 auto *clone = b.clone(*xferWriteOp, mapping);
625 clone->setInherentAttr(xferWriteOp.getInBoundsAttrName(), inBoundsAttr);
626
627 // Create a potential copy from the allocated buffer to the final output in
628 // the slow path case.
629 if (options.vectorTransferSplit == VectorTransferSplit::VectorTransfer)
630 createFullPartialVectorTransferWrite(b, xferWriteOp, inBoundsCond, alloc);
631 else
632 createFullPartialMemRefCopy(b, xferWriteOp, inBoundsCond, alloc);
633
634 b.eraseOp(xferOp);
635
636 return success();
637}
638
639namespace {
640/// Apply `splitFullAndPartialTransfer` selectively via a pattern. This pattern
641/// may take an extra filter to perform selection at a finer granularity.
642struct VectorTransferFullPartialRewriter : public RewritePattern {
643 using FilterConstraintType =
644 std::function<LogicalResult(VectorTransferOpInterface op)>;
645
646 explicit VectorTransferFullPartialRewriter(
647 MLIRContext *context,
648 VectorTransformsOptions options = VectorTransformsOptions(),
649 FilterConstraintType filter =
650 [](VectorTransferOpInterface op) { return success(); },
651 PatternBenefit benefit = 1)
652 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), options(options),
653 filter(std::move(filter)) {}
654
655 /// Performs the rewrite.
656 LogicalResult matchAndRewrite(Operation *op,
657 PatternRewriter &rewriter) const override;
658
659private:
660 VectorTransformsOptions options;
661 FilterConstraintType filter;
662};
663
664} // namespace
665
666LogicalResult VectorTransferFullPartialRewriter::matchAndRewrite(
667 Operation *op, PatternRewriter &rewriter) const {
668 auto xferOp = dyn_cast<VectorTransferOpInterface>(op);
669 if (!xferOp || failed(splitFullAndPartialTransferPrecondition(xferOp)) ||
670 failed(filter(xferOp)))
671 return failure();
672 return splitFullAndPartialTransfer(rewriter, xferOp, options);
673}
674
677 patterns.add<VectorTransferFullPartialRewriter>(patterns.getContext(),
678 options);
679}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
auto load
static llvm::ManagedStatic< PassManagerOptions > options
static Value createInBoundsCond(RewriterBase &b, VectorTransferOpInterface xferOp)
Build the condition to ensure that a particular VectorTransferOpInterface is in-bounds.
Base type for affine expression.
Definition AffineExpr.h:68
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
A trait of region holding operations that define a new scope for automatic allocations,...
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Block & front()
Definition Region.h:65
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
RewritePattern is the common base class for all DAG to DAG replacements.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:335
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given memref value.
Definition MemRefOps.cpp:71
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< Value > ValueVector
An owning vector of values, handy to return from functions.
Definition SCF.h:59
void populateVectorTransferFullPartialPatterns(RewritePatternSet &patterns, const VectorTransformsOptions &options)
Populate patterns with the following patterns.
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
Structure to control the behavior of vector transform patterns.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.